context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) 2002 Ville Palo
// (C) 2003 Martin Willemoes Hansen
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using Xunit;
using System.Xml;
using System.Data.SqlTypes;
using System.Globalization;
using System.Xml.Serialization;
using System.IO;
namespace System.Data.Tests.SqlTypes
{
public class SqlDecimalTest : IDisposable
{
private CultureInfo _originalCulture;
private SqlDecimal _test1;
private SqlDecimal _test2;
private SqlDecimal _test3;
private SqlDecimal _test4;
private SqlDecimal _test5;
public SqlDecimalTest()
{
_originalCulture = CultureInfo.CurrentCulture; ;
CultureInfo.CurrentCulture = new CultureInfo("en-US");
_test1 = new SqlDecimal(6464.6464m);
_test2 = new SqlDecimal(10000.00m);
_test3 = new SqlDecimal(10000.00m);
_test4 = new SqlDecimal(-6m);
_test5 = new SqlDecimal(decimal.MaxValue);
}
public void Dispose()
{
CultureInfo.CurrentCulture = _originalCulture;
}
// Test constructor
[Fact]
public void Create()
{
// SqlDecimal (decimal)
SqlDecimal Test = new SqlDecimal(30.3098m);
Assert.Equal((decimal)30.3098, Test.Value);
try
{
decimal d = decimal.MaxValue;
SqlDecimal test = new SqlDecimal(d + 1);
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// SqlDecimal (double)
Test = new SqlDecimal(10E+10d);
Assert.Equal(100000000000.00000m, Test.Value);
try
{
SqlDecimal test = new SqlDecimal(10E+200d);
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// SqlDecimal (int)
Test = new SqlDecimal(-1);
Assert.Equal(-1m, Test.Value);
// SqlDecimal (long)
Test = new SqlDecimal((long)(-99999));
Assert.Equal(-99999m, Test.Value);
// SqlDecimal (byte, byte, bool. int[]
Test = new SqlDecimal(10, 3, false, new int[4] { 200, 1, 0, 0 });
Assert.Equal(-4294967.496m, Test.Value);
try
{
Test = new SqlDecimal(100, 100, false,
new int[4] {int.MaxValue,
int.MaxValue, int.MaxValue,
int.MaxValue});
Assert.False(true);
}
catch (SqlTypeException)
{
}
// sqlDecimal (byte, byte, bool, int, int, int, int)
Test = new SqlDecimal(12, 2, true, 100, 100, 0, 0);
Assert.Equal(4294967297.00m, Test.Value);
try
{
Test = new SqlDecimal(100, 100, false,
int.MaxValue,
int.MaxValue, int.MaxValue,
int.MaxValue);
Assert.False(true);
}
catch (SqlTypeException)
{
}
}
// Test public fields
[Fact]
public void PublicFields()
{
Assert.Equal((byte)38, SqlDecimal.MaxPrecision);
Assert.Equal((byte)38, SqlDecimal.MaxScale);
// FIXME: on windows: Conversion overflow
Assert.Equal(1262177448, SqlDecimal.MaxValue.Data[3]);
Assert.Equal(1262177448, SqlDecimal.MinValue.Data[3]);
Assert.True(SqlDecimal.Null.IsNull);
Assert.True(!_test1.IsNull);
}
// Test properties
[Fact]
public void Properties()
{
byte[] b = _test1.BinData;
Assert.Equal((byte)64, b[0]);
int[] i = _test1.Data;
Assert.Equal(64646464, i[0]);
Assert.True(SqlDecimal.Null.IsNull);
Assert.True(_test1.IsPositive);
Assert.True(!_test4.IsPositive);
Assert.Equal((byte)8, _test1.Precision);
Assert.Equal((byte)2, _test2.Scale);
Assert.Equal(6464.6464m, _test1.Value);
Assert.Equal((byte)4, _test1.Scale);
Assert.Equal((byte)7, _test2.Precision);
Assert.Equal((byte)1, _test4.Precision);
}
// PUBLIC METHODS
[Fact]
public void ArithmeticMethods()
{
// Abs
Assert.Equal(6m, SqlDecimal.Abs(_test4));
Assert.Equal(new SqlDecimal(6464.6464m).Value, SqlDecimal.Abs(_test1).Value);
Assert.Equal(SqlDecimal.Null, SqlDecimal.Abs(SqlDecimal.Null));
// Add()
SqlDecimal test2 = new SqlDecimal(-2000m);
Assert.Equal(16464.6464m, SqlDecimal.Add(_test1, _test2).Value);
Assert.Equal("158456325028528675187087900670", SqlDecimal.Add(_test5, _test5).ToString());
Assert.Equal(9994.00m, SqlDecimal.Add(_test3, _test4));
Assert.Equal(-2006m, SqlDecimal.Add(_test4, test2));
Assert.Equal(8000.00m, SqlDecimal.Add(test2, _test3));
try
{
SqlDecimal test = SqlDecimal.Add(SqlDecimal.MaxValue, SqlDecimal.MaxValue);
Assert.False(true);
}
catch (OverflowException)
{
}
Assert.Equal(6465m, SqlDecimal.Ceiling(_test1));
Assert.Equal(SqlDecimal.Null, SqlDecimal.Ceiling(SqlDecimal.Null));
// Divide() => Notworking
/*
Assert.Equal ((SqlDecimal)(-1077.441066m), SqlDecimal.Divide (Test1, Test4));
Assert.Equal (1.54687501546m, SqlDecimal.Divide (Test2, Test1).Value);
try {
SqlDecimal test = SqlDecimal.Divide(Test1, new SqlDecimal(0)).Value;
Assert.False(true);
} catch (DivideByZeroException e) {
Assert.Equal (typeof (DivideByZeroException), e.GetType ());
}
*/
Assert.Equal(6464m, SqlDecimal.Floor(_test1));
// Multiply()
SqlDecimal Test;
SqlDecimal test1 = new SqlDecimal(2m);
Assert.Equal(64646464.000000m, SqlDecimal.Multiply(_test1, _test2).Value);
Assert.Equal(-38787.8784m, SqlDecimal.Multiply(_test1, _test4).Value);
Test = SqlDecimal.Multiply(_test5, test1);
Assert.Equal("158456325028528675187087900670", Test.ToString());
try
{
SqlDecimal test = SqlDecimal.Multiply(SqlDecimal.MaxValue, _test1);
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// Power => NotWorking
//Assert.Equal ((SqlDecimal)41791653.0770m, SqlDecimal.Power (Test1, 2));
// Round
Assert.Equal(6464.65m, SqlDecimal.Round(_test1, 2));
// Subtract()
Assert.Equal(-3535.3536m, SqlDecimal.Subtract(_test1, _test3).Value);
Assert.Equal(10006.00m, SqlDecimal.Subtract(_test3, _test4).Value);
Assert.Equal("99999999920771837485735662406456049664", SqlDecimal.Subtract(SqlDecimal.MaxValue, decimal.MaxValue).ToString());
try
{
SqlDecimal test = SqlDecimal.Subtract(SqlDecimal.MinValue, SqlDecimal.MaxValue);
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
Assert.Equal(1, SqlDecimal.Sign(_test1));
Assert.Equal(new SqlInt32(-1), SqlDecimal.Sign(_test4));
}
[Fact]
public void AdjustScale()
{
Assert.Equal("6464.646400", SqlDecimal.AdjustScale(_test1, 2, false).Value.ToString());
Assert.Equal("6464.65", SqlDecimal.AdjustScale(_test1, -2, true).Value.ToString());
Assert.Equal("6464.64", SqlDecimal.AdjustScale(_test1, -2, false).Value.ToString());
Assert.Equal("10000.000000000000", SqlDecimal.AdjustScale(_test2, 10, false).Value.ToString());
Assert.Equal("79228162514264337593543950335.00", SqlDecimal.AdjustScale(_test5, 2, false).ToString());
try
{
SqlDecimal test = SqlDecimal.AdjustScale(_test1, -5, false);
Assert.False(true);
}
catch (SqlTruncateException)
{
}
}
[Fact]
public void ConvertToPrecScale()
{
Assert.Equal(new SqlDecimal(6464.6m).Value, SqlDecimal.ConvertToPrecScale(_test1, 5, 1).Value);
try
{
SqlDecimal test = SqlDecimal.ConvertToPrecScale(_test1, 6, 4);
Assert.False(true);
}
catch (SqlTruncateException e)
{
Assert.Equal(typeof(SqlTruncateException), e.GetType());
}
Assert.Equal("10000.00", SqlDecimal.ConvertToPrecScale(_test2, 7, 2).ToSqlString());
SqlDecimal tmp = new SqlDecimal(38, 4, true, 64646464, 0, 0, 0);
Assert.Equal("6465", SqlDecimal.ConvertToPrecScale(tmp, 4, 0).ToString());
}
[Fact]
public void CompareTo()
{
SqlString TestString = new SqlString("This is a test");
Assert.True(_test1.CompareTo(_test3) < 0);
Assert.True(_test2.CompareTo(_test1) > 0);
Assert.True(_test2.CompareTo(_test3) == 0);
Assert.True(_test4.CompareTo(SqlDecimal.Null) > 0);
try
{
_test1.CompareTo(TestString);
Assert.False(true);
}
catch (ArgumentException e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
}
}
[Fact]
public void EqualsMethods()
{
Assert.True(!_test1.Equals(_test2));
Assert.True(!_test2.Equals(new SqlString("TEST")));
Assert.True(_test2.Equals(_test3));
// Static Equals()-method
Assert.True(SqlDecimal.Equals(_test2, _test2).Value);
Assert.True(!SqlDecimal.Equals(_test1, _test2).Value);
// NotEquals
Assert.True(SqlDecimal.NotEquals(_test1, _test2).Value);
Assert.True(SqlDecimal.NotEquals(_test4, _test1).Value);
Assert.True(!SqlDecimal.NotEquals(_test2, _test3).Value);
Assert.True(SqlDecimal.NotEquals(SqlDecimal.Null, _test3).IsNull);
}
/* Don't do such environment-dependent test. It will never succeed under Portable.NET and MS.NET
[Fact]
public void GetHashCodeTest()
{
// FIXME: Better way to test HashCode
Assert.Equal (-1281249885, Test1.GetHashCode ());
}
*/
[Fact]
public void GetTypeTest()
{
Assert.Equal("System.Data.SqlTypes.SqlDecimal", _test1.GetType().ToString());
Assert.Equal("System.Decimal", _test1.Value.GetType().ToString());
}
[Fact]
public void Greaters()
{
// GreateThan ()
Assert.True(!SqlDecimal.GreaterThan(_test1, _test2).Value);
Assert.True(SqlDecimal.GreaterThan(_test2, _test1).Value);
Assert.True(!SqlDecimal.GreaterThan(_test2, _test3).Value);
// GreaterTharOrEqual ()
Assert.True(!SqlDecimal.GreaterThanOrEqual(_test1, _test2).Value);
Assert.True(SqlDecimal.GreaterThanOrEqual(_test2, _test1).Value);
Assert.True(SqlDecimal.GreaterThanOrEqual(_test2, _test3).Value);
}
[Fact]
public void Lessers()
{
// LessThan()
Assert.True(!SqlDecimal.LessThan(_test3, _test2).Value);
Assert.True(!SqlDecimal.LessThan(_test2, _test1).Value);
Assert.True(SqlDecimal.LessThan(_test1, _test2).Value);
// LessThanOrEqual ()
Assert.True(SqlDecimal.LessThanOrEqual(_test1, _test2).Value);
Assert.True(!SqlDecimal.LessThanOrEqual(_test2, _test1).Value);
Assert.True(SqlDecimal.LessThanOrEqual(_test2, _test3).Value);
Assert.True(SqlDecimal.LessThanOrEqual(_test1, SqlDecimal.Null).IsNull);
}
[Fact]
public void Conversions()
{
// ToDouble
Assert.Equal(6464.6464, _test1.ToDouble());
// ToSqlBoolean ()
Assert.Equal(new SqlBoolean(1), _test1.ToSqlBoolean());
SqlDecimal Test = new SqlDecimal(0);
Assert.True(!Test.ToSqlBoolean().Value);
Test = new SqlDecimal(0);
Assert.True(!Test.ToSqlBoolean().Value);
Assert.True(SqlDecimal.Null.ToSqlBoolean().IsNull);
// ToSqlByte ()
Test = new SqlDecimal(250);
Assert.Equal((byte)250, Test.ToSqlByte().Value);
try
{
SqlByte b = (byte)_test2.ToSqlByte();
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlDouble ()
Assert.Equal(6464.6464, _test1.ToSqlDouble());
// ToSqlInt16 ()
Assert.Equal((short)1, new SqlDecimal(1).ToSqlInt16().Value);
try
{
SqlInt16 test = SqlDecimal.MaxValue.ToSqlInt16().Value;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlInt32 ()
// LAMESPEC: 6464.6464 --> 64646464 ??? with windows
// MS.NET seems to return the first 32 bit integer (i.e.
// Data [0]) but we don't have to follow such stupidity.
// Assert.Equal ((int)64646464, Test1.ToSqlInt32 ().Value);
// Assert.Equal ((int)1212, new SqlDecimal(12.12m).ToSqlInt32 ().Value);
try
{
SqlInt32 test = SqlDecimal.MaxValue.ToSqlInt32().Value;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlInt64 ()
Assert.Equal(6464, _test1.ToSqlInt64().Value);
// ToSqlMoney ()
Assert.Equal((decimal)6464.6464, _test1.ToSqlMoney().Value);
try
{
SqlMoney test = SqlDecimal.MaxValue.ToSqlMoney().Value;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlSingle ()
Assert.Equal((float)6464.6464, _test1.ToSqlSingle().Value);
// ToSqlString ()
Assert.Equal("6464.6464", _test1.ToSqlString().Value);
// ToString ()
Assert.Equal("6464.6464", _test1.ToString());
// NOT WORKING
Assert.Equal("792281625142643375935439503350000.00", SqlDecimal.Multiply(_test5, _test2).ToString());
Assert.Equal(1E+38, SqlDecimal.MaxValue.ToSqlDouble());
}
[Fact]
public void Truncate()
{
// NOT WORKING
Assert.Equal(new SqlDecimal(6464.6400m).Value, SqlDecimal.Truncate(_test1, 2).Value);
Assert.Equal(6464.6400m, SqlDecimal.Truncate(_test1, 2).Value);
}
// OPERATORS
[Fact]
public void ArithmeticOperators()
{
// "+"-operator
Assert.Equal(new SqlDecimal(16464.6464m), _test1 + _test2);
Assert.Equal("79228162514264337593543960335.00", (_test5 + _test3).ToString());
SqlDecimal test2 = new SqlDecimal(-2000m);
Assert.Equal(8000.00m, _test3 + test2);
Assert.Equal(-2006m, _test4 + test2);
Assert.Equal(8000.00m, test2 + _test3);
try
{
SqlDecimal test = SqlDecimal.MaxValue + SqlDecimal.MaxValue;
Assert.False(true);
}
catch (OverflowException) { }
// "/"-operator => NotWorking
//Assert.Equal ((SqlDecimal)1.54687501546m, Test2 / Test1);
try
{
SqlDecimal test = _test3 / new SqlDecimal(0);
Assert.False(true);
}
catch (DivideByZeroException e)
{
Assert.Equal(typeof(DivideByZeroException), e.GetType());
}
// "*"-operator
Assert.Equal(64646464.000000m, _test1 * _test2);
SqlDecimal Test = _test5 * (new SqlDecimal(2m));
Assert.Equal("158456325028528675187087900670", Test.ToString());
try
{
SqlDecimal test = SqlDecimal.MaxValue * _test1;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// "-"-operator
Assert.Equal(3535.3536m, _test2 - _test1);
Assert.Equal(-10006.00m, _test4 - _test3);
try
{
SqlDecimal test = SqlDecimal.MinValue - SqlDecimal.MaxValue;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
Assert.Equal(SqlDecimal.Null, SqlDecimal.Null + _test1);
}
[Fact]
public void ThanOrEqualOperators()
{
SqlDecimal pval = new SqlDecimal(10m);
SqlDecimal nval = new SqlDecimal(-10m);
SqlDecimal val = new SqlDecimal(5m);
// == -operator
Assert.True((_test2 == _test3).Value);
Assert.True(!(_test1 == _test2).Value);
Assert.True((_test1 == SqlDecimal.Null).IsNull);
Assert.False((pval == nval).Value);
// != -operator
Assert.True(!(_test2 != _test3).Value);
Assert.True((_test1 != _test3).Value);
Assert.True((_test4 != _test3).Value);
Assert.True((_test1 != SqlDecimal.Null).IsNull);
Assert.True((pval != nval).Value);
// > -operator
Assert.True((_test2 > _test1).Value);
Assert.True(!(_test1 > _test3).Value);
Assert.True(!(_test2 > _test3).Value);
Assert.True((_test1 > SqlDecimal.Null).IsNull);
Assert.False((nval > val).Value);
// >= -operator
Assert.True(!(_test1 >= _test3).Value);
Assert.True((_test3 >= _test1).Value);
Assert.True((_test2 >= _test3).Value);
Assert.True((_test1 >= SqlDecimal.Null).IsNull);
Assert.False((nval > val).Value);
// < -operator
Assert.True(!(_test2 < _test1).Value);
Assert.True((_test1 < _test3).Value);
Assert.True(!(_test2 < _test3).Value);
Assert.True((_test1 < SqlDecimal.Null).IsNull);
Assert.False((val < nval).Value);
// <= -operator
Assert.True((_test1 <= _test3).Value);
Assert.True(!(_test3 <= _test1).Value);
Assert.True((_test2 <= _test3).Value);
Assert.True((_test1 <= SqlDecimal.Null).IsNull);
Assert.False((val <= nval).Value);
}
[Fact]
public void UnaryNegation()
{
Assert.Equal(6m, -_test4.Value);
Assert.Equal(-6464.6464m, -_test1.Value);
Assert.Equal(SqlDecimal.Null, SqlDecimal.Null);
}
[Fact]
public void SqlBooleanToSqlDecimal()
{
SqlBoolean TestBoolean = new SqlBoolean(true);
SqlDecimal Result;
Result = (SqlDecimal)TestBoolean;
Assert.Equal(1m, Result.Value);
Result = (SqlDecimal)SqlBoolean.Null;
Assert.True(Result.IsNull);
Assert.Equal(SqlDecimal.Null, (SqlDecimal)SqlBoolean.Null);
}
[Fact]
public void SqlDecimalToDecimal()
{
Assert.Equal(6464.6464m, (decimal)_test1);
}
[Fact]
public void SqlDoubleToSqlDecimal()
{
SqlDouble Test = new SqlDouble(12E+10);
Assert.Equal(120000000000.00000m, ((SqlDecimal)Test).Value);
}
[Fact]
public void SqlSingleToSqlDecimal()
{
SqlSingle Test = new SqlSingle(1E+9);
Assert.Equal(1000000000.0000000m, ((SqlDecimal)Test).Value);
try
{
SqlDecimal test = (SqlDecimal)SqlSingle.MaxValue;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlStringToSqlDecimal()
{
SqlString TestString = new SqlString("Test string");
SqlString TestString100 = new SqlString("100");
Assert.Equal(100m, ((SqlDecimal)TestString100).Value);
try
{
SqlDecimal test = (SqlDecimal)TestString;
Assert.False(true);
}
catch (FormatException e)
{
Assert.Equal(typeof(FormatException), e.GetType());
}
try
{
SqlDecimal test = (SqlDecimal)new SqlString("9E+100");
Assert.False(true);
}
catch (FormatException e)
{
Assert.Equal(typeof(FormatException), e.GetType());
}
}
[Fact]
public void DecimalToSqlDecimal()
{
decimal d = 1000.1m;
Assert.Equal(1000.1m, (SqlDecimal)d);
}
[Fact]
public void ByteToSqlDecimal()
{
Assert.Equal(255m, ((SqlDecimal)SqlByte.MaxValue).Value);
}
[Fact]
public void SqlIntToSqlDouble()
{
SqlInt16 Test64 = new SqlInt16(64);
SqlInt32 Test640 = new SqlInt32(640);
SqlInt64 Test64000 = new SqlInt64(64000);
Assert.Equal(64m, ((SqlDecimal)Test64).Value);
Assert.Equal(640m, ((SqlDecimal)Test640).Value);
Assert.Equal(64000m, ((SqlDecimal)Test64000).Value);
}
[Fact]
public void SqlMoneyToSqlDecimal()
{
SqlMoney TestMoney64 = new SqlMoney(64);
Assert.Equal(64.0000M, ((SqlDecimal)TestMoney64).Value);
}
[Fact]
public void ToStringTest()
{
Assert.Equal("Null", SqlDecimal.Null.ToString());
Assert.Equal("-99999999999999999999999999999999999999", SqlDecimal.MinValue.ToString());
Assert.Equal("99999999999999999999999999999999999999", SqlDecimal.MaxValue.ToString());
}
[Fact]
public void Value()
{
decimal d = decimal.Parse("9999999999999999999999999999");
Assert.Equal(9999999999999999999999999999m, d);
}
[Fact]
public void GetXsdTypeTest()
{
XmlQualifiedName qualifiedName = SqlDecimal.GetXsdType(null);
Assert.Equal("decimal", qualifiedName.Name);
}
internal void ReadWriteXmlTestInternal(string xml,
decimal testval,
string unit_test_id)
{
SqlDecimal test;
SqlDecimal test1;
XmlSerializer ser;
StringWriter sw;
XmlTextWriter xw;
StringReader sr;
XmlTextReader xr;
test = new SqlDecimal(testval);
ser = new XmlSerializer(typeof(SqlDecimal));
sw = new StringWriter();
xw = new XmlTextWriter(sw);
ser.Serialize(xw, test);
// Assert.Equal (xml, sw.ToString ());
sr = new StringReader(xml);
xr = new XmlTextReader(sr);
test1 = (SqlDecimal)ser.Deserialize(xr);
Assert.Equal(testval, test1.Value);
}
[Fact]
//[Category ("MobileNotWorking")]
public void ReadWriteXmlTest()
{
string xml1 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><decimal>4556.89756</decimal>";
string xml2 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><decimal>-6445.9999</decimal>";
string xml3 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><decimal>0x455687AB3E4D56F</decimal>";
decimal test1 = new decimal(4556.89756);
// This one fails because of a possible conversion bug
//decimal test2 = new Decimal (-6445.999999999999999999999);
decimal test2 = new decimal(-6445.9999);
decimal test3 = new decimal(0x455687AB3E4D56F);
ReadWriteXmlTestInternal(xml1, test1, "BA01");
ReadWriteXmlTestInternal(xml2, test2, "BA02");
try
{
ReadWriteXmlTestInternal(xml3, test3, "BA03");
Assert.False(true);
}
catch (InvalidOperationException e)
{
Assert.Equal(typeof(FormatException), e.InnerException.GetType());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
namespace BitmapResizer {
/// <summary>
///
/// DISCLAIMER:
///
/// This sample code is not supported under any Microsoft standard support program or service.
/// The sample code is provided AS IS without warranty of any kind. Microsoft further disclaims
/// all implied warranties including, without limitation, any implied warranties of merchantability
/// or of fitness for a particular purpose. The entire risk arising out of the use or performance
/// of the sample code and documentation remains with you. In no event shall Microsoft, its
/// authors, or anyone else involved in the creation, production, or delivery of the code be
/// liable for any damages whatsoever (including, without limitation, damages for loss of business
/// profits, business interruption, loss of business information, or other pecuniary loss) arising
/// out of the use of or inability to use the sample code or documentation, even if Microsoft
/// has been advised of the possibility of such damages.
///
/// </summary>
///
public class IndeterminateProgressBar : System.Windows.Forms.Panel {
private System.Windows.Forms.Timer tmrPulse;
private System.ComponentModel.Container components = null;
protected int numPips = 5;
protected int pnlWidth = 100;
protected int pnlHeight = 16;
protected int pulseIndex = 0;
protected float alphaFactor = 0.2f;
protected bool FadeIn = true;
protected bool start = false;
protected LinearGradientMode gMode = LinearGradientMode.ForwardDiagonal;
protected Color dkBorder = Color.Black;
protected Color ltBorder = Color.White;
protected Color from = Color.LimeGreen;
protected Color to = Color.FromArgb(5, 149, 20);
protected int speed = 25;
protected Bitmap imgBase;
protected Bitmap curBase;
protected ImageAttributes imageAtt = new ImageAttributes();
protected ColorMatrix clrMtrx = new ColorMatrix(new float[][] {new float[] {1.0f, 0, 0, 0, 0},
new float[] { 0, 1.0f, 0, 0, 0},
new float[] { 0, 0, 1.0f, 0, 0},
new float[] { 0, 0, 0, 0.5f, 0},
new float[] { 0, 0, 0, 0, 1.0f}});
public IndeterminateProgressBar(System.ComponentModel.IContainer container) {
///
/// Required for Windows.Forms Class Composition Designer support
///
container.Add(this);
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
this.SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer, true);
this.Width = pnlWidth;
this.Height = pnlHeight;
}
#region Properties
[DefaultValue(typeof(bool), "False"),
Description("If return is true the bar is currently pulsing, else the bar is in idle state."),
Category("Pip State")]
public bool IsPulsing {
get {
return start;
}
}
[DefaultValue(typeof(Color), "Color.Black"),
Description("The color of the dark boarder for each pip."),
Category("Pip Options")]
public Color BorderDark {
get {
return dkBorder;
}
set {
dkBorder = value;
CreateBaseImage();
Invalidate();
}
}
[DefaultValue(typeof(Color), "Color.White"),
Description("The color of the inner light border for each pip."),
Category("Pip Options")]
public Color BorderLight {
get {
return ltBorder;
}
set {
ltBorder = value;
CreateBaseImage();
Invalidate();
}
}
[DefaultValue(typeof(Color), "Color,LimeGreen"),
Description("The start color for each pip's inner body."),
Category("Pip Options")]
public Color ColorFrom {
get {
return from;
}
set {
from = value;
CreateBaseImage();
Invalidate();
}
}
[DefaultValue(typeof(Color), "Color.FromArgb(5,149,20)"),
Description("The end color for each pip's inner body."),
Category("Pip Options")]
public Color ColorTo {
get {
return to;
}
set {
to = value;
CreateBaseImage();
Invalidate();
}
}
[DefaultValue(typeof(LinearGradientMode), "ForwardDiagonal"),
Description("Direction of the gradient within the pip's body."),
Category("Pip Options")]
public LinearGradientMode GradientDirection {
get {
return gMode;
}
set {
gMode = value;
CreateBaseImage();
Invalidate();
}
}
[DefaultValue(typeof(int), "25"),
Description("Speed of the alpha transition between each of the pip's."),
Category("Pip Options")]
public int Speed {
get {
return speed;
}
set {
if (value < 5)
speed = 5;
else
speed = value;
tmrPulse.Interval = speed;
Invalidate();
}
}
[DefaultValue(typeof(int), "5"),
Description("The number of pips to display in the control."),
Category("Pip Options")]
public int Pips {
get {
return numPips;
}
set {
numPips = value;
if (numPips < 1) numPips = 1;
this.Width = numPips * 20;
CreateBaseImage();
Invalidate();
}
}
#endregion
public IndeterminateProgressBar() {
///
/// Required for Windows.Forms Class Composition Designer support
///
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
public void Start() {
if (tmrPulse.Enabled) return;
//Start the pulse
tmrPulse.Enabled = true;
start = tmrPulse.Enabled;
Invalidate();
}
public void Stop() {
if (!tmrPulse.Enabled) return;
//Reset state
tmrPulse.Enabled = false;
start = tmrPulse.Enabled;
pulseIndex = 0;
FadeIn = true;
curBase = imgBase.Clone() as Bitmap;
Invalidate();
}
protected void CreateBaseImage() {
int pipX = 0;
Bitmap tmpBase = new Bitmap(numPips * 20, 17, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Bitmap pipBlank = GeneratePip();
Graphics g = Graphics.FromImage(tmpBase);
try {
for (int i = 0; i < numPips; i++) {
clrMtrx[3, 3] = .2f;
imageAtt.SetColorMatrix(clrMtrx, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(pipBlank, new Rectangle(pipX, 0, 17, 17), 0, 0, 17, 17, GraphicsUnit.Pixel, imageAtt);
pipX = pipX + 20;
}
curBase = tmpBase.Clone() as Bitmap;
imgBase = tmpBase.Clone() as Bitmap;
} finally {
g.Dispose();
pipBlank.Dispose();
tmpBase.Dispose();
}
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) {
if (imgBase == null) CreateBaseImage();
if (start)
e.Graphics.DrawImage(curBase, 0, 0);
else
e.Graphics.DrawImage(imgBase, 0, 0);
}
public void PaintPulseIncrement() {
int pipX = pulseIndex * 20;
float tmpAlpha = .1f;
Bitmap tmpBase = imgBase.Clone() as Bitmap;
Bitmap pipBase = GeneratePip();
Graphics g = Graphics.FromImage(tmpBase);
try {
if (FadeIn) {
//Fade In...
alphaFactor = alphaFactor + 0.1f;
if (alphaFactor > 1.0f) {
alphaFactor = 1.0f;
tmpAlpha = .1f;
FadeIn = false;
}
} else {
//fade out...
alphaFactor = alphaFactor - 0.1f;
if (alphaFactor < 0.2f) {
alphaFactor = 0.2f;
FadeIn = true;
if (++pulseIndex > numPips) pulseIndex = 0;
}
//start fading in the next pip half way through
//the current pips fade out
if (alphaFactor <= 0.5f) tmpAlpha = tmpAlpha + .1f;
}
clrMtrx[3, 3] = alphaFactor;
imageAtt.SetColorMatrix(clrMtrx, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(pipBase, new Rectangle(pipX, 0, 17, 17), 0, 0, 17, 17, GraphicsUnit.Pixel, imageAtt);
if (tmpAlpha > .1f) {
clrMtrx[3, 3] = tmpAlpha;
imageAtt.SetColorMatrix(clrMtrx, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(pipBase, new Rectangle(pipX + 20, 0, 17, 17), 0, 0, 17, 17, GraphicsUnit.Pixel, imageAtt);
}
} finally {
lock (curBase) {
if (curBase != null) curBase.Dispose();
curBase = tmpBase.Clone() as Bitmap;
}
g.Dispose();
pipBase.Dispose();
tmpBase.Dispose();
}
}
private void tmrPulse_Tick(object sender, System.EventArgs e) {
this.PaintPulseIncrement();
this.Invalidate();
}
private Bitmap GeneratePip() {
Bitmap pipBase = new Bitmap(17, 17, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Graphics g = Graphics.FromImage(pipBase);
Pen dkpen = new Pen(dkBorder, 1);
Pen ltpen = new Pen(ltBorder, 1);
try {
g.Clear(this.BackColor);
g.DrawRectangle(dkpen, 0, 0, 16, 16);
g.DrawRectangle(ltpen, 1, 1, 14, 14);
g.DrawRectangle(dkpen, 2, 2, 12, 12);
Rectangle ca = new Rectangle(3, 3, 11, 11);
using (LinearGradientBrush gBrush = new LinearGradientBrush(ca, from, to, gMode))
g.FillRectangle(gBrush, ca);
return pipBase.Clone() as Bitmap;
} finally {
//free resources
g.Dispose();
dkpen.Dispose();
ltpen.Dispose();
pipBase.Dispose();
}
}
protected override void Dispose(bool disposing) {
if (disposing) {
if (components != null) {
//free global resources
imgBase.Dispose();
curBase.Dispose();
imageAtt.Dispose();
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component Designer generated code
private void InitializeComponent() {
components = new System.ComponentModel.Container();
this.tmrPulse = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
this.tmrPulse.Enabled = false;
this.tmrPulse.Interval = 25;
this.tmrPulse.Tick += new System.EventHandler(this.tmrPulse_Tick);
this.ResumeLayout(false);
}
#endregion
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
namespace Lucene.Net.Util
{
/*
* 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 Directory = Lucene.Net.Store.Directory;
/// <summary>
/// This class emulates the new Java 7 "Try-With-Resources" statement.
/// Remove once Lucene is on Java 7.
/// <para/>
/// @lucene.internal
/// </summary>
[ExceptionToClassNameConvention]
public sealed class IOUtils
{
/// <summary>
/// UTF-8 <see cref="Encoding"/> instance to prevent repeated
/// <see cref="Encoding.UTF8"/> lookups </summary>
[Obsolete("Use Encoding.UTF8 instead.")]
public static readonly Encoding CHARSET_UTF_8 = Encoding.UTF8;
/// <summary>
/// UTF-8 charset string.
/// <para/>Where possible, use <see cref="Encoding.UTF8"/> instead,
/// as using the <see cref="string"/> constant may slow things down. </summary>
/// <seealso cref="Encoding.UTF8"/>
public static readonly string UTF_8 = "UTF-8";
private IOUtils() // no instance
{
}
/// <summary>
/// <para>Disposes all given <c>IDisposable</c>s, suppressing all thrown exceptions. Some of the <c>IDisposable</c>s
/// may be <c>null</c>, they are ignored. After everything is disposed, method either throws <paramref name="priorException"/>,
/// if one is supplied, or the first of suppressed exceptions, or completes normally.</para>
/// <para>Sample usage:
/// <code>
/// IDisposable resource1 = null, resource2 = null, resource3 = null;
/// ExpectedException priorE = null;
/// try
/// {
/// resource1 = ...; resource2 = ...; resource3 = ...; // Acquisition may throw ExpectedException
/// ..do..stuff.. // May throw ExpectedException
/// }
/// catch (ExpectedException e)
/// {
/// priorE = e;
/// }
/// finally
/// {
/// IOUtils.CloseWhileHandlingException(priorE, resource1, resource2, resource3);
/// }
/// </code>
/// </para>
/// </summary>
/// <param name="priorException"> <c>null</c> or an exception that will be rethrown after method completion. </param>
/// <param name="objects"> Objects to call <see cref="IDisposable.Dispose()"/> on. </param>
[Obsolete("Use DisposeWhileHandlingException(Exception, params IDisposable[]) instead.")]
public static void CloseWhileHandlingException(Exception priorException, params IDisposable[] objects)
{
DisposeWhileHandlingException(priorException, objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(Exception, IDisposable[])"/>
[Obsolete("Use DisposeWhileHandlingException(Exception, IEnumerable<IDisposable>) instead.")]
public static void CloseWhileHandlingException(Exception priorException, IEnumerable<IDisposable> objects)
{
DisposeWhileHandlingException(priorException, objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. Some of the
/// <see cref="IDisposable"/>s may be <c>null</c>; they are
/// ignored. After everything is closed, the method either
/// throws the first exception it hit while closing, or
/// completes normally if there were no exceptions.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
[Obsolete("Use Dispose(params IDisposable[]) instead.")]
public static void Close(params IDisposable[] objects)
{
Dispose(objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. </summary>
/// <seealso cref="Dispose(IDisposable[])"/>
[Obsolete("Use Dispose(IEnumerable<IDisposable>) instead.")]
public static void Close(IEnumerable<IDisposable> objects)
{
Dispose(objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions.
/// Some of the <see cref="IDisposable"/>s may be <c>null</c>, they are ignored.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
[Obsolete("Use DisposeWhileHandlingException(params IDisposable[]) instead.")]
public static void CloseWhileHandlingException(params IDisposable[] objects)
{
DisposeWhileHandlingException(objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(IEnumerable{IDisposable})"/>
/// <seealso cref="DisposeWhileHandlingException(IDisposable[])"/>
[Obsolete("Use DisposeWhileHandlingException(IEnumerable<IDisposable>) instead.")]
public static void CloseWhileHandlingException(IEnumerable<IDisposable> objects)
{
DisposeWhileHandlingException(objects);
}
// LUCENENET specific - added overloads starting with Dispose... instead of Close...
/// <summary>
/// <para>Disposes all given <c>IDisposable</c>s, suppressing all thrown exceptions. Some of the <c>IDisposable</c>s
/// may be <c>null</c>, they are ignored. After everything is disposed, method either throws <paramref name="priorException"/>,
/// if one is supplied, or the first of suppressed exceptions, or completes normally.</para>
/// <para>Sample usage:
/// <code>
/// IDisposable resource1 = null, resource2 = null, resource3 = null;
/// ExpectedException priorE = null;
/// try
/// {
/// resource1 = ...; resource2 = ...; resource3 = ...; // Acquisition may throw ExpectedException
/// ..do..stuff.. // May throw ExpectedException
/// }
/// catch (ExpectedException e)
/// {
/// priorE = e;
/// }
/// finally
/// {
/// IOUtils.DisposeWhileHandlingException(priorE, resource1, resource2, resource3);
/// }
/// </code>
/// </para>
/// </summary>
/// <param name="priorException"> <c>null</c> or an exception that will be rethrown after method completion. </param>
/// <param name="objects"> Objects to call <see cref="IDisposable.Dispose()"/> on. </param>
public static void DisposeWhileHandlingException(Exception priorException, params IDisposable[] objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(priorException ?? th, t);
if (th == null)
{
th = t;
}
}
}
if (priorException != null)
{
throw priorException;
}
else
{
ReThrow(th);
}
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(Exception, IDisposable[])"/>
public static void DisposeWhileHandlingException(Exception priorException, IEnumerable<IDisposable> objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(priorException ?? th, t);
if (th == null)
{
th = t;
}
}
}
if (priorException != null)
{
throw priorException;
}
else
{
ReThrow(th);
}
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. Some of the
/// <see cref="IDisposable"/>s may be <c>null</c>; they are
/// ignored. After everything is closed, the method either
/// throws the first exception it hit while closing, or
/// completes normally if there were no exceptions.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
public static void Dispose(params IDisposable[] objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(th, t);
if (th == null)
{
th = t;
}
}
}
ReThrow(th);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. </summary>
/// <seealso cref="Dispose(IDisposable[])"/>
public static void Dispose(IEnumerable<IDisposable> objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(th, t);
if (th == null)
{
th = t;
}
}
}
ReThrow(th);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions.
/// Some of the <see cref="IDisposable"/>s may be <c>null</c>, they are ignored.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
public static void DisposeWhileHandlingException(params IDisposable[] objects)
{
foreach (var o in objects)
{
try
{
if (o != null)
{
o.Dispose();
}
}
catch (Exception)
{
//eat it
}
}
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(IDisposable[])"/>
public static void DisposeWhileHandlingException(IEnumerable<IDisposable> objects)
{
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception)
{
//eat it
}
}
}
/// <summary>
/// Since there's no C# equivalent of Java's Exception.AddSuppressed, we add the
/// suppressed exceptions to a data field via the
/// <see cref="Support.ExceptionExtensions.AddSuppressed(Exception, Exception)"/> method.
/// <para/>
/// The exceptions can be retrieved by calling <see cref="ExceptionExtensions.GetSuppressed(Exception)"/>
/// or <see cref="ExceptionExtensions.GetSuppressedAsList(Exception)"/>.
/// </summary>
/// <param name="exception"> this exception should get the suppressed one added </param>
/// <param name="suppressed"> the suppressed exception </param>
private static void AddSuppressed(Exception exception, Exception suppressed)
{
if (exception != null && suppressed != null)
{
exception.AddSuppressed(suppressed);
}
}
/// <summary>
/// Wrapping the given <see cref="Stream"/> in a reader using a <see cref="Encoding"/>.
/// Unlike Java's defaults this reader will throw an exception if your it detects
/// the read charset doesn't match the expected <see cref="Encoding"/>.
/// <para/>
/// Decoding readers are useful to load configuration files, stopword lists or synonym files
/// to detect character set problems. However, its not recommended to use as a common purpose
/// reader.
/// </summary>
/// <param name="stream"> The stream to wrap in a reader </param>
/// <param name="charSet"> The expected charset </param>
/// <returns> A wrapping reader </returns>
public static TextReader GetDecodingReader(Stream stream, Encoding charSet)
{
return new StreamReader(stream, charSet);
}
/// <summary>
/// Opens a <see cref="TextReader"/> for the given <see cref="FileInfo"/> using a <see cref="Encoding"/>.
/// Unlike Java's defaults this reader will throw an exception if your it detects
/// the read charset doesn't match the expected <see cref="Encoding"/>.
/// <para/>
/// Decoding readers are useful to load configuration files, stopword lists or synonym files
/// to detect character set problems. However, its not recommended to use as a common purpose
/// reader. </summary>
/// <param name="file"> The file to open a reader on </param>
/// <param name="charSet"> The expected charset </param>
/// <returns> A reader to read the given file </returns>
public static TextReader GetDecodingReader(FileInfo file, Encoding charSet)
{
FileStream stream = null;
bool success = false;
try
{
stream = file.OpenRead();
TextReader reader = GetDecodingReader(stream, charSet);
success = true;
return reader;
}
finally
{
if (!success)
{
IOUtils.Dispose(stream);
}
}
}
/// <summary>
/// Opens a <see cref="TextReader"/> for the given resource using a <see cref="Encoding"/>.
/// Unlike Java's defaults this reader will throw an exception if your it detects
/// the read charset doesn't match the expected <see cref="Encoding"/>.
/// <para/>
/// Decoding readers are useful to load configuration files, stopword lists or synonym files
/// to detect character set problems. However, its not recommended to use as a common purpose
/// reader. </summary>
/// <param name="clazz"> The class used to locate the resource </param>
/// <param name="resource"> The resource name to load </param>
/// <param name="charSet"> The expected charset </param>
/// <returns> A reader to read the given file </returns>
public static TextReader GetDecodingReader(Type clazz, string resource, Encoding charSet)
{
Stream stream = null;
bool success = false;
try
{
stream = clazz.Assembly.FindAndGetManifestResourceStream(clazz, resource);
TextReader reader = GetDecodingReader(stream, charSet);
success = true;
return reader;
}
finally
{
if (!success)
{
IOUtils.Dispose(stream);
}
}
}
/// <summary>
/// Deletes all given files, suppressing all thrown <see cref="Exception"/>s.
/// <para/>
/// Note that the files should not be <c>null</c>.
/// </summary>
public static void DeleteFilesIgnoringExceptions(Directory dir, params string[] files)
{
foreach (string name in files)
{
try
{
dir.DeleteFile(name);
}
catch (Exception)
{
// ignore
}
}
}
/// <summary>
/// Copy one file's contents to another file. The target will be overwritten
/// if it exists. The source must exist.
/// </summary>
public static void Copy(FileInfo source, FileInfo target)
{
FileStream fis = null;
FileStream fos = null;
try
{
fis = source.OpenRead();
fos = target.OpenWrite();
byte[] buffer = new byte[1024 * 8];
int len;
while ((len = fis.Read(buffer, 0, buffer.Length)) > 0)
{
fos.Write(buffer, 0, len);
}
}
finally
{
Dispose(fis, fos);
}
}
/// <summary>
/// Simple utilty method that takes a previously caught
/// <see cref="Exception"/> and rethrows either
/// <see cref="IOException"/> or an unchecked exception. If the
/// argument is <c>null</c> then this method does nothing.
/// </summary>
public static void ReThrow(Exception th)
{
if (th != null)
{
if (th is System.IO.IOException)
{
throw th;
}
ReThrowUnchecked(th);
}
}
/// <summary>
/// Simple utilty method that takes a previously caught
/// <see cref="Exception"/> and rethrows it as an unchecked exception.
/// If the argument is <c>null</c> then this method does nothing.
/// </summary>
public static void ReThrowUnchecked(Exception th)
{
if (th != null)
{
throw th;
}
}
// LUCENENET specific: Fsync is pointless in .NET, since we are
// calling FileStream.Flush(true) before the stream is disposed
// which means we never need it at the point in Java where it is called.
// /// <summary>
// /// Ensure that any writes to the given file is written to the storage device that contains it. </summary>
// /// <param name="fileToSync"> The file to fsync </param>
// /// <param name="isDir"> If <c>true</c>, the given file is a directory (we open for read and ignore <see cref="IOException"/>s,
// /// because not all file systems and operating systems allow to fsync on a directory) </param>
// public static void Fsync(string fileToSync, bool isDir)
// {
// // Fsync does not appear to function properly for Windows and Linux platforms. In Lucene version
// // they catch this in IOException branch and return if the call is for the directory.
// // In Lucene.Net the exception is UnauthorizedAccessException and is not handled by
// // IOException block. No need to even attempt to fsync, just return if the call is for directory
// if (isDir)
// {
// return;
// }
// var retryCount = 1;
// while (true)
// {
// FileStream file = null;
// bool success = false;
// try
// {
// // If the file is a directory we have to open read-only, for regular files we must open r/w for the fsync to have an effect.
// // See http://blog.httrack.com/blog/2013/11/15/everything-you-always-wanted-to-know-about-fsync/
// file = new FileStream(fileToSync,
// FileMode.Open, // We shouldn't create a file when syncing.
// // Java version uses FileChannel which doesn't create the file if it doesn't already exist,
// // so there should be no reason for attempting to create it in Lucene.Net.
// FileAccess.Write,
// FileShare.ReadWrite);
// //FileSupport.Sync(file);
// file.Flush(true);
// success = true;
// }
//#pragma warning disable 168
// catch (IOException e)
//#pragma warning restore 168
// {
// if (retryCount == 5)
// {
// throw;
// }
//#if !NETSTANDARD1_6
// try
// {
//#endif
// // Pause 5 msec
// Thread.Sleep(5);
//#if !NETSTANDARD1_6
// }
// catch (ThreadInterruptedException ie)
// {
// var ex = new ThreadInterruptedException(ie.ToString(), ie);
// ex.AddSuppressed(e);
// throw ex;
// }
//#endif
// }
// finally
// {
// if (file != null)
// {
// file.Dispose();
// }
// }
// if (success)
// {
// return;
// }
// retryCount++;
// }
// }
}
}
| |
namespace AdMaiora.Bugghy
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Views.Animations;
using Android.Animation;
using Android.Widget;
using Android.Views.InputMethods;
using Android.Content.Res;
using Android.Hardware.Input;
using AdMaiora.AppKit.UI;
//using Xamarin.Auth;
using Android.Gms.Common.Apis;
using Android.Gms.Auth.Api.SignIn;
using Android.Gms.Common;
using Android.Gms.Auth.Api;
#pragma warning disable CS4014
public class LoginFragment : AdMaiora.AppKit.UI.App.Fragment, GoogleApiClient.IOnConnectionFailedListener
{
#region Inner Classes
#endregion
#region Constants and Fields
private string _email;
private string _password;
// Google+ API for signing in
private GoogleSignInOptions _gso;
private GoogleApiClient _gapi;
// This flag check if we are already calling the login REST service
private bool _isLogginUser;
// This cancellation token is used to cancel the rest login request
private CancellationTokenSource _cts0;
// This flag check if we are already calling the login REST service
private bool _isConfirmingUser;
// This cancellation token is used to cancel the rest login request
private CancellationTokenSource _cts1;
#endregion
#region Widgets
[Widget]
private ImageView LogoImage;
[Widget]
private RelativeLayout InputLayout;
[Widget]
private EditText EmailText;
[Widget]
private EditText PasswordText;
[Widget]
private Button LoginButton;
[Widget]
private Button GoogleLoginButton;
[Widget]
private Button RegisterButton;
[Widget]
private Button VerifyButton;
#endregion
#region Constructors
public LoginFragment()
{
}
#endregion
#region Properties
#endregion
#region Fragment Methods
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
_gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
.RequestIdToken(AppController.Globals.GoogleClientId_Android)
.RequestEmail()
.Build();
_gapi = new GoogleApiClient.Builder(this.Context)
.EnableAutoManage(this.Activity, this)
.AddApi(Android.Gms.Auth.Api.Auth.GOOGLE_SIGN_IN_API, _gso)
.AddScope(new Scope(Scopes.Profile))
.Build();
}
public override void OnCreateView(LayoutInflater inflater, ViewGroup container)
{
base.OnCreateView(inflater, container);
#region Desinger Stuff
SetContentView(Resource.Layout.FragmentLogin, inflater, container);
SlideUpToShowKeyboard();
#endregion
this.ActionBar.Hide();
this.EmailText.Text = AppController.Settings.LastLoginUsernameUsed;
this.PasswordText.Text = String.Empty;
this.PasswordText.EditorAction += PasswordText_EditorAction;
this.LoginButton.Click += LoginButton_Click;
this.GoogleLoginButton.Click += GoogleLoginButton_Click;
this.RegisterButton.Click += RegisterButton_Click;
this.VerifyButton.Visibility = ViewStates.Gone;
this.VerifyButton.Click += VerifyButton_Click;
}
public override void OnActivityResult(int requestCode, int resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
try
{
if (requestCode == 1)
{
GoogleSignInResult result = Auth.GoogleSignInApi.GetSignInResultFromIntent(data);
if (result.IsSuccess)
{
GoogleSignInAccount account = result.SignInAccount;
string gClientId = AppController.Globals.GoogleClientId_Android;
string gEmail = account.Email;
string gToken = account.IdToken;
_cts0 = new CancellationTokenSource();
AppController.LoginUser(_cts0, gClientId, gEmail, gToken,
(d) =>
{
AppController.Settings.LastLoginUserIdUsed = d.UserId;
AppController.Settings.LastLoginUsernameUsed = _email;
AppController.Settings.AuthAccessToken = d.AuthAccessToken;
AppController.Settings.AuthExpirationDate = d.AuthExpirationDate.GetValueOrDefault().ToLocalTime();
AppController.Settings.GoogleSignedIn = true;
var f = new GimmicksFragment();
this.FragmentManager.BeginTransaction()
.AddToBackStack("BeforeGimmicksFragment")
.Replace(Resource.Id.ContentLayout, f, "GimmicksFragment")
.Commit();
},
(error) =>
{
Toast.MakeText(this.Activity.Application, error, ToastLength.Long).Show();
},
() =>
{
((MainActivity)this.Activity).UnblockUI();
});
}
else
{
((MainActivity)this.Activity).UnblockUI();
Toast.MakeText(this.Activity.Application, "Unable to login with Google!", ToastLength.Long).Show();
}
}
}
catch(Exception ex)
{
((MainActivity)this.Activity).UnblockUI();
Toast.MakeText(this.Activity.ApplicationContext, "Error logging with Google!", ToastLength.Long).Show();
}
finally
{
// Nothing to do
}
}
public override void OnDestroyView()
{
base.OnDestroyView();
if (_cts0 != null)
_cts0.Cancel();
if (_cts1 != null)
_cts1.Cancel();
this.PasswordText.EditorAction -= PasswordText_EditorAction;
this.LoginButton.Click -= LoginButton_Click;
this.GoogleLoginButton.Click -= GoogleLoginButton_Click;
this.RegisterButton.Click -= RegisterButton_Click;
this.VerifyButton.Click -= VerifyButton_Click;
}
#endregion
#region Google API Methods
public void OnConnectionFailed(ConnectionResult result)
{
}
#endregion
#region Public Methods
#endregion
#region Methods
private void LoginUser()
{
if (ValidateInput())
{
if (_isLogginUser)
return;
_isLogginUser = true;
_email = this.EmailText.Text;
_password = this.PasswordText.Text;
// Prevent user form tapping views while logging
((MainActivity)this.Activity).BlockUI();
// Create a new cancellation token for this request
_cts0 = new CancellationTokenSource();
AppController.LoginUser(_cts0, _email, _password,
// Service call success
(data) =>
{
AppController.Settings.LastLoginUserIdUsed = data.UserId;
AppController.Settings.LastLoginUsernameUsed = _email;
AppController.Settings.AuthAccessToken = data.AuthAccessToken;
AppController.Settings.AuthExpirationDate = data.AuthExpirationDate.GetValueOrDefault().ToLocalTime();
AppController.Settings.GoogleSignedIn = false;
var f = new GimmicksFragment();
this.FragmentManager.BeginTransaction()
.AddToBackStack("BeforeGimmicksFragment")
.Replace(Resource.Id.ContentLayout, f, "GimmicksFragment")
.Commit();
},
// Service call error
(error) =>
{
if (error.Contains("confirm"))
this.VerifyButton.Visibility = ViewStates.Visible;
Toast.MakeText(this.Activity.Application, error, ToastLength.Long).Show();
},
// Service call finished
() =>
{
_isLogginUser = false;
// Allow user to tap views
((MainActivity)this.Activity).UnblockUI();
});
}
}
private void VerifyUser()
{
if (ValidateInput())
{
if (_isConfirmingUser)
return;
_isConfirmingUser = true;
_email = this.EmailText.Text;
_password = this.PasswordText.Text;
// Prevent user form tapping views while logging
((MainActivity)this.Activity).BlockUI();
this.VerifyButton.Visibility = ViewStates.Gone;
// Create a new cancellation token for this request
_cts1 = new CancellationTokenSource();
AppController.VerifyUser(_cts1, _email, _password,
// Service call success
() =>
{
Toast.MakeText(this.Activity.Application, "You should receive a new mail!", ToastLength.Long).Show();
},
// Service call error
(error) =>
{
Toast.MakeText(this.Activity.Application, error, ToastLength.Long).Show();
},
// Service call finished
() =>
{
_isConfirmingUser = false;
// Allow user to tap views
((MainActivity)this.Activity).UnblockUI();
});
}
}
private bool ValidateInput()
{
var validator = new WidgetValidator()
.AddValidator(() => this.EmailText.Text, WidgetValidator.IsNotNullOrEmpty, "Please insert your email.")
.AddValidator(() => this.EmailText.Text, WidgetValidator.IsEmail, "Your mail is not valid!")
.AddValidator(() => this.PasswordText.Text, WidgetValidator.IsNotNullOrEmpty, "Please insert your password.")
.AddValidator(() => this.PasswordText.Text, WidgetValidator.IsPasswordMin8, "Your passowrd is not valid!");
string errorMessage;
if (!validator.Validate(out errorMessage))
{
Toast.MakeText(this.Activity.Application, errorMessage, ToastLength.Long).Show();
return false;
}
return true;
}
private async void LoginInGoogle()
{
((MainActivity)this.Activity).BlockUI();
if (AppController.Settings.GoogleSignedIn)
{
var r = await Auth.GoogleSignInApi.SignOut(_gapi);
if (r.Status.IsSuccess)
{
AppController.Settings.GoogleSignedIn = false;
}
else
{
Toast.MakeText(this.Activity.Application, "Unable to login with Google!", ToastLength.Long).Show();
return;
}
}
Intent intent = Auth.GoogleSignInApi.GetSignInIntent(_gapi);
StartActivityForResult(intent, 1);
}
#endregion
#region Event Handlers
private void PasswordText_EditorAction(object sender, TextView.EditorActionEventArgs e)
{
if (e.ActionId == Android.Views.InputMethods.ImeAction.Done)
{
LoginUser();
e.Handled = true;
DismissKeyboard();
}
}
private void LoginButton_Click(object sender, EventArgs e)
{
LoginUser();
DismissKeyboard();
}
private void GoogleLoginButton_Click(object sender, EventArgs e)
{
LoginInGoogle();
}
private void RegisterButton_Click(object sender, EventArgs e)
{
var f = new Registration0Fragment();
this.FragmentManager.BeginTransaction()
.AddToBackStack("BeforeRegistration0Fragment")
.Replace(Resource.Id.ContentLayout, f, "Registration0Fragment")
.Commit();
DismissKeyboard();
}
private void VerifyButton_Click(object sender, EventArgs e)
{
VerifyUser();
DismissKeyboard();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
namespace System
{
/// <summary>
/// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
[DebuggerTypeProxy(typeof(SpanDebugView<>))]
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public readonly ref struct ReadOnlySpan<T>
{
/// <summary>
/// Creates a new read-only span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
_length = array.Length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
}
/// <summary>
/// Creates a new read-only span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the read-only span.</param>
/// <param name="length">The number of items in the read-only span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
}
/// <summary>
/// Creates a new read-only span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe ReadOnlySpan(void* pointer, int length)
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = null;
_byteOffset = new IntPtr(pointer);
}
/// <summary>
/// Create a new read-only span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because neither the
/// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
/// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length)
{
Pinnable<T> pinnable = Unsafe.As<Pinnable<T>>(obj);
IntPtr byteOffset = Unsafe.ByteOffset<T>(ref pinnable.Data, ref objectData);
return new ReadOnlySpan<T>(pinnable, byteOffset, length);
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlySpan(Pinnable<T> pinnable, IntPtr byteOffset, int length)
{
Debug.Assert(length >= 0);
_length = length;
_pinnable = pinnable;
_byteOffset = byteOffset;
}
//Debugger Display = {T[length]}
private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length);
/// <summary>
/// The number of items in the read-only span.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Returns the specified element of the read-only span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public ref readonly T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= ((uint)_length))
ThrowHelper.ThrowIndexOutOfRangeException();
if (_pinnable == null)
unsafe { return ref Unsafe.Add<T>(ref Unsafe.AsRef<T>(_byteOffset.ToPointer()), index); }
else
return ref Unsafe.Add<T>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index);
}
}
/// <summary>
/// Copies the contents of this read-only span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
/// </summary>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// <summary>
/// Copies the contents of this read-only span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Span<T> destination)
{
int length = _length;
int destLength = destination.Length;
if ((uint)length == 0)
return true;
if ((uint)length > (uint)destLength)
return false;
ref T src = ref DangerousGetPinnableReference();
ref T dst = ref destination.DangerousGetPinnableReference();
SpanHelpers.CopyTo<T>(ref dst, destLength, ref src, length);
return true;
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(T[] array) => array != null ? new ReadOnlySpan<T>(array) : default;
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(ArraySegment<T> arraySegment)
=> arraySegment.Array != null ? new ReadOnlySpan<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count) : default;
/// <summary>
/// Forms a slice out of the given read-only span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
int length = _length - start;
return new ReadOnlySpan<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Forms a slice out of the given read-only span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
return new ReadOnlySpan<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Copies the contents of this read-only span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray()
{
if (_length == 0)
return SpanHelpers.PerTypeValues<T>.EmptyArray;
T[] result = new T[_length];
CopyTo(result);
return result;
}
/// <summary>
/// Returns a 0-length read-only span whose base is the null pointer.
/// </summary>
public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>);
/// <summary>
/// This method is obsolete, use System.Runtime.InteropServices.MemoryMarshal.GetReference instead.
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
internal ref T DangerousGetPinnableReference()
{
if (_pinnable == null)
unsafe { return ref Unsafe.AsRef<T>(_byteOffset.ToPointer()); }
else
return ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset);
}
/// <summary>Gets an enumerator for this span.</summary>
public Enumerator GetEnumerator() => new Enumerator(this);
/// <summary>Enumerates the elements of a <see cref="ReadOnlySpan{T}"/>.</summary>
public ref struct Enumerator
{
/// <summary>The span being enumerated.</summary>
private readonly ReadOnlySpan<T> _span;
/// <summary>The next index to yield.</summary>
private int _index;
/// <summary>Initialize the enumerator.</summary>
/// <param name="span">The span to enumerate.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Enumerator(ReadOnlySpan<T> span)
{
_span = span;
_index = -1;
}
/// <summary>Advances the enumerator to the next element of the span.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
int index = _index + 1;
if (index < _span.Length)
{
_index = index;
return true;
}
return false;
}
/// <summary>Gets the element at the current position of the enumerator.</summary>
public ref readonly T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
// TODO https://github.com/dotnet/corefx/issues/24105:
// Change this to simply be:
// get => ref _span[_index];
// once ReadOnlySpan<T>'s indexer returns ref readonly.
if ((uint)_index >= (uint)_span.Length)
{
ThrowHelper.ThrowIndexOutOfRangeException();
}
return ref Unsafe.Add(ref _span.DangerousGetPinnableReference(), _index);
}
}
}
// These expose the internal representation for Span-related apis use only.
internal Pinnable<T> Pinnable => _pinnable;
internal IntPtr ByteOffset => _byteOffset;
//
// If the Span was constructed from an object,
//
// _pinnable = that object (unsafe-casted to a Pinnable<T>)
// _byteOffset = offset in bytes from "ref _pinnable.Data" to "ref span[0]"
//
// If the Span was constructed from a native pointer,
//
// _pinnable = null
// _byteOffset = the pointer
//
private readonly Pinnable<T> _pinnable;
private readonly IntPtr _byteOffset;
private readonly int _length;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Divan
{
/// <summary>
/// A CouchDB HTTP request with all its options. This is where we do the actual HTTP requests to CouchDB.
/// </summary>
public class CouchRequest : ICouchRequest
{
private const int UploadBufferSize = 100000;
private readonly ICouchDatabase db;
private Stream postStream;
private readonly ICouchServer server;
private string etag, etagToCheck;
private readonly Dictionary<string, string> headers = new Dictionary<string, string>();
// Query options
private string method = "GET"; // PUT, DELETE, POST, HEAD
private string mimeType;
private string path;
private string query;
private JToken result;
#region Contructors
public CouchRequest(ICouchServer server)
{
this.server = server;
}
public CouchRequest(ICouchDatabase db)
{
server = db.Server;
this.db = db;
}
#endregion
/// <summary>
/// Sets the e-tag value
/// </summary>
/// <param name="value">The e-tag value</param>
/// <returns>A CouchRequest with the new e-tag value</returns>
public ICouchRequest Etag(string value)
{
etagToCheck = value;
headers["If-Modified"] = value;
return this;
}
/// <summary>
/// Sets the absolute path in the query
/// </summary>
/// <param name="name">The absolute path</param>
/// <returns>A <see cref="CouchRequest"/> with the new path set.</returns>
public ICouchRequest Path(string name)
{
path = name;
return this;
}
/// <summary>
/// Sets the raw query information in the request. Don't forget to start with a question mark (?).
/// </summary>
/// <param name="value">The raw query</param>
/// <returns>A <see cref="CouchRequest"/> with the new query set.</returns>
public ICouchRequest Query(string value)
{
query = value;
return this;
}
public ICouchRequest QueryOptions(ICollection<KeyValuePair<string, string>> options)
{
if (options == null || options.Count == 0)
{
return this;
}
var sb = new StringBuilder();
sb.Append("?");
foreach (var q in options)
{
if (sb.Length > 1)
{
sb.Append("&");
}
sb.Append(HttpUtility.UrlEncode(q.Key));
sb.Append("=");
sb.Append(HttpUtility.UrlEncode(q.Value));
}
return Query(sb.ToString());
}
/// <summary>
/// Turn the request into a HEAD request, HEAD requests are problematic
/// under Mono 2.4, but has been fixed in later releases.
/// </summary>
public ICouchRequest Head()
{
// NOTE: We need to do this until next release of mono where HEAD requests have been fixed!
method = server.RunningOnMono ? "GET" : "HEAD";
return this;
}
public ICouchRequest Copy()
{
method = "COPY";
return this;
}
public ICouchRequest PostJson()
{
MimeTypeJson();
return Post();
}
public ICouchRequest Post()
{
method = "POST";
return this;
}
public ICouchRequest Get()
{
method = "GET";
return this;
}
public ICouchRequest Put()
{
method = "PUT";
return this;
}
public ICouchRequest Delete()
{
method = "DELETE";
return this;
}
public ICouchRequest Data(string data)
{
return Data(Encoding.UTF8.GetBytes(data));
}
public ICouchRequest Data(byte[] data)
{
postStream = new MemoryStream(data);
return this;
}
public ICouchRequest Data(Stream dataStream)
{
postStream = dataStream;
return this;
}
public ICouchRequest MimeType(string type)
{
mimeType = type;
return this;
}
public ICouchRequest MimeTypeJson()
{
MimeType("application/json");
return this;
}
public JObject Result()
{
return (JObject)result;
}
public T Result<T>() where T : JToken
{
return (T)result;
}
public string Etag()
{
return etag;
}
public ICouchRequest Check(string message)
{
try
{
if (result == null)
{
Parse();
}
if (!result["ok"].Value<bool>())
{
throw CouchException.Create(string.Format(CultureInfo.InvariantCulture, message + ": {0}", result));
}
return this;
}
catch (WebException e)
{
throw CouchException.Create(message, e);
}
}
private HttpWebRequest GetRequest()
{
var requestUri = new UriBuilder("http", server.Host, server.Port, ((db != null) ? db.Name + "/" : "") + path, query).Uri;
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request == null)
{
throw CouchException.Create("Failed to create request");
}
request.Timeout = 3600000; // 1 hour. May use System.Threading.Timeout.Infinite;
request.Method = method;
if (mimeType != null)
{
request.ContentType = mimeType;
}
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
if (!string.IsNullOrEmpty(server.EncodedCredentials))
{
request.Headers.Add("Authorization", server.EncodedCredentials);
}
if (postStream != null)
{
WriteData(request);
}
Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Request: {0} Method: {1}", requestUri, method));
return request;
}
private void WriteData(HttpWebRequest request)
{
request.ContentLength = postStream.Length;
using (Stream ps = request.GetRequestStream())
{
var buffer = new byte[UploadBufferSize];
int bytesRead;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
ps.Write(buffer, 0, bytesRead);
}
}
}
public JObject Parse()
{
return Parse<JObject>();
}
public T Parse<T>() where T : JToken
{
using (WebResponse response = GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
using (var textReader = new JsonTextReader(reader))
{
PickETag(response);
if (etagToCheck != null)
{
if (IsETagValid())
{
return null;
}
}
result = JToken.ReadFrom(textReader); // We know it is a top level JSON JObject.
}
}
}
}
return (T)result;
}
/// <summary>
/// Returns a Json stream from the server
/// </summary>
/// <returns></returns>
public JsonTextReader Stream()
{
return new JsonTextReader(new StreamReader(GetResponse().GetResponseStream()));
}
private void PickETag(WebResponse response)
{
etag = response.Headers["ETag"];
if (etag != null)
{
etag = etag.EndsWith("\"") ? etag.Substring(1, etag.Length - 2) : etag;
}
}
/// <summary>
/// Return the request as a plain string instead of trying to parse it.
/// </summary>
public string String()
{
using (WebResponse response = GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
PickETag(response);
if (etagToCheck != null)
{
if (IsETagValid())
{
return null;
}
}
return reader.ReadToEnd();
}
}
}
public WebResponse Response()
{
WebResponse response = GetResponse();
PickETag(response);
if (etagToCheck != null)
{
if (IsETagValid())
{
return null;
}
}
return response;
}
private WebResponse GetResponse()
{
return GetRequest().GetResponse();
}
public ICouchRequest Send()
{
using (WebResponse response = GetResponse())
{
PickETag(response);
return this;
}
}
public bool IsETagValid()
{
return etagToCheck == etag;
}
public ICouchRequest AddHeader(string key, string value)
{
headers[key] = value;
return this;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Construction;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild
{
/// <summary>
/// An API for loading msbuild project files.
/// </summary>
public class MSBuildProjectLoader
{
// the workspace that the projects and solutions are intended to be loaded into.
private readonly Workspace _workspace;
// used to protect access to the following mutable state
private readonly NonReentrantLock _dataGuard = new NonReentrantLock();
private ImmutableDictionary<string, string> _properties;
private readonly Dictionary<string, string> _extensionToLanguageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Create a new instance of an <see cref="MSBuildProjectLoader"/>.
/// </summary>
public MSBuildProjectLoader(Workspace workspace, ImmutableDictionary<string, string> properties = null)
{
_workspace = workspace;
_properties = properties ?? ImmutableDictionary<string, string>.Empty;
}
/// <summary>
/// The MSBuild properties used when interpreting project files.
/// These are the same properties that are passed to msbuild via the /property:<n>=<v> command line argument.
/// </summary>
public ImmutableDictionary<string, string> Properties
{
get { return _properties; }
}
/// <summary>
/// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects.
/// If the referenced project is already opened, the metadata will not be loaded.
/// If the metadata assembly cannot be found the referenced project will be opened instead.
/// </summary>
public bool LoadMetadataForReferencedProjects { get; set; } = false;
/// <summary>
/// Determines if unrecognized projects are skipped when solutions or projects are opened.
///
/// A project is unrecognized if it either has
/// a) an invalid file path,
/// b) a non-existent project file,
/// c) has an unrecognized file extension or
/// d) a file extension associated with an unsupported language.
///
/// If unrecognized projects cannot be skipped a corresponding exception is thrown.
/// </summary>
public bool SkipUnrecognizedProjects { get; set; } = true;
/// <summary>
/// Associates a project file extension with a language name.
/// </summary>
public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language)
{
if (language == null)
{
throw new ArgumentNullException(nameof(language));
}
if (projectFileExtension == null)
{
throw new ArgumentNullException(nameof(projectFileExtension));
}
using (_dataGuard.DisposableWait())
{
_extensionToLanguageMap[projectFileExtension] = language;
}
}
private const string SolutionDirProperty = "SolutionDir";
private void SetSolutionProperties(string solutionFilePath)
{
// When MSBuild is building an individual project, it doesn't define $(SolutionDir).
// However when building an .sln file, or when working inside Visual Studio,
// $(SolutionDir) is defined to be the directory where the .sln file is located.
// Some projects out there rely on $(SolutionDir) being set (although the best practice is to
// use MSBuildProjectDirectory which is always defined).
if (!string.IsNullOrEmpty(solutionFilePath))
{
string solutionDirectory = Path.GetDirectoryName(solutionFilePath);
if (!solutionDirectory.EndsWith(@"\", StringComparison.Ordinal))
{
solutionDirectory += @"\";
}
if (Directory.Exists(solutionDirectory))
{
_properties = _properties.SetItem(SolutionDirProperty, solutionDirectory);
}
}
}
/// <summary>
/// Loads the <see cref="SolutionInfo"/> for the specified solution file, including all projects referenced by the solution file and
/// all the projects referenced by the project files.
/// </summary>
public async Task<SolutionInfo> LoadSolutionInfoAsync(
string solutionFilePath,
CancellationToken cancellationToken = default(CancellationToken))
{
if (solutionFilePath == null)
{
throw new ArgumentNullException(nameof(solutionFilePath));
}
var absoluteSolutionPath = this.GetAbsoluteSolutionPath(solutionFilePath, Directory.GetCurrentDirectory());
using (_dataGuard.DisposableWait(cancellationToken))
{
this.SetSolutionProperties(absoluteSolutionPath);
}
VersionStamp version = default(VersionStamp);
Microsoft.Build.Construction.SolutionFile solutionFile = Microsoft.Build.Construction.SolutionFile.Parse(absoluteSolutionPath);
var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw;
// a list to accumulate all the loaded projects
var loadedProjects = new LoadState(null);
// load all the projects
foreach (var project in solutionFile.ProjectsInOrder)
{
cancellationToken.ThrowIfCancellationRequested();
if (project.ProjectType != SolutionProjectType.SolutionFolder)
{
var projectAbsolutePath = TryGetAbsolutePath(project.AbsolutePath, reportMode);
if (projectAbsolutePath != null)
{
if (TryGetLoaderFromProjectPath(projectAbsolutePath, reportMode, out var loader))
{
// projects get added to 'loadedProjects' as side-effect
// never prefer metadata when loading solution, all projects get loaded if they can.
var tmp = await GetOrLoadProjectAsync(projectAbsolutePath, loader, preferMetadata: false, loadedProjects: loadedProjects, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}
}
// construct workspace from loaded project infos
return SolutionInfo.Create(SolutionId.CreateNewId(debugName: absoluteSolutionPath), version, absoluteSolutionPath, loadedProjects.Projects);
}
internal string GetAbsoluteSolutionPath(string path, string baseDirectory)
{
string absolutePath;
try
{
absolutePath = GetAbsolutePath(path, baseDirectory);
}
catch (Exception)
{
throw new InvalidOperationException(string.Format(WorkspacesResources.Invalid_solution_file_path_colon_0, path));
}
if (!File.Exists(absolutePath))
{
throw new FileNotFoundException(string.Format(WorkspacesResources.Solution_file_not_found_colon_0, absolutePath));
}
return absolutePath;
}
/// <summary>
/// Loads the <see cref="ProjectInfo"/> from the specified project file and all referenced projects.
/// The first <see cref="ProjectInfo"/> in the result corresponds to the specified project file.
/// </summary>
public async Task<ImmutableArray<ProjectInfo>> LoadProjectInfoAsync(
string projectFilePath,
ImmutableDictionary<string, ProjectId> projectPathToProjectIdMap = null,
CancellationToken cancellationToken = default(CancellationToken))
{
if (projectFilePath == null)
{
throw new ArgumentNullException(nameof(projectFilePath));
}
this.TryGetAbsoluteProjectPath(projectFilePath, Directory.GetCurrentDirectory(), ReportMode.Throw, out var fullPath);
this.TryGetLoaderFromProjectPath(projectFilePath, ReportMode.Throw, out var loader);
var loadedProjects = new LoadState(projectPathToProjectIdMap);
var id = await this.LoadProjectAsync(fullPath, loader, this.LoadMetadataForReferencedProjects, loadedProjects, cancellationToken).ConfigureAwait(false);
var result = loadedProjects.Projects.Reverse().ToImmutableArray();
Debug.Assert(result[0].Id == id);
return result;
}
private class LoadState
{
private Dictionary<ProjectId, ProjectInfo> _projectIdToProjectInfoMap
= new Dictionary<ProjectId, ProjectInfo>();
/// <summary>
/// Used to memoize results of <see cref="ProjectAlreadyReferencesProject"/> calls.
/// Reset any time internal state is changed.
/// </summary>
private Dictionary<ProjectId, Dictionary<ProjectId, bool>> _projectAlreadyReferencesProjectResultCache
= new Dictionary<ProjectId, Dictionary<ProjectId, bool>>();
private readonly Dictionary<string, ProjectId> _projectPathToProjectIdMap
= new Dictionary<string, ProjectId>();
public LoadState(IReadOnlyDictionary<string, ProjectId> projectPathToProjectIdMap)
{
if (projectPathToProjectIdMap != null)
{
_projectPathToProjectIdMap.AddRange(projectPathToProjectIdMap);
}
}
public void Add(ProjectInfo info)
{
_projectIdToProjectInfoMap.Add(info.Id, info);
//Memoized results of ProjectAlreadyReferencesProject may no longer be correct;
//reset the cache.
_projectAlreadyReferencesProjectResultCache.Clear();
}
/// <summary>
/// Returns true if the project identified by <paramref name="fromProject"/> has a reference (even indirectly)
/// on the project identified by <paramref name="targetProject"/>.
/// </summary>
public bool ProjectAlreadyReferencesProject(ProjectId fromProject, ProjectId targetProject)
{
if ( !_projectAlreadyReferencesProjectResultCache.TryGetValue(fromProject, out var fromProjectMemo))
{
fromProjectMemo = new Dictionary<ProjectId, bool>();
_projectAlreadyReferencesProjectResultCache.Add(fromProject, fromProjectMemo);
}
if ( !fromProjectMemo.TryGetValue(targetProject, out var answer))
{
answer =
_projectIdToProjectInfoMap.TryGetValue(fromProject, out var info) &&
info.ProjectReferences.Any(pr =>
pr.ProjectId == targetProject ||
ProjectAlreadyReferencesProject(pr.ProjectId, targetProject)
);
fromProjectMemo.Add(targetProject, answer);
}
return answer;
}
public IEnumerable<ProjectInfo> Projects
{
get { return _projectIdToProjectInfoMap.Values; }
}
public ProjectId GetProjectId(string fullProjectPath)
{
_projectPathToProjectIdMap.TryGetValue(fullProjectPath, out var id);
return id;
}
public ProjectId GetOrCreateProjectId(string fullProjectPath)
{
if (!_projectPathToProjectIdMap.TryGetValue(fullProjectPath, out var id))
{
id = ProjectId.CreateNewId(debugName: fullProjectPath);
_projectPathToProjectIdMap.Add(fullProjectPath, id);
}
return id;
}
}
private async Task<ProjectId> GetOrLoadProjectAsync(string projectFilePath, IProjectFileLoader loader, bool preferMetadata, LoadState loadedProjects, CancellationToken cancellationToken)
{
var projectId = loadedProjects.GetProjectId(projectFilePath);
if (projectId == null)
{
projectId = await this.LoadProjectAsync(projectFilePath, loader, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false);
}
return projectId;
}
private async Task<ProjectId> LoadProjectAsync(string projectFilePath, IProjectFileLoader loader, bool preferMetadata, LoadState loadedProjects, CancellationToken cancellationToken)
{
Debug.Assert(projectFilePath != null);
Debug.Assert(loader != null);
var projectId = loadedProjects.GetOrCreateProjectId(projectFilePath);
var projectName = Path.GetFileNameWithoutExtension(projectFilePath);
var projectFile = await loader.LoadProjectFileAsync(projectFilePath, _properties, cancellationToken).ConfigureAwait(false);
if (projectFile.ErrorMessage != null)
{
ReportFailure(ReportMode.Log, GetMsbuildFailedMessage(projectFilePath, projectFile.ErrorMessage));
// if we failed during load there won't be any project file info, so bail early with empty project.
loadedProjects.Add(CreateEmptyProjectInfo(projectId, projectFilePath, loader.Language));
return projectId;
}
var projectFileInfo = await projectFile.GetProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);
if (projectFileInfo.ErrorMessage != null)
{
ReportFailure(ReportMode.Log, GetMsbuildFailedMessage(projectFilePath, projectFileInfo.ErrorMessage));
}
var projectDirectory = Path.GetDirectoryName(projectFilePath);
var outputFilePath = projectFileInfo.OutputFilePath;
var outputDirectory = Path.GetDirectoryName(outputFilePath);
var version = GetProjectVersion(projectFilePath);
// translate information from command line args
var commandLineParser = _workspace.Services.GetLanguageServices(loader.Language).GetService<ICommandLineParserService>();
var metadataService = _workspace.Services.GetService<IMetadataService>();
var analyzerService = _workspace.Services.GetService<IAnalyzerService>();
var commandLineArgs = commandLineParser.Parse(
arguments: projectFileInfo.CommandLineArgs,
baseDirectory: projectDirectory,
isInteractive: false,
sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory());
// we only support file paths in /r command line arguments
var resolver = new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory));
var metadataReferences = commandLineArgs.ResolveMetadataReferences(resolver);
var analyzerLoader = analyzerService.GetLoader();
foreach (var path in commandLineArgs.AnalyzerReferences.Select(r => r.FilePath))
{
analyzerLoader.AddDependencyLocation(path);
}
var analyzerReferences = commandLineArgs.ResolveAnalyzerReferences(analyzerLoader);
var defaultEncoding = commandLineArgs.Encoding;
// docs & additional docs
var docFileInfos = projectFileInfo.Documents.ToImmutableArrayOrEmpty();
var additionalDocFileInfos = projectFileInfo.AdditionalDocuments.ToImmutableArrayOrEmpty();
// check for duplicate documents
var allDocFileInfos = docFileInfos.AddRange(additionalDocFileInfos);
CheckDocuments(allDocFileInfos, projectFilePath, projectId);
var docs = new List<DocumentInfo>();
foreach (var docFileInfo in docFileInfos)
{
GetDocumentNameAndFolders(docFileInfo.LogicalPath, out var name, out var folders);
docs.Add(DocumentInfo.Create(
DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath),
name,
folders,
projectFile.GetSourceCodeKind(docFileInfo.FilePath),
new FileTextLoader(docFileInfo.FilePath, defaultEncoding),
docFileInfo.FilePath,
docFileInfo.IsGenerated));
}
var additionalDocs = new List<DocumentInfo>();
foreach (var docFileInfo in additionalDocFileInfos)
{
GetDocumentNameAndFolders(docFileInfo.LogicalPath, out var name, out var folders);
additionalDocs.Add(DocumentInfo.Create(
DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath),
name,
folders,
SourceCodeKind.Regular,
new FileTextLoader(docFileInfo.FilePath, defaultEncoding),
docFileInfo.FilePath,
docFileInfo.IsGenerated));
}
// project references
var resolvedReferences = await ResolveProjectReferencesAsync(
projectId, projectFilePath, projectFileInfo.ProjectReferences, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false);
// add metadata references for project refs converted to metadata refs
metadataReferences = metadataReferences.Concat(resolvedReferences.MetadataReferences);
// if the project file loader couldn't figure out an assembly name, make one using the project's file path.
var assemblyName = commandLineArgs.CompilationName;
if (string.IsNullOrWhiteSpace(assemblyName))
{
assemblyName = GetAssemblyNameFromProjectPath(projectFilePath);
}
// make sure that doc-comments at least get parsed.
var parseOptions = commandLineArgs.ParseOptions;
if (parseOptions.DocumentationMode == DocumentationMode.None)
{
parseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Parse);
}
// add all the extra options that are really behavior overrides
var compOptions = commandLineArgs.CompilationOptions
.WithXmlReferenceResolver(new XmlFileResolver(projectDirectory))
.WithSourceReferenceResolver(new SourceFileResolver(ImmutableArray<string>.Empty, projectDirectory))
// TODO: https://github.com/dotnet/roslyn/issues/4967
.WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray<string>.Empty, projectDirectory)))
.WithStrongNameProvider(new DesktopStrongNameProvider(ImmutableArray.Create(projectDirectory, outputFilePath)))
.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
loadedProjects.Add(
ProjectInfo.Create(
projectId,
version,
projectName,
assemblyName,
loader.Language,
projectFilePath,
outputFilePath,
compilationOptions: compOptions,
parseOptions: parseOptions,
documents: docs,
projectReferences: resolvedReferences.ProjectReferences,
metadataReferences: metadataReferences,
analyzerReferences: analyzerReferences,
additionalDocuments: additionalDocs,
isSubmission: false,
hostObjectType: null));
return projectId;
}
private static string GetMsbuildFailedMessage(string projectFilePath, string message)
{
if (string.IsNullOrWhiteSpace(message))
{
return string.Format(WorkspaceDesktopResources.Msbuild_failed_when_processing_the_file_0, projectFilePath);
}
else
{
return string.Format(WorkspaceDesktopResources.Msbuild_failed_when_processing_the_file_0_with_message_1, projectFilePath, message);
}
}
private static VersionStamp GetProjectVersion(string projectFilePath)
{
if (!string.IsNullOrEmpty(projectFilePath) && File.Exists(projectFilePath))
{
return VersionStamp.Create(File.GetLastWriteTimeUtc(projectFilePath));
}
else
{
return VersionStamp.Create();
}
}
private ProjectInfo CreateEmptyProjectInfo(ProjectId projectId, string projectFilePath, string language)
{
var languageService = _workspace.Services.GetLanguageServices(language);
var parseOptions = languageService.GetService<ISyntaxTreeFactoryService>().GetDefaultParseOptions();
var compilationOptions = languageService.GetService<ICompilationFactoryService>().GetDefaultCompilationOptions();
var projectName = Path.GetFileNameWithoutExtension(projectFilePath);
var version = GetProjectVersion(projectFilePath);
return ProjectInfo.Create(
projectId,
version,
projectName,
assemblyName: GetAssemblyNameFromProjectPath(projectFilePath),
language: language,
filePath: projectFilePath,
outputFilePath: string.Empty,
compilationOptions: compilationOptions,
parseOptions: parseOptions,
documents: SpecializedCollections.EmptyEnumerable<DocumentInfo>(),
projectReferences: SpecializedCollections.EmptyEnumerable<ProjectReference>(),
metadataReferences: SpecializedCollections.EmptyEnumerable<MetadataReference>(),
analyzerReferences: SpecializedCollections.EmptyEnumerable<AnalyzerReference>(),
additionalDocuments: SpecializedCollections.EmptyEnumerable<DocumentInfo>(),
isSubmission: false,
hostObjectType: null);
}
private static string GetAssemblyNameFromProjectPath(string projectFilePath)
{
var assemblyName = Path.GetFileNameWithoutExtension(projectFilePath);
// if this is still unreasonable, use a fixed name.
if (string.IsNullOrWhiteSpace(assemblyName))
{
assemblyName = "assembly";
}
return assemblyName;
}
private static readonly char[] s_directorySplitChars = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
private static void GetDocumentNameAndFolders(string logicalPath, out string name, out ImmutableArray<string> folders)
{
var pathNames = logicalPath.Split(s_directorySplitChars, StringSplitOptions.RemoveEmptyEntries);
if (pathNames.Length > 0)
{
if (pathNames.Length > 1)
{
folders = pathNames.Take(pathNames.Length - 1).ToImmutableArray();
}
else
{
folders = ImmutableArray.Create<string>();
}
name = pathNames[pathNames.Length - 1];
}
else
{
name = logicalPath;
folders = ImmutableArray.Create<string>();
}
}
private void CheckDocuments(IEnumerable<DocumentFileInfo> docs, string projectFilePath, ProjectId projectId)
{
var paths = new HashSet<string>();
foreach (var doc in docs)
{
if (paths.Contains(doc.FilePath))
{
_workspace.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Warning, string.Format(WorkspacesResources.Duplicate_source_file_0_in_project_1, doc.FilePath, projectFilePath), projectId));
}
paths.Add(doc.FilePath);
}
}
private class ResolvedReferences
{
public readonly List<ProjectReference> ProjectReferences = new List<ProjectReference>();
public readonly List<MetadataReference> MetadataReferences = new List<MetadataReference>();
}
private async Task<ResolvedReferences> ResolveProjectReferencesAsync(
ProjectId thisProjectId,
string thisProjectPath,
IReadOnlyList<ProjectFileReference> projectFileReferences,
bool preferMetadata,
LoadState loadedProjects,
CancellationToken cancellationToken)
{
var resolvedReferences = new ResolvedReferences();
var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw;
foreach (var projectFileReference in projectFileReferences)
{
if (TryGetAbsoluteProjectPath(projectFileReference.Path, Path.GetDirectoryName(thisProjectPath), reportMode, out var fullPath))
{
// if the project is already loaded, then just reference the one we have
var existingProjectId = loadedProjects.GetProjectId(fullPath);
if (existingProjectId != null)
{
resolvedReferences.ProjectReferences.Add(new ProjectReference(existingProjectId, projectFileReference.Aliases));
continue;
}
TryGetLoaderFromProjectPath(fullPath, ReportMode.Ignore, out var loader);
// get metadata if preferred or if loader is unknown
if (preferMetadata || loader == null)
{
var projectMetadata = await this.GetProjectMetadata(fullPath, projectFileReference.Aliases, _properties, cancellationToken).ConfigureAwait(false);
if (projectMetadata != null)
{
resolvedReferences.MetadataReferences.Add(projectMetadata);
continue;
}
}
// must load, so we really need loader
if (TryGetLoaderFromProjectPath(fullPath, reportMode, out loader))
{
// load the project
var projectId = await this.GetOrLoadProjectAsync(fullPath, loader, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false);
// If that other project already has a reference on us, this will cause a circularity.
// This check doesn't need to be in the "already loaded" path above, since in any circularity this path
// must be taken at least once.
if (loadedProjects.ProjectAlreadyReferencesProject(projectId, targetProject: thisProjectId))
{
// We'll try to make this metadata if we can
var projectMetadata = await this.GetProjectMetadata(fullPath, projectFileReference.Aliases, _properties, cancellationToken).ConfigureAwait(false);
if (projectMetadata != null)
{
resolvedReferences.MetadataReferences.Add(projectMetadata);
}
continue;
}
else
{
resolvedReferences.ProjectReferences.Add(new ProjectReference(projectId, projectFileReference.Aliases));
continue;
}
}
}
else
{
fullPath = projectFileReference.Path;
}
// cannot find metadata and project cannot be loaded, so leave a project reference to a non-existent project.
var id = loadedProjects.GetOrCreateProjectId(fullPath);
resolvedReferences.ProjectReferences.Add(new ProjectReference(id, projectFileReference.Aliases));
}
return resolvedReferences;
}
/// <summary>
/// Gets a MetadataReference to a project's output assembly.
/// </summary>
private async Task<MetadataReference> GetProjectMetadata(string projectFilePath, ImmutableArray<string> aliases, IDictionary<string, string> globalProperties, CancellationToken cancellationToken)
{
// use loader service to determine output file for project if possible
string outputFilePath = null;
try
{
outputFilePath = await ProjectFileLoader.GetOutputFilePathAsync(projectFilePath, globalProperties, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
_workspace.OnWorkspaceFailed(new WorkspaceDiagnostic(WorkspaceDiagnosticKind.Failure, e.Message));
}
if (outputFilePath != null && File.Exists(outputFilePath))
{
if (Workspace.TestHookStandaloneProjectsDoNotHoldReferences)
{
var documentationService = _workspace.Services.GetService<IDocumentationProviderService>();
var docProvider = documentationService.GetDocumentationProvider(outputFilePath);
var metadata = AssemblyMetadata.CreateFromImage(File.ReadAllBytes(outputFilePath));
return metadata.GetReference(
documentation: docProvider,
aliases: aliases,
display: outputFilePath);
}
else
{
var metadataService = _workspace.Services.GetService<IMetadataService>();
return metadataService.GetReference(outputFilePath, new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases));
}
}
return null;
}
private string TryGetAbsolutePath(string path, ReportMode mode)
{
try
{
path = Path.GetFullPath(path);
}
catch (Exception)
{
ReportFailure(mode, string.Format(WorkspacesResources.Invalid_project_file_path_colon_0, path));
return null;
}
if (!File.Exists(path))
{
ReportFailure(
mode,
string.Format(WorkspacesResources.Project_file_not_found_colon_0, path),
msg => new FileNotFoundException(msg));
return null;
}
return path;
}
internal bool TryGetLoaderFromProjectPath(string projectFilePath, out IProjectFileLoader loader)
{
return TryGetLoaderFromProjectPath(projectFilePath, ReportMode.Ignore, out loader);
}
private bool TryGetLoaderFromProjectPath(string projectFilePath, ReportMode mode, out IProjectFileLoader loader)
{
using (_dataGuard.DisposableWait())
{
// otherwise try to figure it out from extension
var extension = Path.GetExtension(projectFilePath);
if (extension.Length > 0 && extension[0] == '.')
{
extension = extension.Substring(1);
}
if (_extensionToLanguageMap.TryGetValue(extension, out var language))
{
if (_workspace.Services.SupportedLanguages.Contains(language))
{
loader = _workspace.Services.GetLanguageServices(language).GetService<IProjectFileLoader>();
}
else
{
loader = null;
this.ReportFailure(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language));
return false;
}
}
else
{
loader = ProjectFileLoader.GetLoaderForProjectFileExtension(_workspace, extension);
if (loader == null)
{
this.ReportFailure(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectFilePath, Path.GetExtension(projectFilePath)));
return false;
}
}
// since we have both C# and VB loaders in this same library, it no longer indicates whether we have full language support available.
if (loader != null)
{
language = loader.Language;
// check for command line parser existing... if not then error.
var commandLineParser = _workspace.Services.GetLanguageServices(language).GetService<ICommandLineParserService>();
if (commandLineParser == null)
{
loader = null;
this.ReportFailure(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language));
return false;
}
}
return loader != null;
}
}
private bool TryGetAbsoluteProjectPath(string path, string baseDirectory, ReportMode mode, out string absolutePath)
{
try
{
absolutePath = GetAbsolutePath(path, baseDirectory);
}
catch (Exception)
{
ReportFailure(mode, string.Format(WorkspacesResources.Invalid_project_file_path_colon_0, path));
absolutePath = null;
return false;
}
if (!File.Exists(absolutePath))
{
ReportFailure(
mode,
string.Format(WorkspacesResources.Project_file_not_found_colon_0, absolutePath),
msg => new FileNotFoundException(msg));
return false;
}
return true;
}
private static string GetAbsolutePath(string path, string baseDirectoryPath)
{
return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, baseDirectoryPath) ?? path);
}
private enum ReportMode
{
Throw,
Log,
Ignore
}
private void ReportFailure(ReportMode mode, string message, Func<string, Exception> createException = null)
{
switch (mode)
{
case ReportMode.Throw:
if (createException != null)
{
throw createException(message);
}
else
{
throw new InvalidOperationException(message);
}
case ReportMode.Log:
_workspace.OnWorkspaceFailed(new WorkspaceDiagnostic(WorkspaceDiagnosticKind.Failure, message));
break;
case ReportMode.Ignore:
default:
break;
}
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
#if !UNITY
#if XAMIOS || XAMDROID
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // XAMIOS || XAMDROID
#endif // !UNITY
namespace MsgPack
{
partial class MessagePackObjectDictionary
{
/// <summary>
/// Represents the collection of values in a <see cref="MessagePackObjectDictionary"/>.
/// </summary>
#if !SILVERLIGHT && !NETFX_CORE
[Serializable]
#endif
[DebuggerDisplay( "Count={Count}" )]
[DebuggerTypeProxy( typeof( CollectionDebuggerProxy<> ) )]
[SuppressMessage( "Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "ICollection implementing dictionary should return ICollection implementing values." )]
public sealed partial class ValueCollection : ICollection<MessagePackObject>, ICollection
{
private readonly MessagePackObjectDictionary _dictionary;
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public int Count
{
get { return this._dictionary.Count; }
}
bool ICollection<MessagePackObject>.IsReadOnly
{
get { return true; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return this; }
}
internal ValueCollection( MessagePackObjectDictionary dictionary )
{
#if !UNITY
Contract.Assert( dictionary != null, "dictionary != null" );
#endif // !UNITY
this._dictionary = dictionary;
}
/// <summary>
/// Copies the entire collection to a compatible one-dimensional array, starting at the beginning of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied from this dictionary.
/// The <see cref="Array"/> must have zero-based indexing.
/// </param>
public void CopyTo( MessagePackObject[] array )
{
if ( array == null )
{
throw new ArgumentNullException( "array" );
}
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
CollectionOperation.CopyTo( this, this.Count, 0, array, 0, this.Count );
}
/// <summary>
/// Copies the entire collection to a compatible one-dimensional array,
/// starting at the specified index of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied from this dictionary.
/// The <see cref="Array"/> must have zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in <paramref name="array"/> at which copying begins.
/// </param>
public void CopyTo( MessagePackObject[] array, int arrayIndex )
{
CollectionOperation.CopyTo( this, this.Count, 0, array, arrayIndex, this.Count );
}
/// <summary>
/// Copies a range of elements from this collection to a compatible one-dimensional array,
/// starting at the specified index of the target array.
/// </summary>
/// <param name="index">
/// The zero-based index in the source dictionary at which copying begins.
/// </param>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied from this dictionary.
/// The <see cref="Array"/> must have zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in <paramref name="array"/> at which copying begins.
/// </param>
/// <param name="count">
/// The number of elements to copy.
/// </param>
public void CopyTo( int index, MessagePackObject[] array, int arrayIndex, int count )
{
if ( array == null )
{
throw new ArgumentNullException( "array" );
}
if ( index < 0 )
{
throw new ArgumentOutOfRangeException( "index" );
}
if ( 0 < this.Count && this.Count <= index )
{
throw new ArgumentException( "Specified array is too small to complete copy operation.", "array" );
}
if ( arrayIndex < 0 )
{
throw new ArgumentOutOfRangeException( "arrayIndex" );
}
if ( count < 0 )
{
throw new ArgumentOutOfRangeException( "count" );
}
if ( array.Length - count <= arrayIndex )
{
throw new ArgumentException( "Specified array is too small to complete copy operation.", "array" );
}
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
CollectionOperation.CopyTo( this, this.Count, index, array, arrayIndex, count );
}
void ICollection.CopyTo( Array array, int arrayIndex )
{
CollectionOperation.CopyTo( this, this.Count, array, arrayIndex );
}
/// <summary>
/// Determines whether this collection contains a specific value.
/// </summary>
/// <param name="item">
/// The object to locate in this collection.</param>
/// <returns>
/// <c>true</c> if <paramref name="item"/> is found in this collection; otherwise, <c>false</c>.
/// </returns>
bool ICollection<MessagePackObject>.Contains( MessagePackObject item )
{
return this._dictionary.ContainsValue( item );
}
void ICollection<MessagePackObject>.Add( MessagePackObject item )
{
throw new NotSupportedException();
}
void ICollection<MessagePackObject>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<MessagePackObject>.Remove( MessagePackObject item )
{
throw new NotSupportedException();
}
/// <summary>
/// Returns an enumerator that iterates through this collction.
/// </summary>
/// <returns>
/// Returns an enumerator that iterates through this collction.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator( this._dictionary );
}
IEnumerator<MessagePackObject> IEnumerable<MessagePackObject>.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement.Metadata.Builders;
namespace OrchardCore.ContentManagement
{
public static class ContentExtensions
{
public const string WeldedPartSettingsName = "@WeldedPartSettings";
/// <summary>
/// These settings instruct merge to replace current value, even for null values.
/// </summary>
private static readonly JsonMergeSettings JsonMergeSettings = new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge };
/// <summary>
/// Gets a content element by its name.
/// </summary>
/// <typeparam name="TElement">The expected type of the content element.</typeparam>
/// <typeparam name="name">The name of the content element.</typeparam>
/// <returns>The content element instance or <code>null</code> if it doesn't exist.</returns>
public static TElement Get<TElement>(this ContentElement contentElement, string name) where TElement : ContentElement
{
return (TElement)contentElement.Get(typeof(TElement), name);
}
/// <summary>
/// Gets whether a content element has a specific element attached.
/// </summary>
/// <typeparam name="TElement">The expected type of the content element.</typeparam>
public static bool Has<TElement>(this ContentElement contentElement) where TElement : ContentElement
{
return contentElement.Has(typeof(TElement).Name);
}
/// <summary>
/// Gets a content element by its name.
/// </summary>
/// <typeparam name="contentElementType">The expected type of the content element.</typeparam>
/// <typeparam name="name">The name of the content element.</typeparam>
/// <returns>The content element instance or <code>null</code> if it doesn't exist.</returns>
public static ContentElement Get(this ContentElement contentElement, Type contentElementType, string name)
{
if (contentElement.Elements.TryGetValue(name, out var element))
{
return element;
}
var elementData = contentElement.Data[name] as JObject;
if (elementData == null)
{
return null;
}
var result = (ContentElement)elementData.ToObject(contentElementType);
result.Data = elementData;
result.ContentItem = contentElement.ContentItem;
contentElement.Elements[name] = result;
return result;
}
/// <summary>
/// Gets a content element by its name or create a new one.
/// </summary>
/// <typeparam name="TElement">The expected type of the content element.</typeparam>
/// <typeparam name="name">The name of the content element.</typeparam>
/// <returns>The content element instance or a new one if it doesn't exist.</returns>
public static TElement GetOrCreate<TElement>(this ContentElement contentElement, string name) where TElement : ContentElement, new()
{
var existing = contentElement.Get<TElement>(name);
if (existing == null)
{
var newElement = new TElement();
newElement.ContentItem = contentElement.ContentItem;
contentElement.Data[name] = newElement.Data;
contentElement.Elements[name] = newElement;
return newElement;
}
return existing;
}
/// <summary>
/// Adds a content element by name.
/// </summary>
/// <typeparam name="name">The name of the content element.</typeparam>
/// <typeparam name="element">The element to add to the <see cref="ContentItem"/>.</typeparam>
/// <returns>The current <see cref="ContentItem"/> instance.</returns>
public static ContentElement Weld(this ContentElement contentElement, string name, ContentElement element)
{
if (!contentElement.Data.ContainsKey(name))
{
element.Data = JObject.FromObject(element, ContentBuilderSettings.IgnoreDefaultValuesSerializer);
element.ContentItem = contentElement.ContentItem;
contentElement.Data[name] = element.Data;
contentElement.Elements[name] = element;
}
return contentElement;
}
/// <summary>
/// Welds a new part to the content item. If a part of the same type is already welded nothing is done.
/// This part can be not defined in Content Definitions.
/// </summary>
/// <typeparam name="TPart">The type of the part to be welded.</typeparam>
public static ContentElement Weld<TElement>(this ContentElement contentElement, object settings = null) where TElement : ContentElement, new()
{
var elementName = typeof(TElement).Name;
var elementData = contentElement.Data[elementName] as JObject;
if (elementData == null)
{
// build and welded the part
var part = new TElement();
contentElement.Weld(elementName, part);
}
JToken result;
if (!contentElement.Data.TryGetValue(WeldedPartSettingsName, out result))
{
contentElement.Data[WeldedPartSettingsName] = result = new JObject();
}
var weldedPartSettings = (JObject)result;
weldedPartSettings[elementName] = settings == null ? new JObject() : JObject.FromObject(settings, ContentBuilderSettings.IgnoreDefaultValuesSerializer);
return contentElement;
}
/// <summary>
/// Updates the content element with the specified name.
/// </summary>
/// <typeparam name="name">The name of the element to update.</typeparam>
/// <typeparam name="element">The content element instance to update.</typeparam>
/// <returns>The current <see cref="ContentItem"/> instance.</returns>
public static ContentElement Apply(this ContentElement contentElement, string name, ContentElement element)
{
var elementData = contentElement.Data[name] as JObject;
if (elementData != null)
{
elementData.Merge(JObject.FromObject(element), JsonMergeSettings);
}
else
{
elementData = JObject.FromObject(element, ContentBuilderSettings.IgnoreDefaultValuesSerializer);
contentElement.Data[name] = elementData;
}
element.Data = elementData;
element.ContentItem = contentElement.ContentItem;
// Replace the existing content element with the new one
contentElement.Elements[name] = element;
if (element is ContentField)
{
contentElement.ContentItem.Elements.Clear();
}
return contentElement;
}
/// <summary>
/// Updates the whole content.
/// </summary>
/// <typeparam name="element">The content element instance to update.</typeparam>
/// <returns>The current <see cref="ContentItem"/> instance.</returns>
public static ContentElement Apply(this ContentElement contentElement, ContentElement element)
{
if (contentElement.Data != null)
{
contentElement.Data.Merge(JObject.FromObject(element.Data), JsonMergeSettings);
}
else
{
contentElement.Data = JObject.FromObject(element.Data, ContentBuilderSettings.IgnoreDefaultValuesSerializer);
}
contentElement.Elements.Clear();
return contentElement;
}
/// <summary>
/// Modifies a new or existing content element by name.
/// </summary>
/// <typeparam name="name">The name of the content element to update.</typeparam>
/// <typeparam name="action">An action to apply on the content element.</typeparam>
/// <returns>The current <see cref="ContentElement"/> instance.</returns>
public static ContentElement Alter<TElement>(this ContentElement contentElement, string name, Action<TElement> action) where TElement : ContentElement, new()
{
var element = contentElement.GetOrCreate<TElement>(name);
action(element);
contentElement.Apply(name, element);
return contentElement;
}
/// <summary>
/// Updates the content item data.
/// </summary>
/// <returns>The current <see cref="ContentPart"/> instance.</returns>
public static ContentPart Apply(this ContentPart contentPart)
{
contentPart.ContentItem.Apply(contentPart.GetType().Name, contentPart);
return contentPart;
}
/// <summary>
/// Whether the content element is published or not.
/// </summary>
/// <param name="content">The content to check.</param>
/// <returns><c>True</c> if the content is published, <c>False</c> otherwise.</returns>
public static bool IsPublished(this IContent content)
{
return content.ContentItem != null && content.ContentItem.Published;
}
/// <summary>
/// Whether the content element has a draft or not.
/// </summary>
/// <param name="content">The content to check.</param>
/// <returns><c>True</c> if the content has a draft, <c>False</c> otherwise.</returns>
public static bool HasDraft(this IContent content)
{
return content.ContentItem != null && (!content.ContentItem.Published || !content.ContentItem.Latest);
}
/// <summary>
/// Gets all content elements of a specific type.
/// </summary>
/// <typeparam name="TElement">The expected type of the content elements.</typeparam>
/// <returns>The content element instances or empty sequence if no entries exist.</returns>
public static IEnumerable<TElement> OfType<TElement>(this ContentElement contentElement) where TElement : ContentElement
{
foreach (var part in contentElement.Elements)
{
var result = part.Value as TElement;
if (result != null)
{
yield return result;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public partial class StreamMethods
{
protected virtual Stream CreateStream()
{
return new MemoryStream();
}
protected virtual Stream CreateStream(int bufferSize)
{
return new MemoryStream(new byte[bufferSize]);
}
[Fact]
public void MemoryStreamSeekStress()
{
var ms1 = CreateStream();
SeekTest(ms1, false);
}
[Fact]
public void MemoryStreamSeekStressWithInitialBuffer()
{
var ms1 = CreateStream(1024);
SeekTest(ms1, false);
}
[Fact]
public async Task MemoryStreamStress()
{
var ms1 = CreateStream();
await StreamTest(ms1, false);
}
private static void SeekTest(Stream stream, bool fSuppres)
{
long lngPos;
byte btValue;
stream.Position = 0;
Assert.Equal(0, stream.Position);
int length = 1 << 10; //fancy way of writing 2 to the pow 10
byte[] btArr = new byte[length];
for (int i = 0; i < btArr.Length; i++)
btArr[i] = unchecked((byte)i);
if (stream.CanWrite)
stream.Write(btArr, 0, btArr.Length);
else
stream.Position = btArr.Length;
Assert.Equal(btArr.Length, stream.Position);
lngPos = stream.Seek(0, SeekOrigin.Begin);
Assert.Equal(0, lngPos);
Assert.Equal(0, stream.Position);
for (int i = 0; i < btArr.Length; i++)
{
if (stream.CanWrite)
{
btValue = (byte)stream.ReadByte();
Assert.Equal(btArr[i], btValue);
}
else
{
stream.Seek(1, SeekOrigin.Current);
}
Assert.Equal(i + 1, stream.Position);
}
Assert.Throws<IOException>(() => stream.Seek(-5, SeekOrigin.Begin));
lngPos = stream.Seek(5, SeekOrigin.Begin);
Assert.Equal(5, lngPos);
Assert.Equal(5, stream.Position);
lngPos = stream.Seek(5, SeekOrigin.End);
Assert.Equal(length + 5, lngPos);
Assert.Throws<IOException>(() => stream.Seek(-(btArr.Length + 1), SeekOrigin.End));
lngPos = stream.Seek(-5, SeekOrigin.End);
Assert.Equal(btArr.Length - 5, lngPos);
Assert.Equal(btArr.Length - 5, stream.Position);
lngPos = stream.Seek(0, SeekOrigin.End);
Assert.Equal(btArr.Length, stream.Position);
for (int i = btArr.Length; i > 0; i--)
{
stream.Seek(-1, SeekOrigin.Current);
Assert.Equal(i - 1, stream.Position);
}
Assert.Throws<IOException>(() => stream.Seek(-1, SeekOrigin.Current));
}
private static async Task StreamTest(Stream stream, bool fSuppress)
{
string strValue;
int iValue;
//[] We will first use the stream's 2 writing methods
int iLength = 1 << 10;
stream.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < iLength; i++)
stream.WriteByte(unchecked((byte)i));
byte[] btArr = new byte[iLength];
for (int i = 0; i < iLength; i++)
btArr[i] = unchecked((byte)i);
stream.Write(btArr, 0, iLength);
//we will write many things here using a binary writer
BinaryWriter bw1 = new BinaryWriter(stream);
bw1.Write(false);
bw1.Write(true);
for (int i = 0; i < 10; i++)
{
bw1.Write((byte)i);
bw1.Write((sbyte)i);
bw1.Write((short)i);
bw1.Write((char)i);
bw1.Write((ushort)i);
bw1.Write(i);
bw1.Write((uint)i);
bw1.Write((long)i);
bw1.Write((ulong)i);
bw1.Write((float)i);
bw1.Write((double)i);
}
//Some strings, chars and Bytes
char[] chArr = new char[iLength];
for (int i = 0; i < iLength; i++)
chArr[i] = (char)i;
bw1.Write(chArr);
bw1.Write(chArr, 512, 512);
bw1.Write(new string(chArr));
bw1.Write(new string(chArr));
//[] we will now read
stream.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < iLength; i++)
{
Assert.Equal(i % 256, stream.ReadByte());
}
btArr = new byte[iLength];
stream.Read(btArr, 0, iLength);
for (int i = 0; i < iLength; i++)
{
Assert.Equal(unchecked((byte)i), btArr[i]);
}
//Now, for the binary reader
BinaryReader br1 = new BinaryReader(stream);
Assert.False(br1.ReadBoolean());
Assert.True(br1.ReadBoolean());
for (int i = 0; i < 10; i++)
{
Assert.Equal( (byte)i, br1.ReadByte());
Assert.Equal((sbyte)i, br1.ReadSByte());
Assert.Equal((short)i, br1.ReadInt16());
Assert.Equal((char)i, br1.ReadChar());
Assert.Equal((ushort)i, br1.ReadUInt16());
Assert.Equal(i, br1.ReadInt32());
Assert.Equal((uint)i, br1.ReadUInt32());
Assert.Equal((long)i, br1.ReadInt64());
Assert.Equal((ulong)i, br1.ReadUInt64());
Assert.Equal((float)i, br1.ReadSingle());
Assert.Equal((double)i, br1.ReadDouble());
}
chArr = br1.ReadChars(iLength);
for (int i = 0; i < iLength; i++)
{
Assert.Equal((char)i, chArr[i]);
}
chArr = new char[512];
chArr = br1.ReadChars(iLength / 2);
for (int i = 0; i < iLength / 2; i++)
{
Assert.Equal((char)(iLength / 2 + i), chArr[i]);
}
chArr = new char[iLength];
for (int i = 0; i < iLength; i++)
chArr[i] = (char)i;
strValue = br1.ReadString();
Assert.Equal(new string(chArr), strValue);
strValue = br1.ReadString();
Assert.Equal(new string(chArr), strValue);
stream.Seek(1, SeekOrigin.Current); // In the original test, success here would end the test
//[] we will do some async tests here now
stream.Position = 0;
btArr = new byte[iLength];
for (int i = 0; i < iLength; i++)
btArr[i] = unchecked((byte)(i + 5));
await stream.WriteAsync(btArr, 0, btArr.Length);
stream.Position = 0;
for (int i = 0; i < iLength; i++)
{
Assert.Equal(unchecked((byte)(i + 5)), stream.ReadByte());
}
//we will read asynchronously
stream.Position = 0;
byte[] compArr = new byte[iLength];
iValue = await stream.ReadAsync(compArr, 0, compArr.Length);
Assert.Equal(btArr.Length, iValue);
for (int i = 0; i < iLength; i++)
{
Assert.Equal(compArr[i], btArr[i]);
}
}
[Fact]
public async Task FlushAsyncTest()
{
byte[] data = Enumerable.Range(0, 8000).Select(i => unchecked((byte)i)).ToArray();
Stream stream = CreateStream();
for (int i = 0; i < 4; i++)
{
await stream.WriteAsync(data, 2000 * i, 2000);
await stream.FlushAsync();
}
stream.Position = 0;
byte[] output = new byte[data.Length];
int bytesRead, totalRead = 0;
while ((bytesRead = await stream.ReadAsync(output, totalRead, data.Length - totalRead)) > 0)
totalRead += bytesRead;
Assert.Equal(data, output);
}
[Fact]
public void ArgumentValidation()
{
Stream stream = CreateStream();
Assert.Equal(TaskStatus.Canceled, stream.ReadAsync(new byte[1], 0, 1, new CancellationToken(canceled: true)).Status);
Assert.Equal(TaskStatus.Canceled, stream.WriteAsync(new byte[1], 0, 1, new CancellationToken(canceled: true)).Status);
Assert.Equal(TaskStatus.Canceled, stream.FlushAsync(new CancellationToken(canceled: true)).Status);
AssertExtensions.Throws<ArgumentNullException>("buffer", () => { stream.ReadAsync(null, 0, 0); });
AssertExtensions.Throws<ArgumentNullException>("buffer", () => { stream.WriteAsync(null, 0, 0); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => { stream.ReadAsync(new byte[1], -1, 0); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => { stream.WriteAsync(new byte[1], -1, 0); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => { stream.ReadAsync(new byte[1], 0, -1); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => { stream.WriteAsync(new byte[1], 0, -1); });
AssertExtensions.Throws<ArgumentException>(null, () => { stream.ReadAsync(new byte[1], 0, 2); });
AssertExtensions.Throws<ArgumentException>(null, () => { stream.WriteAsync(new byte[1], 0, 2); });
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Sql.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Sql.Fluent.Models;
using Microsoft.Azure.Management.Sql.Fluent.SqlFailoverGroup.Update;
using Microsoft.Azure.Management.Sql.Fluent.SqlFailoverGroupOperations.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlFailoverGroupOperations.SqlFailoverGroupOperationsDefinition;
using System.Collections.Generic;
using System;
/// <summary>
/// Implementation for SqlFailoverGroup.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LnNxbC5pbXBsZW1lbnRhdGlvbi5TcWxGYWlsb3Zlckdyb3VwSW1wbA==
internal partial class SqlFailoverGroupImpl :
ChildResource<
Models.FailoverGroupInner,
Microsoft.Azure.Management.Sql.Fluent.SqlServerImpl,
Microsoft.Azure.Management.Sql.Fluent.ISqlServer>,
ISqlFailoverGroup,
IUpdate,
ISqlFailoverGroupOperationsDefinition
{
private ISqlManager sqlServerManager;
private string resourceGroupName;
private string sqlServerName;
protected string sqlServerLocation;
private string name;
string ICreatable<ISqlFailoverGroup>.Name => this.Name();
/// <summary>
/// Creates an instance of external child resource in-memory.
/// </summary>
/// <param name="name">The name of this external child resource.</param>
/// <param name="parent">Reference to the parent of this external child resource.</param>
/// <param name="innerObject">Reference to the inner object representing this external child resource.</param>
/// <param name="sqlServerManager">Reference to the SQL server manager that accesses failover group operations.</param>
///GENMHASH:10321C7CB3A1E7C461BBEBEAA7FCEB2A:D04715006C36394109746FEBD7928CCE
internal SqlFailoverGroupImpl(string name, SqlServerImpl parent, FailoverGroupInner innerObject, ISqlManager sqlServerManager)
: base(innerObject, parent)
{
this.name = name;
this.sqlServerManager = sqlServerManager;
this.resourceGroupName = parent.ResourceGroupName;
this.sqlServerName = parent.Name;
this.sqlServerLocation = parent.RegionName;
}
/// <summary>
/// Creates an instance of external child resource in-memory.
/// </summary>
/// <param name="resourceGroupName">The resource group name.</param>
/// <param name="sqlServerName">The parent SQL server name.</param>
/// <param name="name">The name of this external child resource.</param>
/// <param name="innerObject">Reference to the inner object representing this external child resource.</param>
/// <param name="sqlServerManager">Reference to the SQL server manager that accesses failover group operations.</param>
///GENMHASH:2FFBF1911C3D11A4A0D6DB160D9678D8:A6FEE4EFEDACA027A0C59D9323BFCAC7
internal SqlFailoverGroupImpl(string resourceGroupName, string sqlServerName, string sqlServerLocation, string name, FailoverGroupInner innerObject, ISqlManager sqlServerManager)
: base(innerObject, null)
{
this.name = name;
this.sqlServerManager = sqlServerManager;
this.resourceGroupName = resourceGroupName;
this.sqlServerName = sqlServerName;
this.sqlServerLocation = sqlServerLocation;
}
/// <summary>
/// Creates an instance of external child resource in-memory.
/// </summary>
/// <param name="name">The name of this external child resource.</param>
/// <param name="innerObject">Reference to the inner object representing this external child resource.</param>
/// <param name="sqlServerManager">Reference to the SQL server manager that accesses failover group operations.</param>
///GENMHASH:FFACBC94C1D9864074BFA5694BF5256F:8A4C506BC6C1E988E601BB237AB86255
internal SqlFailoverGroupImpl(string name, FailoverGroupInner innerObject, ISqlManager sqlServerManager)
: base(innerObject, null)
{
this.name = name;
this.sqlServerManager = sqlServerManager;
if (innerObject != null && innerObject.Id != null)
{
if (innerObject.Id != null)
{
ResourceId resourceId = ResourceId.FromString(innerObject.Id);
this.resourceGroupName = resourceId.ResourceGroupName;
this.sqlServerName = resourceId.Parent.Name;
this.sqlServerLocation = innerObject.Location;
}
}
}
public override string Name()
{
return this.name;
}
///GENMHASH:59D8987F7EC078423F8247D1F7D40FBD:D2670680EF14BA9058384CB186AA4289
public string ReplicationState()
{
return this.Inner.ReplicationState;
}
///GENMHASH:C73D1F1D079CEECCF50424619696E723:2AA531F593D8FD511740FF63460BAB25
public SqlFailoverGroupImpl WithDatabaseIds(params string[] ids)
{
this.Inner.Databases = new List<String>();
foreach(var id in ids)
{
this.Inner.Databases.Add(id);
}
return this;
}
///GENMHASH:F340B9C68B7C557DDB54F615FEF67E89:3054A3D10ED7865B89395E7C007419C9
public string RegionName()
{
return this.Inner.Location;
}
///GENMHASH:6BCE517E09457FF033728269C8936E64:ECB4548536225101A4FBA7DFDB22FE6D
public SqlFailoverGroupImpl Update()
{
// This is the beginning of the update flow
return this;
}
///GENMHASH:0F77D8DDF25E08872FE274A3A166ADE5:6C95377B4560A9605FABA3A3ABEA3DD7
public SqlFailoverGroupImpl WithReadOnlyEndpointPolicyEnabled()
{
if (this.Inner.ReadOnlyEndpoint == null)
{
this.Inner.ReadOnlyEndpoint = new FailoverGroupReadOnlyEndpoint();
}
this.Inner.ReadOnlyEndpoint.FailoverPolicy = ReadOnlyEndpointFailoverPolicy.Enabled.Value;
return this;
}
///GENMHASH:96605E96D2B00E4658FBEC921BFDAEDB:890AE0BD0FB219762BA5213F6C979CED
public SqlFailoverGroupImpl WithAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(int gracePeriodInMinutes)
{
if (this.Inner.ReadWriteEndpoint == null)
{
this.Inner.ReadWriteEndpoint = new FailoverGroupReadWriteEndpoint();
}
this.Inner.ReadWriteEndpoint.FailoverPolicy = ReadWriteEndpointFailoverPolicy.Automatic.Value;
this.Inner.ReadWriteEndpoint.FailoverWithDataLossGracePeriodMinutes = gracePeriodInMinutes;
return this;
}
///GENMHASH:8442F1C1132907DE46B62B277F4EE9B7:605B8FC69F180AFC7CE18C754024B46C
public string Type()
{
return this.Inner.Type;
}
///GENMHASH:65E6085BB9054A86F6A84772E3F5A9EC:B061CBC11BB55C3C2C792B41D582EF90
public void Delete()
{
Extensions.Synchronize(() => this.DeleteAsync());
}
///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:30CAC49BAB6546B97833BEE6FBF589B0
protected async Task<Models.FailoverGroupInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await this.sqlServerManager.Inner.FailoverGroups
.GetAsync(this.resourceGroupName, this.sqlServerName, this.Name(), cancellationToken);
}
///GENMHASH:A4C5627076EA958957EDF76AFF379813:3360AEDBB627D649CA421A9FD4E7987C
public SqlFailoverGroupImpl WithManualReadWriteEndpointPolicy()
{
if (this.Inner.ReadWriteEndpoint == null)
{
this.Inner.ReadWriteEndpoint = new FailoverGroupReadWriteEndpoint();
}
this.Inner.ReadWriteEndpoint.FailoverPolicy = ReadWriteEndpointFailoverPolicy.Manual.Value;
this.Inner.ReadWriteEndpoint.FailoverWithDataLossGracePeriodMinutes = null;
return this;
}
///GENMHASH:B24A79172321D553084B735FBB0E7713:DF6A01D48A9534BC9AC582CF0EEDF4ED
public SqlFailoverGroupImpl WithNewDatabaseId(string id)
{
return this.WithDatabaseId(id);
}
///GENMHASH:02E62DCF3FCAA41C259D744B0174DC48:396C9E3144E9E77A131581AAEBCF990D
public FailoverGroupReplicationRole ReplicationRole()
{
return Models.FailoverGroupReplicationRole.Parse(this.Inner.ReplicationRole);
}
///GENMHASH:32E35A609CF1108D0FC5FAAF9277C1AA:E462F242E1761228E205CEE8F760EDF9
public SqlFailoverGroupImpl WithTags(IDictionary<string,string> tags)
{
this.Inner.Tags = new Dictionary<string,string>(tags);
return this;
}
///GENMHASH:20379C1CF9C8A8BD14B895EC33C6ABAF:9D9A4A7AA91755F446D78C73DA17C23B
public IReadOnlyList<Models.PartnerInfo> PartnerServers()
{
List<Models.PartnerInfo> result = new List<PartnerInfo>();
if (this.Inner.PartnerServers != null)
{
result.AddRange(this.Inner.PartnerServers);
}
return result.AsReadOnly();
}
///GENMHASH:66F8434BF34E8FA8C73DB8696A7EEB2C:A7C977C528FF94419AB1543C350B4DE1
public SqlFailoverGroupImpl WithReadOnlyEndpointPolicyDisabled()
{
if (this.Inner.ReadOnlyEndpoint == null)
{
this.Inner.ReadOnlyEndpoint = new FailoverGroupReadOnlyEndpoint();
}
this.Inner.ReadOnlyEndpoint.FailoverPolicy = ReadOnlyEndpointFailoverPolicy.Disabled.Value;
return this;
}
///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:899F2B088BBBD76CCBC31221756265BC
public string Id()
{
return this.Inner.Id;
}
///GENMHASH:35FBF194AC594444C9765ECADC1188F7:691378AE1888BF331479823D2FB2B948
public int ReadWriteEndpointDataLossGracePeriodMinutes()
{
return this.Inner.ReadWriteEndpoint != null ? this.Inner.ReadWriteEndpoint.FailoverWithDataLossGracePeriodMinutes.GetValueOrDefault(0) : 0;
}
///GENMHASH:507A92D4DCD93CE9595A78198DEBDFCF:16AD01F8BDD93611BB283CC787483C90
public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup> UpdateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await this.CreateResourceAsync(cancellationToken);
}
///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:A3C80C2E1D3C644B36853F85D52AB3A1
public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlFailoverGroup> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
//$ SqlFailoverGroupImpl self = this;
if (this.Inner.Location == null)
{
this.Inner.Location = this.sqlServerLocation;
}
var failoverGroupInner = await this.sqlServerManager.Inner.FailoverGroups
.CreateOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.Name(), this.Inner, cancellationToken);
this.SetInner(failoverGroupInner);
return this;
}
///GENMHASH:24DCA35ADCDF86A8A58340A3C0947F91:C0E448625A6CEF0869254B602F9C3284
public ReadWriteEndpointFailoverPolicy ReadWriteEndpointPolicy()
{
return this.Inner.ReadWriteEndpoint != null ? ReadWriteEndpointFailoverPolicy.Parse(this.Inner.ReadWriteEndpoint.FailoverPolicy) : null;
}
///GENMHASH:DF46C62E0E8998CD0340B3F8A136F135:A2E155D6CABB052D1DD1A6832C1DAA75
public IReadOnlyList<string> Databases()
{
List<string> result = new List<string>();
if (this.Inner.Databases != null)
{
result.AddRange(this.Inner.Databases);
}
return result.AsReadOnly();
}
///GENMHASH:E9EDBD2E8DC2C547D1386A58778AA6B9:7EBD4102FEBFB0AD7091EA1ACBD84F8B
public string ResourceGroupName()
{
return this.resourceGroupName;
}
///GENMHASH:2345D3E100BA4B78504A2CC57A361F1E:D6AE50211DB2EC346F816A0DDC4845EA
public SqlFailoverGroupImpl WithoutTag(string key)
{
if (this.Inner.Tags != null) {
this.Inner.Tags.Remove(key);
}
return this;
}
///GENMHASH:61F5809AB3B985C61AC40B98B1FBC47E:998832D58C98F6DCF3637916D2CC70B9
public string SqlServerName()
{
return this.sqlServerName;
}
///GENMHASH:546F275F5C716DBA4B4E3ED283223400:C9AFE281174DD8EB14C99E6BBD807BF6
public SqlFailoverGroupImpl WithExistingSqlServer(string resourceGroupName, string sqlServerName, string sqlServerLocation)
{
this.resourceGroupName = resourceGroupName;
this.sqlServerName = sqlServerName;
this.sqlServerLocation = sqlServerLocation;
return this;
}
///GENMHASH:A0EEAA3D4BFB322B5036FE92D9F0F641:29E97F88060ECB7FAB4757A4A7DF3007
public SqlFailoverGroupImpl WithExistingSqlServer(ISqlServer sqlServer)
{
this.resourceGroupName = sqlServer.ResourceGroupName;
this.sqlServerName = sqlServer.Name;
this.sqlServerLocation = sqlServer.RegionName;
return this;
}
///GENMHASH:4C8578EFF3D217B6EA41794FE6A88D90:6B0C5C338A1A92F53A398DAF56A562D3
public SqlFailoverGroupImpl WithDatabaseId(string id)
{
if (this.Inner.Databases == null)
{
this.Inner.Databases = new List<string>();
}
this.Inner.Databases.Add(id);
return this;
}
///GENMHASH:0FEDA307DAD2022B36843E8905D26EAD:95BA1017B6D636BB0934427C9B74AB8D
public async Task DeleteAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.DeleteResourceAsync(cancellationToken);
}
///GENMHASH:7A0398C4BB6EBF42CC817EE638D40E9C:2DC6B3BEB4C8A428A0339820143BFEB3
public string ParentId()
{
var resourceId = ResourceId.FromString(this.Id());
return resourceId?.Parent?.Id;
}
///GENMHASH:4B19A5F1B35CA91D20F63FBB66E86252:3E9F81F446FDF2A19095DC13C7608416
public IReadOnlyDictionary<string,string> Tags()
{
return (Dictionary<string, string>)this.Inner.Tags;
}
///GENMHASH:611FC8A9A0FAF341CC4E6B86DEC5706D:582413C777F5A88C5E3C9F9E04423F02
public SqlFailoverGroupImpl WithoutDatabaseId(string id)
{
if (this.Inner.Databases != null)
{
this.Inner.Databases.Remove(id);
}
return this;
}
///GENMHASH:FF80DD5A8C82E021759350836BD2FAD1:763203E811F074BDB99DB2C358722526
public SqlFailoverGroupImpl WithTag(string key, string value)
{
if (Inner.Tags == null)
{
Inner.Tags = new Dictionary<string, string>();
}
Inner.Tags[key] = value;
return this;
}
///GENMHASH:4F39D9594546CC718D25003EDD94C8D2:BA490544FC6653B09C582938721E6C2A
public ReadOnlyEndpointFailoverPolicy ReadOnlyEndpointPolicy()
{
return this.Inner.ReadOnlyEndpoint != null ? Models.ReadOnlyEndpointFailoverPolicy.Parse(this.Inner.ReadOnlyEndpoint.FailoverPolicy) : null;
}
///GENMHASH:E24A9768E91CD60E963E43F00AA1FDFE:72DE68F02B89E29132C1E5F2740CF122
public async Task DeleteResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.sqlServerManager.Inner.FailoverGroups
.DeleteAsync(this.resourceGroupName, this.sqlServerName, this.Name(), cancellationToken);
}
///GENMHASH:6A2970A94B2DD4A859B00B9B9D9691AD:6475F0E6B085A35B081FA09FFCBDDBF8
public Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region Region()
{
return Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region.Create(this.Inner.Location);
}
///GENMHASH:E298356333CE068A7E11D11B4BD192D2:61A9A437F28382C465CD3D2A914CA8EA
public SqlFailoverGroupImpl WithPartnerServerId(string id)
{
this.Inner.PartnerServers = new List<PartnerInfo>();
this.Inner.PartnerServers.Add(new PartnerInfo(){ Id = id });
return this;
}
public ISqlFailoverGroup Refresh()
{
return Extensions.Synchronize(() => this.RefreshAsync());
}
public async Task<ISqlFailoverGroup> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken))
{
this.SetInner(await this.GetInnerAsync(cancellationToken));
return this;
}
public ISqlFailoverGroup Apply()
{
return Extensions.Synchronize(() => this.ApplyAsync());
}
public async Task<ISqlFailoverGroup> ApplyAsync(CancellationToken cancellationToken = default(CancellationToken), bool multiThreaded = true)
{
return await this.UpdateResourceAsync(cancellationToken);
}
public ISqlFailoverGroup Create()
{
return Extensions.Synchronize(() => this.CreateAsync());
}
public async Task<ISqlFailoverGroup> CreateAsync(CancellationToken cancellationToken = default(CancellationToken), bool multiThreaded = true)
{
return await this.CreateResourceAsync(cancellationToken);
}
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using System;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
namespace MahApps.Metro.Controls
{
/// <summary>
/// enumeration for the different transition types
/// </summary>
public enum TransitionType
{
/// <summary>
/// Use the VisualState DefaultTransition
/// </summary>
Default,
/// <summary>
/// Use the VisualState Normal
/// </summary>
Normal,
/// <summary>
/// Use the VisualState UpTransition
/// </summary>
Up,
/// <summary>
/// Use the VisualState DownTransition
/// </summary>
Down,
/// <summary>
/// Use the VisualState RightTransition
/// </summary>
Right,
/// <summary>
/// Use the VisualState RightReplaceTransition
/// </summary>
RightReplace,
/// <summary>
/// Use the VisualState LeftTransition
/// </summary>
Left,
/// <summary>
/// Use the VisualState LeftReplaceTransition
/// </summary>
LeftReplace,
/// <summary>
/// Use a custom VisualState, the name must be set using CustomVisualStatesName property
/// </summary>
Custom
}
/// <summary>
/// A ContentControl that animates content as it loads and unloads.
/// </summary>
public class TransitioningContentControl : ContentControl
{
internal const string PresentationGroup = "PresentationStates";
internal const string NormalState = "Normal";
internal const string PreviousContentPresentationSitePartName = "PreviousContentPresentationSite";
internal const string CurrentContentPresentationSitePartName = "CurrentContentPresentationSite";
private ContentPresenter currentContentPresentationSite;
private ContentPresenter previousContentPresentationSite;
private bool allowIsTransitioningPropertyWrite;
private Storyboard currentTransition;
public event RoutedEventHandler TransitionCompleted;
public const TransitionType DefaultTransitionState = TransitionType.Default;
public static readonly DependencyProperty IsTransitioningProperty = DependencyProperty.Register("IsTransitioning", typeof(bool), typeof(TransitioningContentControl), new PropertyMetadata(OnIsTransitioningPropertyChanged));
public static readonly DependencyProperty TransitionProperty = DependencyProperty.Register("Transition", typeof(TransitionType), typeof(TransitioningContentControl), new FrameworkPropertyMetadata(TransitionType.Default, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.Inherits, OnTransitionPropertyChanged));
public static readonly DependencyProperty RestartTransitionOnContentChangeProperty = DependencyProperty.Register("RestartTransitionOnContentChange", typeof(bool), typeof(TransitioningContentControl), new PropertyMetadata(false, OnRestartTransitionOnContentChangePropertyChanged));
public static readonly DependencyProperty CustomVisualStatesProperty = DependencyProperty.Register("CustomVisualStates", typeof(ObservableCollection<VisualState>), typeof(TransitioningContentControl), new PropertyMetadata(null));
public static readonly DependencyProperty CustomVisualStatesNameProperty = DependencyProperty.Register("CustomVisualStatesName", typeof(string), typeof(TransitioningContentControl), new PropertyMetadata("CustomTransition"));
public ObservableCollection<VisualState> CustomVisualStates
{
get { return (ObservableCollection<VisualState>)this.GetValue(CustomVisualStatesProperty); }
set { this.SetValue(CustomVisualStatesProperty, value); }
}
/// <summary>
/// Gets or sets the name of the custom transition visual state.
/// </summary>
public string CustomVisualStatesName
{
get { return (string)this.GetValue(CustomVisualStatesNameProperty); }
set { this.SetValue(CustomVisualStatesNameProperty, value); }
}
/// <summary>
/// Gets/sets if the content is transitioning.
/// </summary>
public bool IsTransitioning
{
get { return (bool)this.GetValue(IsTransitioningProperty); }
private set
{
this.allowIsTransitioningPropertyWrite = true;
this.SetValue(IsTransitioningProperty, value);
this.allowIsTransitioningPropertyWrite = false;
}
}
public TransitionType Transition
{
get { return (TransitionType)this.GetValue(TransitionProperty); }
set { this.SetValue(TransitionProperty, value); }
}
public bool RestartTransitionOnContentChange
{
get { return (bool)this.GetValue(RestartTransitionOnContentChangeProperty); }
set { this.SetValue(RestartTransitionOnContentChangeProperty, value); }
}
private static void OnIsTransitioningPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var source = (TransitioningContentControl)d;
if (!source.allowIsTransitioningPropertyWrite)
{
source.IsTransitioning = (bool)e.OldValue;
throw new InvalidOperationException();
}
}
private Storyboard CurrentTransition
{
get { return this.currentTransition; }
set
{
// decouple event
if (this.currentTransition != null)
{
this.currentTransition.Completed -= this.OnTransitionCompleted;
}
this.currentTransition = value;
if (this.currentTransition != null)
{
this.currentTransition.Completed += this.OnTransitionCompleted;
}
}
}
private static void OnTransitionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var source = (TransitioningContentControl)d;
var oldTransition = (TransitionType)e.OldValue;
var newTransition = (TransitionType)e.NewValue;
if (source.IsTransitioning)
{
source.AbortTransition();
}
// find new transition
Storyboard newStoryboard = source.GetStoryboard(newTransition);
// unable to find the transition.
if (newStoryboard == null)
{
// could be during initialization of xaml that presentationgroups was not yet defined
if (VisualStates.TryGetVisualStateGroup(source, PresentationGroup) == null)
{
// will delay check
source.CurrentTransition = null;
}
else
{
// revert to old value
source.SetValue(TransitionProperty, oldTransition);
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Temporary removed exception message", newTransition));
}
}
else
{
source.CurrentTransition = newStoryboard;
}
}
private static void OnRestartTransitionOnContentChangePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TransitioningContentControl)d).OnRestartTransitionOnContentChangeChanged((bool)e.OldValue, (bool)e.NewValue);
}
protected virtual void OnRestartTransitionOnContentChangeChanged(bool oldValue, bool newValue)
{
}
public TransitioningContentControl()
{
this.CustomVisualStates = new ObservableCollection<VisualState>();
this.DefaultStyleKey = typeof(TransitioningContentControl);
}
public override void OnApplyTemplate()
{
if (this.IsTransitioning)
{
this.AbortTransition();
}
if (this.CustomVisualStates != null && this.CustomVisualStates.Any())
{
var presentationGroup = VisualStates.TryGetVisualStateGroup(this, PresentationGroup);
if (presentationGroup != null)
{
foreach (var state in this.CustomVisualStates)
{
presentationGroup.States.Add(state);
}
}
}
base.OnApplyTemplate();
this.previousContentPresentationSite = this.GetTemplateChild(PreviousContentPresentationSitePartName) as ContentPresenter;
this.currentContentPresentationSite = this.GetTemplateChild(CurrentContentPresentationSitePartName) as ContentPresenter;
if (this.currentContentPresentationSite != null)
{
if (this.ContentTemplateSelector != null)
{
this.currentContentPresentationSite.ContentTemplate = this.ContentTemplateSelector.SelectTemplate(this.Content, this);
}
else
{
this.currentContentPresentationSite.ContentTemplate = this.ContentTemplate;
}
this.currentContentPresentationSite.Content = this.Content;
}
// hookup currenttransition
Storyboard transition = this.GetStoryboard(this.Transition);
this.CurrentTransition = transition;
if (transition == null)
{
var invalidTransition = this.Transition;
// revert to default
this.Transition = DefaultTransitionState;
throw new ArgumentException(string.Format("'{0}' Transition could not be found!", invalidTransition), "Transition");
}
VisualStateManager.GoToState(this, NormalState, false);
}
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
this.StartTransition(oldContent, newContent);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "newContent", Justification = "Should be used in the future.")]
private void StartTransition(object oldContent, object newContent)
{
// both presenters must be available, otherwise a transition is useless.
if (this.currentContentPresentationSite != null && this.previousContentPresentationSite != null)
{
if (this.RestartTransitionOnContentChange)
{
this.CurrentTransition.Completed -= this.OnTransitionCompleted;
}
if (this.ContentTemplateSelector != null)
{
this.previousContentPresentationSite.ContentTemplate = this.ContentTemplateSelector.SelectTemplate(oldContent, this);
this.currentContentPresentationSite.ContentTemplate = this.ContentTemplateSelector.SelectTemplate(newContent, this);
}
else
{
this.previousContentPresentationSite.ContentTemplate = this.ContentTemplate;
this.currentContentPresentationSite.ContentTemplate = this.ContentTemplate;
}
this.currentContentPresentationSite.Content = newContent;
this.previousContentPresentationSite.Content = oldContent;
// and start a new transition
if (!this.IsTransitioning || this.RestartTransitionOnContentChange)
{
if (this.RestartTransitionOnContentChange)
{
this.CurrentTransition.Completed += this.OnTransitionCompleted;
}
this.IsTransitioning = true;
VisualStateManager.GoToState(this, NormalState, false);
VisualStateManager.GoToState(this, this.GetTransitionName(this.Transition), true);
}
}
}
/// <summary>
/// Reload the current transition if the content is the same.
/// </summary>
public void ReloadTransition()
{
// both presenters must be available, otherwise a transition is useless.
if (this.currentContentPresentationSite != null && this.previousContentPresentationSite != null)
{
if (this.RestartTransitionOnContentChange)
{
this.CurrentTransition.Completed -= this.OnTransitionCompleted;
}
if (!this.IsTransitioning || this.RestartTransitionOnContentChange)
{
if (this.RestartTransitionOnContentChange)
{
this.CurrentTransition.Completed += this.OnTransitionCompleted;
}
this.IsTransitioning = true;
VisualStateManager.GoToState(this, NormalState, false);
VisualStateManager.GoToState(this, this.GetTransitionName(this.Transition), true);
}
}
}
private void OnTransitionCompleted(object sender, EventArgs e)
{
var clockGroup = sender as ClockGroup;
this.AbortTransition();
if (clockGroup == null || clockGroup.CurrentState == ClockState.Stopped)
{
this.TransitionCompleted?.Invoke(this, new RoutedEventArgs());
}
}
public void AbortTransition()
{
// go to normal state and release our hold on the old content.
VisualStateManager.GoToState(this, NormalState, false);
this.IsTransitioning = false;
if (this.previousContentPresentationSite != null)
{
this.previousContentPresentationSite.ContentTemplate = null;
this.previousContentPresentationSite.Content = null;
}
}
private Storyboard GetStoryboard(TransitionType newTransition)
{
VisualStateGroup presentationGroup = VisualStates.TryGetVisualStateGroup(this, PresentationGroup);
Storyboard newStoryboard = null;
if (presentationGroup != null)
{
var transitionName = this.GetTransitionName(newTransition);
newStoryboard = presentationGroup.States
.OfType<VisualState>()
.Where(state => state.Name == transitionName)
.Select(state => state.Storyboard)
.FirstOrDefault();
}
return newStoryboard;
}
private string GetTransitionName(TransitionType transition)
{
switch (transition)
{
default:
case TransitionType.Default:
return "DefaultTransition";
case TransitionType.Normal:
return "Normal";
case TransitionType.Up:
return "UpTransition";
case TransitionType.Down:
return "DownTransition";
case TransitionType.Right:
return "RightTransition";
case TransitionType.RightReplace:
return "RightReplaceTransition";
case TransitionType.Left:
return "LeftTransition";
case TransitionType.LeftReplace:
return "LeftReplaceTransition";
case TransitionType.Custom:
return this.CustomVisualStatesName;
}
}
}
}
| |
//
// Pkcs9SigningTimeTest.cs - NUnit tests for Pkcs9SigningTime
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using NUnit.Framework;
using System;
using System.Collections;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Text;
namespace MonoTests.System.Security.Cryptography.Pkcs {
[TestFixture]
public class Pkcs9SigningTimeTest {
static string signingTimeOid = "1.2.840.113549.1.9.5";
static string signingTimeName = "Signing Time";
static DateTime mono10release = new DateTime (632241648000000000);
[Test]
public void DateTime_Mono10Release ()
{
// some tests fails if the assumption fails
Assert.AreEqual ("040630040000Z", mono10release.ToString ("yyMMddhhmmssZ"), "Z");
}
[Test]
public void Constructor_Empty ()
{
Pkcs9SigningTime st = new Pkcs9SigningTime ();
Assert.AreEqual (signingTimeName, st.Oid.FriendlyName, "Oid.FriendlyName");
Assert.AreEqual (signingTimeOid, st.Oid.Value, "Oid.Value");
Assert.AreEqual (15, st.RawData.Length, "RawData.Length");
Assert.AreEqual (BitConverter.ToString (st.RawData).ToLower ().Replace ("-", " "), st.Format (true), "Format(true)");
Assert.AreEqual (BitConverter.ToString (st.RawData).ToLower ().Replace ("-", " "), st.Format (false), "Format(false)");
}
[Test]
public void Constructor_DateTime_Now ()
{
Pkcs9SigningTime st = new Pkcs9SigningTime (DateTime.UtcNow);
Assert.AreEqual (signingTimeName, st.Oid.FriendlyName, "Oid.FriendlyName");
Assert.AreEqual (signingTimeOid, st.Oid.Value, "Oid.Value");
Assert.AreEqual (15, st.RawData.Length, "RawData.Length");
Assert.AreEqual (BitConverter.ToString (st.RawData).ToLower ().Replace ("-", " "), st.Format (true), "Format(true)");
Assert.AreEqual (BitConverter.ToString (st.RawData).ToLower ().Replace ("-", " "), st.Format (false), "Format(false)");
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void Constructor_DateTime_MinValue ()
{
Pkcs9SigningTime st = new Pkcs9SigningTime (DateTime.MinValue);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void Constructor_DateTime_1600 ()
{
DateTime dt = new DateTime (1600, 12, 31, 11, 59, 59);
Pkcs9SigningTime st = new Pkcs9SigningTime (dt);
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void Constructor_DateTime_1601 ()
{
DateTime dt = new DateTime (1601, 01, 01, 00, 00, 00);
Pkcs9SigningTime st = new Pkcs9SigningTime (dt);
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void Constructor_DateTime_MaxValue ()
{
Pkcs9SigningTime st = new Pkcs9SigningTime (DateTime.MaxValue);
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void Constructor_DateTime_Before1950 ()
{
DateTime dt = new DateTime (1949, 12, 31, 11, 59, 59);
// UTCTIME (0x17), i.e. 2 digits years, limited to 1950-2050
Pkcs9SigningTime st = new Pkcs9SigningTime (dt);
}
[Test]
public void Constructor_DateTime_After1950 ()
{
DateTime dt = new DateTime (1950, 01, 01, 00, 00, 00);
// UTCTIME (0x17), i.e. 2 digits years, limited to 1950-2050
Pkcs9SigningTime st = new Pkcs9SigningTime (dt);
Assert.AreEqual (signingTimeName, st.Oid.FriendlyName, "Oid.FriendlyName");
Assert.AreEqual (signingTimeOid, st.Oid.Value, "Oid.Value");
Assert.AreEqual (15, st.RawData.Length, "RawData.Length");
Assert.AreEqual ("17-0D-35-30-30-31-30-31-30-30-30-30-30-30-5A", BitConverter.ToString (st.RawData));
Assert.AreEqual (dt, st.SigningTime, "st.SigningTime");
Assert.AreEqual ("17 0d 35 30 30 31 30 31 30 30 30 30 30 30 5a", st.Format (true), "Format(true)");
Assert.AreEqual ("17 0d 35 30 30 31 30 31 30 30 30 30 30 30 5a", st.Format (false), "Format(false)");
}
[Test]
public void Constructor_DateTime_Before2050 ()
{
DateTime dt = new DateTime (2049, 12, 31, 11, 59, 59);
// up to 2050 encoding should stay with UTCTIME (0x17), i.e. 2 digits years
Pkcs9SigningTime st = new Pkcs9SigningTime (dt);
Assert.AreEqual (signingTimeName, st.Oid.FriendlyName, "Oid.FriendlyName");
Assert.AreEqual (signingTimeOid, st.Oid.Value, "Oid.Value");
Assert.AreEqual (15, st.RawData.Length, "RawData.Length");
Assert.AreEqual ("17-0D-34-39-31-32-33-31-31-31-35-39-35-39-5A", BitConverter.ToString (st.RawData));
Assert.AreEqual (dt, st.SigningTime, "st.SigningTime");
Assert.AreEqual ("17 0d 34 39 31 32 33 31 31 31 35 39 35 39 5a", st.Format (true), "Format(true)");
Assert.AreEqual ("17 0d 34 39 31 32 33 31 31 31 35 39 35 39 5a", st.Format (false), "Format(false)");
}
[Test]
[ExpectedException (typeof (CryptographicException))]
public void Constructor_DateTime_After2050 ()
{
DateTime dt = new DateTime (2050, 01, 01, 00, 00, 00);
// in 2050 encoding should switch to GENERALIZEDTIME (0x18), i.e. 4 digits years
Pkcs9SigningTime st = new Pkcs9SigningTime (dt);
}
[Test]
public void Constructor_DateTime ()
{
Pkcs9SigningTime st = new Pkcs9SigningTime (mono10release);
Assert.AreEqual (signingTimeName, st.Oid.FriendlyName, "Oid.FriendlyName");
Assert.AreEqual (signingTimeOid, st.Oid.Value, "Oid.Value");
Assert.AreEqual (15, st.RawData.Length, "RawData.Length");
Assert.AreEqual ("17-0D-30-34-30-36-33-30-30-34-30-30-30-30-5A", BitConverter.ToString (st.RawData), "RawData");
Assert.AreEqual (mono10release, st.SigningTime, "st.SigningTime");
Assert.AreEqual ("17 0d 30 34 30 36 33 30 30 34 30 30 30 30 5a", st.Format (true), "Format(true)");
Assert.AreEqual ("17 0d 30 34 30 36 33 30 30 34 30 30 30 30 5a", st.Format (false), "Format(false)");
}
[Test]
public void Constructor_Bytes ()
{
byte[] date = new byte [15] { 0x17, 0x0D, 0x30, 0x34, 0x30, 0x36, 0x33, 0x30, 0x30, 0x34, 0x30, 0x30, 0x30, 0x30, 0x5A };
Pkcs9SigningTime st = new Pkcs9SigningTime (date);
Assert.AreEqual (signingTimeName, st.Oid.FriendlyName, "Oid.FriendlyName");
Assert.AreEqual (signingTimeOid, st.Oid.Value, "Oid.Value");
Assert.AreEqual (15, st.RawData.Length, "RawData.Length");
Assert.AreEqual ("17-0D-30-34-30-36-33-30-30-34-30-30-30-30-5A", BitConverter.ToString (st.RawData), "RawData");
Assert.AreEqual (mono10release, st.SigningTime, "st.SigningTime");
Assert.AreEqual ("17 0d 30 34 30 36 33 30 30 34 30 30 30 30 5a", st.Format (true), "Format(true)");
Assert.AreEqual ("17 0d 30 34 30 36 33 30 30 34 30 30 30 30 5a", st.Format (false), "Format(false)");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Constructor_Bytes_Null ()
{
Pkcs9SigningTime st = new Pkcs9SigningTime (null);
}
[Test]
// [Ignore ("MS returns bad results (original time) - Mono needs to override CopyFrom to fix")]
// http://lab.msdn.microsoft.com/ProductFeedback/viewfeedback.aspx?feedbackid=66943396-ad73-497f-82ae-090b87ffcb4e
public void CopyFrom ()
{
Pkcs9SigningTime st1 = new Pkcs9SigningTime (mono10release);
Pkcs9SigningTime st2 = new Pkcs9SigningTime (DateTime.UtcNow);
st1.CopyFrom (st2);
Assert.AreEqual (st2.Oid.FriendlyName, st1.Oid.FriendlyName, "Oid.FriendlyName");
Assert.AreEqual (st2.Oid.Value, st1.Oid.Value, "Oid.Value");
Assert.AreEqual (BitConverter.ToString (st2.RawData), BitConverter.ToString (st1.RawData), "RawData");
// Note: Some timing resolution is lost by goind to ASN.1
Assert.AreEqual (st2.SigningTime.ToString (), st1.SigningTime.ToString (), "SigningTime");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CopyFrom_Null ()
{
new Pkcs9SigningTime (mono10release).CopyFrom (null);
}
[Test]
// [Ignore ("MS doesn't throw but returns bad results - Mono needs to override CopyFrom to fix")]
// http://lab.msdn.microsoft.com/ProductFeedback/viewfeedback.aspx?feedbackid=66943396-ad73-497f-82ae-090b87ffcb4e
[ExpectedException (typeof (CryptographicException))]
public void CopyFrom_Bad ()
{
Pkcs9SigningTime st = new Pkcs9SigningTime (mono10release);
Pkcs9DocumentName dn = new Pkcs9DocumentName ("Mono");
st.CopyFrom (dn);
Assert.AreEqual (dn.Oid.FriendlyName, st.Oid.FriendlyName, "Oid.FriendlyName");
Assert.AreEqual (dn.Oid.Value, st.Oid.Value, "Oid.Value");
Assert.AreEqual (BitConverter.ToString (dn.RawData), BitConverter.ToString (st.RawData), "RawData");
// wrong ASN.1
Assert.AreEqual (mono10release, st.SigningTime, "SigningTime");
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
namespace AdmxPolicy
{
[Flags]
public enum RegistryTypes
{
Unknown = 0,
LocalMachine = 1,
CurrentUser = 2,
Both = LocalMachine + CurrentUser
}
public sealed class AdmlResource
{
private string _DisplayName;
public string DisplayName { get { return _DisplayName; } }
private string _Description;
public string Description { get { return _Description; } }
private Dictionary<string, string> _Strings = new Dictionary<string, string>();
public Dictionary<string, string> Strings { get { return _Strings; } }
private Dictionary<string, string> _Windows = new Dictionary<string, string>();
public Dictionary<string, string> Windows { get { return _Windows; } }
public AdmlResource()
{
_DisplayName = "";
_Description = "";
}
public AdmlResource(string displayName, string description)
{
_DisplayName = displayName;
_Description = description;
}
}
public sealed class AdmxFileInfo
{
private string _Name;
public string Name { get { return _Name; } }
private string _DisplayName;
public string DisplayName { get { return _DisplayName; } }
private string _Description;
public string Description { get { return _Description; } }
private List<CategoryInfo> _Categories = new List<CategoryInfo>();
public List<CategoryInfo> Categories { get { return _Categories; } }
public AdmxFileInfo(string name, string displayName, string description)
{
_Name = name;
_DisplayName = displayName;
_Description = description;
}
public override string ToString()
{
return _Name;
}
}
public sealed class CategoryInfo
{
private string _Name;
public string Name { get { return _Name; } }
private string _DisplayName;
public string DisplayName { get { return _DisplayName; } }
public CategoryInfo(string name, string displayName)
{
_Name = name;
_DisplayName = displayName;
}
}
public sealed class PolicyInfo
{
private AdmxFileInfo _FileInfo;
public AdmxFileInfo FileInfo { get { return _FileInfo; } }
public string FileName { get { return _FileInfo == null ? "" : _FileInfo.Name; } }
private string _Name;
public string Name { get { return _Name; } }
private string _DisplayName;
public string DisplayName { get { return _DisplayName; } }
private string _ExplainText;
public string ExplainText { get { return _ExplainText; } }
private RegistryTypes _RegistryType;
public RegistryTypes RegistryType { get { return _RegistryType; } }
public string[] RegistryRootKeys
{
get
{
switch (_RegistryType)
{
case RegistryTypes.LocalMachine: { return new string[] { "HKEY_LOCAL_MACHINE" }; }
case RegistryTypes.CurrentUser: { return new string[] { "HKEY_CURRENT_USER" }; }
case RegistryTypes.Both: { return new string[] { "HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER" }; }
default: { return new string[] { "" }; }
}
}
}
public string[] RegistryPSDrives
{
get
{
switch (_RegistryType)
{
case RegistryTypes.LocalMachine: { return new string[] { "HKLM:" }; }
case RegistryTypes.CurrentUser: { return new string[] { "HKCU:" }; }
case RegistryTypes.Both: { return new string[] { "HKLM:", "HKCU:" }; }
default: { return new string[] { "" }; }
}
}
}
private string _RegistryPath;
public string RegistryPath { get { return _RegistryPath; } }
private PolicyValueInfo _ValueInfo;
public PolicyValueInfo ValueInfo { get { return _ValueInfo; } }
public PolicyInfo(AdmxFileInfo fileInfo, string name, string displayName, string explainText,
RegistryTypes registryType, string registryPath, PolicyValueInfo valueInfo)
{
_FileInfo = fileInfo;
_Name = name;
_DisplayName = displayName;
_ExplainText = explainText;
_RegistryType = registryType;
_RegistryPath = registryPath;
_ValueInfo = valueInfo;
}
}
public enum ValueTypes
{
Unknown = 0,
Delete,
Decimal,
LongDecimal,
String
}
// same values as Microsoft.Win32.RegistryValueKind
public enum RegistryValueKind
{
Unknown = 0,
String = 1,
DWord = 4,
MultiString = 7,
QWord = 11,
None = -1
}
public sealed class ValueDefinition
{
private ValueTypes _Type;
public ValueTypes Type { get { return _Type; } }
public RegistryValueKind RegistryType
{
get
{
switch (_Type)
{
case ValueTypes.Delete: { return RegistryValueKind.None; }
case ValueTypes.Decimal: { return RegistryValueKind.DWord; }
case ValueTypes.LongDecimal: { return RegistryValueKind.QWord; }
case ValueTypes.String: { return RegistryValueKind.String; }
default: { return RegistryValueKind.Unknown; }
}
}
}
private object _Value;
public object Value { get { return _Value; } }
public ValueDefinition(ValueTypes type, object value)
{
_Type = type;
_Value = value;
}
public override string ToString()
{
return String.Format("{0} : {1}", _Type, _Value);
}
}
public static class DefaultValueDefinition
{
// maybe, maybe...
public static readonly ValueDefinition Enabled = new ValueDefinition(ValueTypes.Decimal, (UInt32)1);
public static readonly ValueDefinition Disabled = new ValueDefinition(ValueTypes.Delete, null);
}
public sealed class ValueDefinitionList
{
private List<ListItem> _Items = new List<ListItem>();
public List<ListItem> Items { get { return _Items; } }
private string _DefaultRegistryPath;
public string DefaultRegistryPath { get { return _DefaultRegistryPath; } }
public ValueDefinitionList()
{
_DefaultRegistryPath = "";
}
public ValueDefinitionList(string defaultRegistryPath)
{
_DefaultRegistryPath = defaultRegistryPath;
}
}
public sealed class ListItem
{
private string _RegistryPath;
public string RegistryPath { get { return _RegistryPath; } }
private string _RegistryValueName;
public string RegistryValueName { get { return _RegistryValueName; } }
private ValueDefinition _Value;
public ValueDefinition Value { get { return _Value; } }
public ListItem(string registryPath, string registryValueName, ValueDefinition value)
{
_RegistryPath = registryPath;
_RegistryValueName = registryValueName;
_Value = value;
}
}
public enum ElementTypes
{
Unknown = 0,
Boolean,
Decimal,
LongDecimal,
Text,
MultiText,
Enum,
List
}
public interface IValueDefinitionElement
{
ElementTypes ElementType { get; }
string Id { get; }
string RegistryValueName { get; }
}
public abstract class ValueDefinitionElementBase : IValueDefinitionElement
{
public virtual ElementTypes ElementType { get { return ElementTypes.Unknown; } }
private string _Id;
public string Id { get { return _Id; } }
private string _RegistryPath;
public string RegistryPath { get { return _RegistryPath; } }
private string _RegistryValueName;
public string RegistryValueName { get { return _RegistryValueName; } }
public ValueDefinitionElementBase(string id, string registryPath, string registryValueName)
{
_Id = id;
_RegistryPath = registryPath;
_RegistryValueName = registryValueName;
}
}
public sealed class BooleanDefinitionElement : ValueDefinitionElementBase
{
public override ElementTypes ElementType { get { return ElementTypes.Boolean; } }
private ValueDefinition _TrueValue;
public ValueDefinition TrueValue { get { return _TrueValue; } }
private ValueDefinition _FalseValue;
public ValueDefinition FalseValue { get { return _FalseValue; } }
private ValueDefinitionList _TrueList;
public ValueDefinitionList TrueList { get { return _TrueList; } }
public bool HasTrueList { get { return (_TrueList != null && _TrueList.Items.Count > 0); } }
private ValueDefinitionList _FalseList;
public ValueDefinitionList FalseList { get { return _FalseList; } }
public bool HasFalseList { get { return (_FalseList != null && _FalseList.Items.Count > 0); } }
[System.Management.Automation.HiddenAttribute]
public void set_Properties(ValueDefinition trueValue, ValueDefinition falseValue, ValueDefinitionList trueList, ValueDefinitionList falseList)
{
_TrueValue = trueValue;
_FalseValue = falseValue;
_TrueList = trueList;
_FalseList = falseList;
}
public BooleanDefinitionElement(string id, string registryPath, string registryValueName) : base(id, registryPath, registryValueName)
{
}
}
public sealed class DecimalDefinitionElement : ValueDefinitionElementBase
{
public override ElementTypes ElementType { get { return ElementTypes.Decimal; } }
private bool _Required;
public bool Required { get { return _Required; } }
private Decimal _MinValue;
public Decimal MinValue { get { return _MinValue; } }
private Decimal _MaxValue = 9999;
public Decimal MaxValue { get { return _MaxValue; } }
private bool _StoreAsText;
public bool StoreAsText { get { return _StoreAsText; } }
private bool _Soft;
public bool Soft { get { return _Soft; } }
[System.Management.Automation.HiddenAttribute]
public void set_Properties(bool required, Decimal minValue, Decimal maxValue, bool storeAsText, bool soft)
{
_Required = required;
_MinValue = minValue;
_MaxValue = maxValue;
_StoreAsText = storeAsText;
_Soft = soft;
}
public DecimalDefinitionElement(string id, string registryPath, string registryValueName) : base(id, registryPath, registryValueName)
{
}
}
public sealed class LongDecimalDefinitionElement : ValueDefinitionElementBase
{
public override ElementTypes ElementType { get { return ElementTypes.LongDecimal; } }
private bool _Required;
public bool Required { get { return _Required; } }
private Decimal _MinValue;
public Decimal MinValue { get { return _MinValue; } }
private Decimal _MaxValue = 9999;
public Decimal MaxValue { get { return _MaxValue; } }
private bool _StoreAsText;
public bool StoreAsText { get { return _StoreAsText; } }
private bool _Soft;
public bool Soft { get { return _Soft; } }
[System.Management.Automation.HiddenAttribute]
public void set_Properties(bool required, Decimal minValue, Decimal maxValue, bool storeAsText, bool soft)
{
_Required = required;
_MinValue = minValue;
_MaxValue = maxValue;
_StoreAsText = storeAsText;
_Soft = soft;
}
public LongDecimalDefinitionElement(string id, string registryPath, string registryValueName) : base(id, registryPath, registryValueName)
{
}
}
public sealed class TextDefinitionElement : ValueDefinitionElementBase
{
public override ElementTypes ElementType { get { return ElementTypes.Text; } }
private bool _Required;
public bool Required { get { return _Required; } }
private Decimal _MaxLength = 1023;
public Decimal MaxLength { get { return _MaxLength; } }
private bool _Expandable;
public bool Expandable { get { return _Expandable; } }
private bool _Soft;
public bool Soft { get { return _Soft; } }
[System.Management.Automation.HiddenAttribute]
public void set_Properties(bool required, Decimal maxLength, bool expandable, bool soft)
{
_Required = required;
_MaxLength = maxLength;
_Expandable = expandable;
_Soft = soft;
}
public TextDefinitionElement(string id, string registryPath, string registryValueName) : base(id, registryPath, registryValueName)
{
}
}
public sealed class MultiTextDefinitionElement : ValueDefinitionElementBase
{
public override ElementTypes ElementType { get { return ElementTypes.MultiText; } }
private bool _Required;
public bool Required { get { return _Required; } }
private Decimal _MaxLength = 1023;
public Decimal MaxLength { get { return _MaxLength; } }
private Decimal _MaxStrings;
public Decimal MaxStrings { get { return _MaxStrings; } }
private bool _Soft;
public bool Soft { get { return _Soft; } }
[System.Management.Automation.HiddenAttribute]
public void set_Properties(bool required, Decimal maxLength, Decimal maxStrings, bool soft)
{
_Required = required;
_MaxLength = maxLength;
_MaxStrings = maxStrings;
_Soft = soft;
}
public MultiTextDefinitionElement(string id, string registryPath, string registryValueName) : base(id, registryPath, registryValueName)
{
}
}
public sealed class EnumValue
{
private ValueDefinition _Value;
public ValueDefinition Value { get { return _Value; } }
private ValueDefinitionList _ValueList;
public ValueDefinitionList ValueList { get { return _ValueList; } internal set { _ValueList = value; } }
public bool HasValueList { get { return (_ValueList != null && _ValueList.Items.Count > 0); } }
public EnumValue(ValueDefinition value)
{
_Value = value;
}
public override string ToString()
{
return _Value.ToString();
}
}
public sealed class EnumDefinitionElement : ValueDefinitionElementBase
{
public override ElementTypes ElementType { get { return ElementTypes.Enum; } }
private bool _Required;
public bool Required { get { return _Required; } }
[System.Management.Automation.HiddenAttribute]
public void set_Properties(bool required)
{
_Required = required;
}
private List<KeyValuePair<string, EnumValue>> _Enums = new List<KeyValuePair<string, EnumValue>>();
public List<KeyValuePair<string, EnumValue>> Enums { get { return _Enums; } }
[System.Management.Automation.HiddenAttribute]
public void add_EnumsItem(string displayName, ValueDefinition value, ValueDefinitionList valueList)
{
EnumValue enumvalue = new EnumValue(value);
if (valueList != null)
{
enumvalue.ValueList = valueList;
}
_Enums.Add(new KeyValuePair<string, EnumValue>(displayName, enumvalue));
}
public EnumDefinitionElement(string id, string registryPath, string registryValueName) : base(id, registryPath, registryValueName)
{
}
}
public sealed class ListDefinitionElement : ValueDefinitionElementBase
{
public override ElementTypes ElementType { get { return ElementTypes.List; } }
private string _ValuePrefix;
public string ValuePrefix { get { return _ValuePrefix; } }
private bool _Additive;
public bool Additive { get { return _Additive; } }
private bool _Expandable;
public bool Expandable { get { return _Expandable; } }
private bool _ExplicitValue;
public bool ExplicitValue { get { return _ExplicitValue; } }
private string _ClientExtension;
public string ClientExtension { get { return _ClientExtension; } }
[System.Management.Automation.HiddenAttribute]
public void set_Properties(string valuePrefix, bool additive, bool expandable, bool explicitValue, string clientExtension)
{
_ValuePrefix = valuePrefix;
_Additive = additive;
_Expandable = expandable;
_ExplicitValue = explicitValue;
_ClientExtension = clientExtension;
}
public ListDefinitionElement(string id, string registryPath, string registryValueName) : base(id, registryPath, registryValueName)
{
}
}
public sealed class ValueDefinitionElements
{
private List<IValueDefinitionElement> _Items = new List<IValueDefinitionElement>();
public List<IValueDefinitionElement> Items { get { return _Items; } }
}
public sealed class PolicyValueInfo
{
// Registry value information.
private string _RegistryValueName;
public string RegistryValueName { get { return _RegistryValueName; } }
// single Enabled/Disabled value definitions.
private ValueDefinition _EnabledValue;
public ValueDefinition EnabledValue { get { return _EnabledValue; } }
private ValueDefinition _DisabledValue;
public ValueDefinition DisabledValue { get { return _DisabledValue; } }
[System.Management.Automation.HiddenAttribute]
public void set_RegistryValue(string valueName, ValueDefinition enabledValue, ValueDefinition disabledValue)
{
_RegistryValueName = valueName;
_EnabledValue = enabledValue;
_DisabledValue = disabledValue;
}
// list value definitions.
private ValueDefinitionList _EnabledList;
public ValueDefinitionList EnabledList { get { return _EnabledList; } }
public bool HasEnabledList { get { return (_EnabledList != null && _EnabledList.Items.Count > 0); } }
private ValueDefinitionList _DisabledList;
public ValueDefinitionList DisabledList { get { return _DisabledList; } }
public bool HasDisabledList { get { return (_DisabledList != null && _DisabledList.Items.Count > 0); } }
[System.Management.Automation.HiddenAttribute]
public void set_EnabledListValue(ValueDefinitionList list)
{
_EnabledList = list;
}
[System.Management.Automation.HiddenAttribute]
public void set_DisabledListValue(ValueDefinitionList list)
{
_DisabledList = list;
}
// element value definition.
private ValueDefinitionElements _Elements;
public ValueDefinitionElements Elements { get { return _Elements; } }
public bool HasElements { get { return (_Elements != null && _Elements.Items.Count > 0); } }
[System.Management.Automation.HiddenAttribute]
public void set_ElementsValue(ValueDefinitionElements elements)
{
_Elements = elements;
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using NUnit.Framework;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki.Tests.PropertyTests {
[TestFixture]
public class PropertyTests {
[Test]
public void SaveGetPageProperty() {
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
string content = Utils.GetSmallRandomText();
//NOTE: PUT: resource/{properties}/{key} is allowing property creation. Creating properties this way is undocumented and not recommended but was added for import/export
//Test property creation via PUT
//msg = p.At("pages", id, "properties", "foo").PutAsync(DreamMessage.Ok(MimeType.TEXT, content)).Wait();
//Assert.AreEqual(DreamStatus.Conflict, msg.Status);
msg = p.At("pages", id, "properties").WithHeader("Slug", XUri.Encode("foo")).PostAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, content)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "post properties returned non 200 status: " + msg.ToString());
//TODO: validate response XML for 200's
msg = p.At("pages", id, "properties", "foo", "info").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "get property returned non 200 status: " + msg.ToString());
Assert.AreEqual(content, msg.ToDocument()["/property[@name= 'foo']/contents"].AsText, "Contents don't match!");
XUri contentsUri = msg.ToDocument()["/property[@name = 'foo']/contents/@href"].AsUri;
Assert.IsTrue(contentsUri != null, "Couldn't find content href");
Plug p2 = Plug.New(contentsUri).WithTimeout(p.Timeout).WithHeaders(p.Headers).WithCredentials(p.Credentials);
msg = p2.GetAsync().Wait();
Assert.IsTrue(msg.Status == DreamStatus.Ok, "get property contents by uri didnt return status 200: " + msg.ToString());
Assert.IsTrue(msg.ContentType.Match(MimeType.TEXT), "get property content type didnt match: " + msg.ToString());
Assert.IsTrue(msg.AsText() == content, "get property content didnt match: " + msg.ToString());
}
[Test]
public void FileUploadAndPropertyUpdate() {
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
string filepath = FileUtils.CreateRamdomFile(null);
string fileName = System.IO.Path.GetFileName(filepath);
fileName = "properties";
//Upload file via PUT: pages/{id}/files/{filename}
msg = p.At("pages", id, "files", "=" + XUri.DoubleEncode(fileName)).PutAsync(DreamMessage.FromFile(filepath)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Initial upload failed");
string fileid = msg.ToDocument()["@id"].AsText;
//Upload another rev of file via PUT:files/{fileid}/{filename}
msg = p.At("files", fileid, "=" + XUri.DoubleEncode(fileName)).PutAsync(DreamMessage.FromFile(filepath)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "upload via PUT:files/{fileid}/{filename} failed");
Assert.AreEqual("file", msg.ToDocument().Name, "File upload did not return a file xml");
//Create a property 'foo' on the file
msg = p.At("files", fileid, "properties").WithHeader("slug", "foo").PostAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, "foo content")).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Property foo set via POST:files/{id}/properties failed");
Assert.AreEqual("property", msg.ToDocument().Name, "property upload did not return property xml");
string propEtag = msg.ToDocument()["@etag"].AsText;
//Update property 'foo' using the batch feature
string newPropertyContent = "Some new content";
XDoc propDoc = new XDoc("properties")
.Start("property").Attr("name", "foo").Attr("etag", propEtag)
.Start("contents").Attr("type", MimeType.TEXT_UTF8.ToString()).Value(newPropertyContent).End()
.End();
msg = p.At("files", fileid, "properties").PutAsync(propDoc).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "batch property call failed");
Assert.AreEqual("properties", msg.ToDocument().Name, "batch property upload did not return properties xml");
}
[Test]
[Ignore]
public void RevisionPageProperty() {
//Create n revisions.
//Validate number of revisions created and content at head revisions
//Validate content of each revision
//TODO: description tests
int REVS = 10;
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
for (int i = 1; i <= REVS; i++) {
XDoc content = new XDoc("revtest");
content.Start("revision").Value(i).End();
string etag = string.Empty;
msg = p.At("pages", id, "properties", "foo").WithHeader(DreamHeaders.ETAG, etag).PutAsync(DreamMessage.Ok(content)).Wait();
Assert.IsTrue(msg.Status == DreamStatus.Ok, "put property returned non 200 status: " + msg.ToString());
etag = msg.ToDocument()["/property/@etag"].AsText;
msg = p.At("pages", id, "properties", "foo", "info").GetAsync().Wait();
Assert.IsTrue(msg.Status == DreamStatus.Ok, "get property returned non 200 status: " + msg.ToString());
string c = XDocFactory.From(msg.ToDocument()["/property[@name= 'foo']/contents"].AsText, MimeType.New(msg.ToDocument()["/property[@name='foo']/contents/@type"].AsText)).ToPrettyString();
Assert.IsTrue(msg.Status == DreamStatus.Ok, "get property returned non 200 status: " + msg.ToString());
Assert.AreEqual(content.ToPrettyString(), c, "Contents don't match!");
Assert.AreEqual((msg.ToDocument()["/property[@name= 'foo']/revisions/@count"].AsInt ?? 0), i);
}
msg = p.At("pages", id, "properties", "foo", "revisions").GetAsync().Wait();
Assert.IsTrue(msg.Status == DreamStatus.Ok, "get property revisions returned non 200 status: " + msg.ToString());
Assert.AreEqual((msg.ToDocument()["/properties/@count"].AsInt ?? 0), REVS);
for (int i = 1; i <= REVS; i++) {
XDoc content = new XDoc("revtest");
content.Start("revision").Value(i).End();
msg = p.At("pages", id, "properties", "foo", "info").With("revision", i).GetAsync().Wait();
Assert.IsTrue(msg.Status == DreamStatus.Ok, "get property returned non 200 status: " + msg.ToString());
string c = XDocFactory.From(msg.ToDocument()["/property[@name= 'foo']/contents"].AsText, MimeType.New(msg.ToDocument()["/property[@name='foo']/contents/@type"].AsText)).ToPrettyString();
Assert.IsTrue(msg.Status == DreamStatus.Ok, "get property returned non 200 status: " + msg.ToString());
Assert.AreEqual(content.ToPrettyString(), c, "Contents don't match!");
Assert.AreEqual((msg.ToDocument()["/property[@name= 'foo']/revisions/@count"].AsInt ?? 0), REVS);
}
}
[Test]
public void DeleteAndOverwritePageProperty() {
//Set a property foo with content c1
//Delete the property foo
//Validate that foo doesn't exist
//Set property to content c2
//Validate property content of c2
string C1 = "C1";
string C2 = "C2";
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
XDoc content = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
//Set foo with c1
content = new XDoc("deltest").Start("somevalue").Value(C1).End();
msg = p.At("pages", id, "properties").WithHeader("Slug", XUri.Encode("foo")).PostAsync(DreamMessage.Ok(content)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "put property returned non 200 status: " + msg.ToString());
msg = p.At("pages", id, "properties", "foo", "info").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "get property returned non 200 status: " + msg.ToString());
msg = p.At("pages", id, "properties", "foo").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "get property contents returned non 200 status: " + msg.ToString());
Assert.AreEqual(content.ToPrettyString(), msg.ToDocument().ToPrettyString(), "Contents don't match!");
//Delete foo
msg = p.At("pages", id, "properties", "foo").DeleteAsync(DreamMessage.Ok()).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "delete property returned non 200 status: " + msg.ToString());
//Validate that foo doesn't exist
msg = p.At("pages", id, "properties", "foo", "info").GetAsync(DreamMessage.Ok()).Wait();
Assert.AreEqual(DreamStatus.NotFound, msg.Status, "get deleted property returned non 404 status: " + msg.ToString());
//Set property to content c2
content = new XDoc("deltest").Start("somevalue").Value(C2).End();
msg = p.At("pages", id, "properties").WithHeader("Slug", XUri.Encode("foo")).PostAsync(DreamMessage.Ok(content)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "put property returned non 200 status: " + msg.ToString());
msg = p.At("pages", id, "properties", "foo", "info").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "get property returned non 200 status: " + msg.ToString());
//Validate property content of c2
msg = p.At("pages", id, "properties", "foo").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "get property contents returned non 200 status: " + msg.ToString());
Assert.AreEqual(content.ToPrettyString(), msg.ToDocument().ToPrettyString(), "Contents don't match!");
}
[Test]
public void MultiplePropertiesInPage() {
//Save multiple properties in a page
//Retrieve them
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
int NUMPROPS = 5;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
for(int i = 1; i <= NUMPROPS; i++) {
string propname = string.Format("testprop_{0}", i);
XDoc content = new XDoc("proptest");
content.Start("name").Value(propname).End();
msg = p.At("pages", id, "properties").WithHeader("Slug", XUri.Encode(propname)).PostAsync(DreamMessage.Ok(content)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "put property returned non 200 status: " + msg.ToString());
msg = p.At("pages", id, "properties", propname, "info").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "get property returned non 200 status: " + msg.ToString());
Assert.AreEqual(MimeType.XML.ToString(), MimeType.New(msg.ToDocument()["/property[@name='" + propname + "']/contents/@type"].AsText).ToString(), "Content types dont match");
msg = p.At("pages", id, "properties", propname).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "get property content returned non 200 status: " + msg.ToString());
Assert.AreEqual(content.ToPrettyString(), msg.ToDocument().ToPrettyString(), "Contents don't match!");
//revisions not yet supported.
//Assert.AreEqual((msg.ToDocument()["/property[@name= '" + propname + "']/revisions/@count"].AsInt ?? 0), 1);
}
msg = p.At("pages", id, "properties").GetAsync(DreamMessage.Ok()).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "get properties returned non 200 status: " + msg.ToString());
Assert.AreEqual(msg.ToDocument()["/properties/@count"].AsInt, NUMPROPS, "Wrong property count!");
}
//[Test]
public void FileProperties() {
//TODO!
}
//[Test]
public void UserProperties() {
//TODO!
}
//[Test]
public void PropPermissions() {
//TODO!
}
/*TODO: batch tests:
* duplicate name in put
* invalid mimetype
* Etags
*/
[Test]
public void PropPutBatchPositive() {
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
string name;
const int NUMPROPS = 5;
XDoc doc = new XDoc("properties");
string nameTemplate = "prop_{0}";
string contentTemplate = "Some value {0}";
string descTemplate = "Soem description {0}";
string[] etags = new string[NUMPROPS];
//Create 5 new properties
for(int i = 0; i < NUMPROPS; i++) {
doc.Start("property").Attr("name", string.Format(nameTemplate, i))
.Start("contents").Attr("type", MimeType.TEXT.ToString())
.Value(string.Format(contentTemplate, i))
.End()
.Elem("description", string.Format(descTemplate, i))
.End();
}
msg = p.At("pages", id, "properties").PutAsync(DreamMessage.Ok(doc)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "put batch property returned non 200 status: " + msg.ToString());
Assert.AreEqual(msg.ToDocument()["/properties/@count"].AsInt, NUMPROPS, "count is wrong");
for(int i = 0; i < NUMPROPS; i++) {
name = string.Format(nameTemplate, i);
string etag = msg.ToDocument()["/properties/property[@name = '" + name + "']/@etag"].AsText;
Assert.IsTrue(!string.IsNullOrEmpty(etag), string.Format("Property {0} etag empty", name));
etags[i] = etag;
Assert.AreEqual(msg.ToDocument()["/properties/property[@name = '" + name + "']/status/@code"].AsInt ?? 0, 200, string.Format("Property {0} status", name));
Assert.AreEqual(msg.ToDocument()["/properties/property[@name = '" + name + "']/contents"].AsText, string.Format(contentTemplate, i), string.Format("Property {0} content", name));
Assert.AreEqual(msg.ToDocument()["/properties/property[@name = '" + name + "']/contents/@type"].AsText, MimeType.TEXT.ToString(), string.Format("Property {0} content type", name));
Assert.AreEqual(msg.ToDocument()["/properties/property[@name = '" + name + "']/change-description"].AsText, string.Format(descTemplate, i), string.Format("Property {0} description", name));
}
//prop 0 is getting deleted (no content)
//prop 1 is getting updated
//prop 2 is getting updated with same content
string PROP1CONTENT = "some new content";
doc = new XDoc("properties")
.Start("property").Attr("name", string.Format(nameTemplate, 0)).Attr("etag", etags[0]).End()
.Start("property").Attr("name", string.Format(nameTemplate, 1)).Attr("etag", etags[1])
.Start("contents").Attr("type", MimeType.TEXT.ToString()).Value(PROP1CONTENT).End()
.End()
.Start("property").Attr("name", string.Format(nameTemplate, 2)).Attr("etag", etags[2])
.Start("contents").Attr("type", MimeType.TEXT.ToString()).Value(string.Format(contentTemplate, 2)).End()
.End();
msg = p.At("pages", id, "properties").PutAsync(DreamMessage.Ok(doc)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "put batch property request #2 returned non 200 status: " + msg.ToString());
//prop 0: deleted
name = string.Format(nameTemplate, 0);
Assert.AreEqual(msg.ToDocument()["/properties/property[@name = '" + name + "']/status/@code"].AsInt ?? 0, 200, string.Format("Property {0} status after delete", name));
Assert.IsTrue((msg.ToDocument()["/properties/property[@name = '" + name + "']/user.deleted/@id"].AsInt ?? 0) > 0, string.Format("Property {0} delete user", name));
Assert.IsTrue(msg.ToDocument()["/properties/property[@name = '" + name + "']/date.deleted"].AsDate != null, string.Format("Property {0} delete date", name));
//prop 1: updated
name = string.Format(nameTemplate, 1);
Assert.AreEqual(msg.ToDocument()["/properties/property[@name = '" + name + "']/status/@code"].AsInt ?? 0, 200, string.Format("Property {0} status after update", name));
Assert.AreEqual(msg.ToDocument()["/properties/property[@name = '" + name + "']/contents"].AsText, PROP1CONTENT, string.Format("Property {0} content after update", name));
//TODO test for prop2 when content isn't updated.
}
[Test]
public void PropGetContentPreviewsPositive() {
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
int NUMPROPS = 5;
XDoc doc = new XDoc("properties");
string contentLong = Utils.GetRandomTextByAlphabet(5000);
string contentShort = "Some content";
string descTemplate = "Soem description {0}";
//Short content
doc.Start("property").Attr("name", "prop_short")
.Start("contents").Attr("type", MimeType.TEXT.ToString())
.Value(contentShort)
.End()
.End();
//Long content
doc.Start("property").Attr("name", "prop_long")
.Start("contents").Attr("type", MimeType.TEXT.ToString())
.Value(contentLong)
.End()
.End();
msg = p.At("pages", id, "properties").PutAsync(DreamMessage.Ok(doc)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "put batch property returned non 200 status: " + msg.ToString());
msg = p.At("pages", id, "properties").GetAsync(DreamMessage.Ok()).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "get properties returned non 200 status: " + msg.ToString());
}
[Ignore("PUT: resource/{properties} is allowing property creation. Creating properties this way is undocumented and not recommended but was added for import/export.")]
[Test]
public void NewPropertyWithEtagNegative() {
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
XDoc doc = new XDoc("properties");
string contentShort = "Some content";
doc.Start("property").Attr("name", "prop_short").Attr("etag", "some-unexpected-etag")
.Start("contents").Attr("type", MimeType.TEXT.ToString())
.Value(contentShort)
.End()
.End();
msg = p.At("pages", id, "properties").PutAsync(DreamMessage.Ok(doc)).Wait();
Assert.AreEqual(DreamStatus.MultiStatus, msg.Status, "put batch property returned 200 status but expected MultiStatus");
Assert.AreEqual("409", msg.ToDocument()["/properties/property[@name='prop_short']/status/@code"].AsText);
msg = p.At("pages", id, "properties").WithHeader("Slug", XUri.Encode("foo")).WithHeader(DreamHeaders.ETAG, "some-etag").PostAsync(DreamMessage.Ok(MimeType.TEXT, "blah")).Wait();
Assert.AreEqual(DreamStatus.Conflict, msg.Status, "put batch property returned 200 status but expected : " + msg.ToString());
}
[Test]
public void GetPageProperties()
{
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
msg = p.At("pages", id, "properties").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msg = p.At("pages", "=" + XUri.DoubleEncode(path), "properties").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
PageUtils.DeletePageByID(p, id, true);
}
[Test]
public void PutPageProperties()
{
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
string propertyContent = Utils.GetSmallRandomText();
string propertyName = Utils.GenerateUniqueName();
msg = p.At("pages", id, "properties").WithHeader("Slug", XUri.Encode(propertyName)).PostAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, propertyContent)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreEqual(msg.ToDocument()["/property/contents"].AsText, propertyContent, "Contents don't match!");
msg = p.At("pages", id, "properties", propertyName).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreEqual(propertyContent, msg.AsText(), "Contents don't match!");
PageUtils.DeletePageByID(p, id, true);
}
[Test]
public void GetFileProperties()
{
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
string fileid = null;
msg = FileUtils.UploadRandomFile(p, id, out fileid);
msg = p.At("files", fileid, "properties").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
PageUtils.DeletePageByID(p, id, true);
}
[Test]
public void PutFileProperties()
{
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
string propertyContent = Utils.GetSmallRandomText();
string propertyName = Utils.GenerateUniqueName();
string fileid = null;
msg = FileUtils.UploadRandomFile(p, id, out fileid);
msg = p.At("files", fileid, "properties").WithHeader("Slug", XUri.Encode(propertyName)).PostAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, propertyContent)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreEqual(msg.ToDocument()["/property/contents"].AsText, propertyContent, "Contents don't match!");
msg = p.At("files", fileid, "properties", propertyName).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Non 200 status on get:property content: "+msg.ToString());
Assert.AreEqual(propertyContent, msg.AsText(), "Contents don't match!");
PageUtils.DeletePageByID(p, id, true);
}
[Test]
public void GetUserProperties()
{
Plug p = Utils.BuildPlugForAdmin();
string id = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id);
msg = p.At("users", id, "properties").GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
}
[Test]
public void PostUserProperties()
{
Plug p = Utils.BuildPlugForAdmin();
string id = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id);
string propertyContent = Utils.GetSmallRandomText();
string propertyName = Utils.GenerateUniqueName();
msg = p.At("users", id, "properties").WithHeader("Slug", XUri.Encode(propertyName)).PostAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, propertyContent)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreEqual(msg.ToDocument()["/property/contents"].AsText, propertyContent, "Contents don't match!");
msg = p.At("users", id, "properties", propertyName).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreEqual(propertyContent, msg.AsText(), "Contents don't match!");
}
[Test]
public void PostPutDeleteSiteProperties() {
Plug p = Utils.BuildPlugForAdmin();
string propertyContent = Utils.GetSmallRandomText();
string propertyName = Utils.GenerateUniqueName();
DreamMessage msg = null;
try {
msg = p.At("site", "properties").WithHeader("Slug", XUri.Encode(propertyName)).PostAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, propertyContent)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "POST property got non 200");
Assert.AreEqual(msg.ToDocument()["/property/contents"].AsText, propertyContent, "Contents don't match!");
msg = p.At("site", "properties", propertyName).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "GET property returned non 200");
Assert.AreEqual(propertyContent, msg.AsText(), "Contents don't match!");
propertyContent = Utils.GetSmallRandomText();
msg = p.At("site", "properties", propertyName).WithHeader(DreamHeaders.ETAG, msg.Headers.ETag).PutAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, propertyContent)).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "PUT property returned non 200");
msg = p.At("site", "properties", propertyName).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "GET property returned non 200");
Assert.AreEqual(propertyContent, msg.AsText(), "Contents don't match on second rev!");
} finally {
msg = p.At("site", "properties", propertyName).DeleteAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Delete status non 200");
}
msg = p.At("site", "properties", propertyName).GetAsync().Wait();
Assert.AreEqual(DreamStatus.NotFound, msg.Status, "Deleted property get status non 404");
}
}
}
| |
#pragma warning disable SA1633 // File should have header - This is an imported file,
// original header with license shall remain the same
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* The following part was imported from https://gitlab.freedesktop.org/uchardet/uchardet
* The implementation of this feature was originally done on https://gitlab.freedesktop.org/uchardet/uchardet/blob/master/src/LangModels/LangThaiModel.cpp
* and adjusted to language specific support.
*/
namespace UtfUnknown.Core.Models.SingleByte.Thai;
internal class Iso_8859_11_ThaiModel : ThaiModel
{
// Generated by BuildLangModel.py
// On: 2015-12-04 03:05:06.182099
//
//aracter Mapping Table:
// ILL: illegal character.
// CTR: control character specific to the charset.
// RET: carriage/return.
// SYM: symbol (punctuation) that does not belong to word.
// NUM: 0 - 9.
//
// Other characters are ordered by probabilities
// (0 is the most common character in the language).
//
// Orders are generic to a language.So the codepoint with order X in
// CHARSET1 maps to the same character as the codepoint with the same
// order X in CHARSET2 for the same language.
// As such, it is possible to get missing order.For instance the
// ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1
// even though they are both used for French.Same for the euro sign.
private static readonly byte[] CHAR_TO_ORDER_MAP =
{
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
RET,
CTR,
CTR,
RET,
CTR,
CTR, /* 0X */
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR, /* 1X */
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM, /* 2X */
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM, /* 3X */
SYM,
66,
70,
67,
80,
78,
87,
85,
73,
79,
93,
88,
84,
68,
77,
81, /* 4X */
75,
101,
74,
61,
71,
86,
96,
90,
103,
100,
99,
SYM,
SYM,
SYM,
SYM,
SYM, /* 5X */
SYM,
35,
64,
48,
52,
32,
60,
65,
54,
36,
97,
76,
46,
56,
41,
40, /* 6X */
59,
104,
43,
45,
44,
55,
72,
82,
94,
57,
92,
SYM,
SYM,
SYM,
SYM,
CTR, /* 7X */
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR, /* 8X */
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR,
CTR, /* 9X */
SYM,
3,
23,
112,
15,
113,
89,
5,
21,
63,
26,
31,
102,
42,
69,
58, /* AX */
49,
91,
83,
34,
9,
17,
30,
12,
39,
1,
16,
19,
33,
62,
22,
47, /* BX */
38,
7,
10,
2,
50,
11,
114,
8,
28,
37,
13,
18,
98,
4,
53,
95, /* CX */
14,
SYM,
0,
29,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
ILL,
ILL,
ILL,
ILL,
SYM, /* DX */
6,
20,
27,
24,
25,
115,
51,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
SYM,
116, /* EX */
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
NUM,
117,
118,
ILL,
ILL,
ILL,
ILL /* FX */
};
/*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */
public Iso_8859_11_ThaiModel()
: base(
CHAR_TO_ORDER_MAP,
CodepageName.ISO_8859_11) { }
}
| |
using System;
using System.Net;
using System.Threading;
using Orleans.Messaging;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Messaging
{
internal class MessageCenter : ISiloMessageCenter, IDisposable
{
private Gateway Gateway { get; set; }
private IncomingMessageAcceptor ima;
private static readonly Logger log = LogManager.GetLogger("Orleans.Messaging.MessageCenter");
private Action<Message> rerouteHandler;
internal Func<Message, bool> ShouldDrop;
// ReSharper disable NotAccessedField.Local
private IntValueStatistic sendQueueLengthCounter;
private IntValueStatistic receiveQueueLengthCounter;
// ReSharper restore NotAccessedField.Local
internal IOutboundMessageQueue OutboundQueue { get; set; }
internal IInboundMessageQueue InboundQueue { get; set; }
internal SocketManager SocketManager;
private readonly MessageFactory messageFactory;
internal bool IsBlockingApplicationMessages { get; private set; }
internal ISiloPerformanceMetrics Metrics { get; private set; }
public bool IsProxying { get { return Gateway != null; } }
public bool TryDeliverToProxy(Message msg)
{
return msg.TargetGrain.IsClient && Gateway != null && Gateway.TryDeliverToProxy(msg);
}
// This is determined by the IMA but needed by the OMS, and so is kept here in the message center itself.
public SiloAddress MyAddress { get; private set; }
public IMessagingConfiguration MessagingConfiguration { get; private set; }
public MessageCenter(
SiloInitializationParameters silo,
NodeConfiguration nodeConfig,
IMessagingConfiguration config,
ISiloPerformanceMetrics metrics,
MessageFactory messageFactory)
{
this.messageFactory = messageFactory;
this.Initialize(silo.SiloAddress.Endpoint, nodeConfig.Generation, config, metrics);
if (nodeConfig.IsGatewayNode)
{
this.InstallGateway(nodeConfig.ProxyGatewayEndpoint);
}
}
private void Initialize(IPEndPoint here, int generation, IMessagingConfiguration config, ISiloPerformanceMetrics metrics = null)
{
if(log.IsVerbose3) log.Verbose3("Starting initialization.");
SocketManager = new SocketManager(config);
ima = new IncomingMessageAcceptor(this, here, SocketDirection.SiloToSilo, this.messageFactory);
MyAddress = SiloAddress.New((IPEndPoint)ima.AcceptingSocket.LocalEndPoint, generation);
MessagingConfiguration = config;
InboundQueue = new InboundMessageQueue();
OutboundQueue = new OutboundMessageQueue(this, config);
Gateway = null;
Metrics = metrics;
sendQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_SEND_QUEUE_LENGTH, () => SendQueueLength);
receiveQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_RECEIVE_QUEUE_LENGTH, () => ReceiveQueueLength);
if (log.IsVerbose3) log.Verbose3("Completed initialization.");
}
public void InstallGateway(IPEndPoint gatewayAddress)
{
Gateway = new Gateway(this, gatewayAddress, this.messageFactory);
}
public void Start()
{
IsBlockingApplicationMessages = false;
ima.Start();
OutboundQueue.Start();
}
public void StartGateway(ClientObserverRegistrar clientRegistrar)
{
if (Gateway != null)
Gateway.Start(clientRegistrar);
}
public void PrepareToStop()
{
}
public void Stop()
{
IsBlockingApplicationMessages = true;
try
{
ima.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100108, "Stop failed.", exc);
}
StopAcceptingClientMessages();
try
{
OutboundQueue.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100110, "Stop failed.", exc);
}
try
{
SocketManager.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100111, "Stop failed.", exc);
}
}
public void StopAcceptingClientMessages()
{
if (log.IsVerbose) log.Verbose("StopClientMessages");
if (Gateway == null) return;
try
{
Gateway.Stop();
}
catch (Exception exc) { log.Error(ErrorCode.Runtime_Error_100109, "Stop failed.", exc); }
Gateway = null;
}
public Action<Message> RerouteHandler
{
set
{
if (rerouteHandler != null)
throw new InvalidOperationException("MessageCenter RerouteHandler already set");
rerouteHandler = value;
}
}
public void RerouteMessage(Message message)
{
if (rerouteHandler != null)
rerouteHandler(message);
else
SendMessage(message);
}
public Action<Message> SniffIncomingMessage
{
set
{
ima.SniffIncomingMessage = value;
}
}
public Func<SiloAddress, bool> SiloDeadOracle { get; set; }
public void SendMessage(Message msg)
{
// Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here.
if (IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && (msg.Result != Message.ResponseTypes.Rejection)
&& !Constants.SystemMembershipTableId.Equals(msg.TargetGrain))
{
// Drop the message on the floor if it's an application message that isn't a rejection
}
else
{
if (msg.SendingSilo == null)
msg.SendingSilo = MyAddress;
OutboundQueue.SendMessage(msg);
}
}
internal void SendRejection(Message msg, Message.RejectionTypes rejectionType, string reason)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
if (string.IsNullOrEmpty(reason)) reason = string.Format("Rejection from silo {0} - Unknown reason.", MyAddress);
Message error = this.messageFactory.CreateRejectionResponse(msg, rejectionType, reason);
// rejection msgs are always originated in the local silo, they are never remote.
InboundQueue.PostMessage(error);
}
public Message WaitMessage(Message.Categories type, CancellationToken ct)
{
return InboundQueue.WaitMessage(type);
}
public void Dispose()
{
if (ima != null)
{
ima.Dispose();
ima = null;
}
OutboundQueue.Dispose();
GC.SuppressFinalize(this);
}
public int SendQueueLength { get { return OutboundQueue.Count; } }
public int ReceiveQueueLength { get { return InboundQueue.Count; } }
/// <summary>
/// Indicates that application messages should be blocked from being sent or received.
/// This method is used by the "fast stop" process.
/// <para>
/// Specifically, all outbound application messages are dropped, except for rejections and messages to the membership table grain.
/// Inbound application requests are rejected, and other inbound application messages are dropped.
/// </para>
/// </summary>
public void BlockApplicationMessages()
{
if(log.IsVerbose) log.Verbose("BlockApplicationMessages");
IsBlockingApplicationMessages = true;
}
}
}
| |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace Avro
{
/// <summary>
/// Base class for all schema types
/// </summary>
public abstract class Schema
{
/// <summary>
/// Enum for schema types
/// </summary>
public enum Type
{
/// <summary>
/// No value.
/// </summary>
Null,
/// <summary>
/// A binary value.
/// </summary>
Boolean,
/// <summary>
/// A 32-bit signed integer.
/// </summary>
Int,
/// <summary>
/// A 64-bit signed integer.
/// </summary>
Long,
/// <summary>
/// A single precision (32-bit) IEEE 754 floating-point number.
/// </summary>
Float,
/// <summary>
/// A double precision (64-bit) IEEE 754 floating-point number.
/// </summary>
Double,
/// <summary>
/// A sequence of 8-bit unsigned bytes.
/// </summary>
Bytes,
/// <summary>
/// An unicode character sequence.
/// </summary>
String,
/// <summary>
/// A logical collection of fields.
/// </summary>
Record,
/// <summary>
/// An enumeration.
/// </summary>
Enumeration,
/// <summary>
/// An array of values.
/// </summary>
Array,
/// <summary>
/// A map of values with string keys.
/// </summary>
Map,
/// <summary>
/// A union.
/// </summary>
Union,
/// <summary>
/// A fixed-length byte string.
/// </summary>
Fixed,
/// <summary>
/// A protocol error.
/// </summary>
Error,
/// <summary>
/// A logical type.
/// </summary>
Logical
}
/// <summary>
/// Schema type property
/// </summary>
public Type Tag { get; private set; }
/// <summary>
/// Additional JSON attributes apart from those defined in the AVRO spec
/// </summary>
internal PropertyMap Props { get; private set; }
/// <summary>
/// Constructor for schema class
/// </summary>
/// <param name="type"></param>
/// <param name="props">dictionary that provides access to custom properties</param>
protected Schema(Type type, PropertyMap props)
{
this.Tag = type;
this.Props = props;
}
/// <summary>
/// If this is a record, enum or fixed, returns its name, otherwise the name the primitive type.
/// </summary>
public abstract string Name { get; }
/// <summary>
/// The name of this schema. If this is a named schema such as an enum, it returns the fully qualified
/// name for the schema. For other schemas, it returns the type of the schema.
/// </summary>
public virtual string Fullname
{
get { return Name; }
}
/// <summary>
/// Static class to return new instance of schema object
/// </summary>
/// <param name="jtok">JSON object</param>
/// <param name="names">list of named schemas already read</param>
/// <param name="encspace">enclosing namespace of the schema</param>
/// <returns>new Schema object</returns>
internal static Schema ParseJson(JToken jtok, SchemaNames names, string encspace)
{
if (null == jtok) throw new ArgumentNullException("j", "j cannot be null.");
if (jtok.Type == JTokenType.String) // primitive schema with no 'type' property or primitive or named type of a record field
{
string value = (string)jtok;
PrimitiveSchema ps = PrimitiveSchema.NewInstance(value);
if (null != ps) return ps;
NamedSchema schema = null;
if (names.TryGetValue(value, null, encspace, null, out schema)) return schema;
throw new SchemaParseException($"Undefined name: {value} at '{jtok.Path}'");
}
if (jtok is JArray) // union schema with no 'type' property or union type for a record field
return UnionSchema.NewInstance(jtok as JArray, null, names, encspace);
if (jtok is JObject) // JSON object with open/close parenthesis, it must have a 'type' property
{
JObject jo = jtok as JObject;
JToken jtype = jo["type"];
if (null == jtype)
throw new SchemaParseException($"Property type is required at '{jtok.Path}'");
var props = Schema.GetProperties(jtok);
if (jtype.Type == JTokenType.String)
{
string type = (string)jtype;
if (type.Equals("array", StringComparison.Ordinal))
return ArraySchema.NewInstance(jtok, props, names, encspace);
if (type.Equals("map", StringComparison.Ordinal))
return MapSchema.NewInstance(jtok, props, names, encspace);
if (null != jo["logicalType"]) // logical type based on a primitive
return LogicalSchema.NewInstance(jtok, props, names, encspace);
Schema schema = PrimitiveSchema.NewInstance((string)type, props);
if (null != schema) return schema;
return NamedSchema.NewInstance(jo, props, names, encspace);
}
else if (jtype.Type == JTokenType.Array)
return UnionSchema.NewInstance(jtype as JArray, props, names, encspace);
else if (jtype.Type == JTokenType.Object)
{
if (null != jo["logicalType"]) // logical type based on a complex type
{
return LogicalSchema.NewInstance(jtok, props, names, encspace);
}
var schema = ParseJson(jtype, names, encspace); // primitive schemas are allowed to have additional metadata properties
if (schema is PrimitiveSchema)
{
return schema;
}
}
}
throw new AvroTypeException($"Invalid JSON for schema: {jtok} at '{jtok.Path}'");
}
/// <summary>
/// Parses a given JSON string to create a new schema object
/// </summary>
/// <param name="json">JSON string</param>
/// <returns>new Schema object</returns>
public static Schema Parse(string json)
{
if (string.IsNullOrEmpty(json)) throw new ArgumentNullException(nameof(json), "json cannot be null.");
return Parse(json.Trim(), new SchemaNames(), null); // standalone schema, so no enclosing namespace
}
/// <summary>
/// Parses a JSON string to create a new schema object
/// </summary>
/// <param name="json">JSON string</param>
/// <param name="names">list of named schemas already read</param>
/// <param name="encspace">enclosing namespace of the schema</param>
/// <returns>new Schema object</returns>
internal static Schema Parse(string json, SchemaNames names, string encspace)
{
Schema sc = PrimitiveSchema.NewInstance(json);
if (null != sc) return sc;
try
{
bool IsArray = json.StartsWith("[", StringComparison.Ordinal)
&& json.EndsWith("]", StringComparison.Ordinal);
JContainer j = IsArray ? (JContainer)JArray.Parse(json) : (JContainer)JObject.Parse(json);
return ParseJson(j, names, encspace);
}
catch (Newtonsoft.Json.JsonSerializationException ex)
{
throw new SchemaParseException("Could not parse. " + ex.Message + Environment.NewLine + json);
}
}
/// <summary>
/// Static function to parse custom properties (not defined in the Avro spec) from the given JSON object
/// </summary>
/// <param name="jtok">JSON object to parse</param>
/// <returns>Property map if custom properties were found, null if no custom properties found</returns>
internal static PropertyMap GetProperties(JToken jtok)
{
var props = new PropertyMap();
props.Parse(jtok);
if (props.Count > 0)
return props;
else
return null;
}
/// <summary>
/// Returns the canonical JSON representation of this schema.
/// </summary>
/// <returns>The canonical JSON representation of this schema.</returns>
public override string ToString()
{
using (System.IO.StringWriter sw = new System.IO.StringWriter())
using (Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
{
WriteJson(writer, new SchemaNames(), null); // stand alone schema, so no enclosing name space
return sw.ToString();
}
}
/// <summary>
/// Writes opening { and 'type' property
/// </summary>
/// <param name="writer">JSON writer</param>
private void writeStartObject(JsonTextWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("type");
writer.WriteValue(GetTypeString(this.Tag));
}
/// <summary>
/// Returns symbol name for the given schema type
/// </summary>
/// <param name="type">schema type</param>
/// <returns>symbol name</returns>
public static string GetTypeString(Type type)
{
return type != Type.Enumeration ? type.ToString().ToLowerInvariant() : "enum";
}
/// <summary>
/// Default implementation for writing schema properties in JSON format
/// </summary>
/// <param name="writer">JSON writer</param>
/// <param name="names">list of named schemas already written</param>
/// <param name="encspace">enclosing namespace of the schema</param>
protected internal virtual void WriteJsonFields(JsonTextWriter writer, SchemaNames names, string encspace)
{
}
/// <summary>
/// Writes schema object in JSON format
/// </summary>
/// <param name="writer">JSON writer</param>
/// <param name="names">list of named schemas already written</param>
/// <param name="encspace">enclosing namespace of the schema</param>
protected internal virtual void WriteJson(JsonTextWriter writer, SchemaNames names, string encspace)
{
writeStartObject(writer);
WriteJsonFields(writer, names, encspace);
if (null != this.Props) Props.WriteJson(writer);
writer.WriteEndObject();
}
/// <summary>
/// Returns the schema's custom property value given the property name
/// </summary>
/// <param name="key">custom property name</param>
/// <returns>custom property value</returns>
public string GetProperty(string key)
{
if (null == this.Props) return null;
string v;
return this.Props.TryGetValue(key, out v) ? v : null;
}
/// <summary>
/// Hash code function
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return Tag.GetHashCode() + getHashCode(Props);
}
/// <summary>
/// Returns true if and only if data written using writerSchema can be read using the current schema
/// according to the Avro resolution rules.
/// </summary>
/// <param name="writerSchema">The writer's schema to match against.</param>
/// <returns>True if and only if the current schema matches the writer's.</returns>
public virtual bool CanRead(Schema writerSchema) { return Tag == writerSchema.Tag; }
/// <summary>
/// Compares two objects, null is equal to null
/// </summary>
/// <param name="o1">first object</param>
/// <param name="o2">second object</param>
/// <returns>true if two objects are equal, false otherwise</returns>
protected static bool areEqual(object o1, object o2)
{
return o1 == null ? o2 == null : o1.Equals(o2);
}
/// <summary>
/// Hash code helper function
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
protected static int getHashCode(object obj)
{
return obj == null ? 0 : obj.GetHashCode();
}
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Microsoft.Rest.Azure;
/// <summary>
/// An Azure Batch job to add.
/// </summary>
public partial class JobAddParameter
{
/// <summary>
/// Initializes a new instance of the JobAddParameter class.
/// </summary>
public JobAddParameter() { }
/// <summary>
/// Initializes a new instance of the JobAddParameter class.
/// </summary>
/// <param name="id">A string that uniquely identifies the job within the account.</param>
/// <param name="poolInfo">The pool on which the Batch service runs the job's tasks.</param>
/// <param name="displayName">The display name for the job.</param>
/// <param name="priority">The priority of the job.</param>
/// <param name="constraints">The execution constraints for the job.</param>
/// <param name="jobManagerTask">Details of a Job Manager task to be launched when the job is started.</param>
/// <param name="jobPreparationTask">The Job Preparation task.</param>
/// <param name="jobReleaseTask">The Job Release task.</param>
/// <param name="commonEnvironmentSettings">The list of common environment variable settings. These environment variables are set for all tasks in the job (including the Job Manager, Job Preparation and Job Release tasks).</param>
/// <param name="onAllTasksComplete">The action the Batch service should take when all tasks in the job are in the completed state. Possible values include: 'noAction', 'terminateJob'</param>
/// <param name="onTaskFailure">The action the Batch service should take when any task in the job fails. A task is considered to have failed if it completes with a non-zero exit code and has exhausted its retry count, or if it had a scheduling error. Possible values include: 'noAction', 'performExitOptionsJobAction'</param>
/// <param name="metadata">A list of name-value pairs associated with the job as metadata.</param>
/// <param name="usesTaskDependencies">The flag that determines if this job will use tasks with dependencies.</param>
public JobAddParameter(string id, PoolInformation poolInfo, string displayName = default(string), int? priority = default(int?), JobConstraints constraints = default(JobConstraints), JobManagerTask jobManagerTask = default(JobManagerTask), JobPreparationTask jobPreparationTask = default(JobPreparationTask), JobReleaseTask jobReleaseTask = default(JobReleaseTask), IList<EnvironmentSetting> commonEnvironmentSettings = default(IList<EnvironmentSetting>), OnAllTasksComplete? onAllTasksComplete = default(OnAllTasksComplete?), OnTaskFailure? onTaskFailure = default(OnTaskFailure?), IList<MetadataItem> metadata = default(IList<MetadataItem>), bool? usesTaskDependencies = default(bool?))
{
Id = id;
DisplayName = displayName;
Priority = priority;
Constraints = constraints;
JobManagerTask = jobManagerTask;
JobPreparationTask = jobPreparationTask;
JobReleaseTask = jobReleaseTask;
CommonEnvironmentSettings = commonEnvironmentSettings;
PoolInfo = poolInfo;
OnAllTasksComplete = onAllTasksComplete;
OnTaskFailure = onTaskFailure;
Metadata = metadata;
UsesTaskDependencies = usesTaskDependencies;
}
/// <summary>
/// Gets or sets a string that uniquely identifies the job within the
/// account.
/// </summary>
/// <remarks>
/// The id can contain any combination of alphanumeric characters
/// including hyphens and underscores, and cannot contain more than
/// 64 characters. It is common to use a GUID for the id.
/// </remarks>
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the display name for the job.
/// </summary>
[JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the priority of the job.
/// </summary>
/// <remarks>
/// Priority values can range from -1000 to 1000, with -1000 being
/// the lowest priority and 1000 being the highest priority. The
/// default value is 0.
/// </remarks>
[JsonProperty(PropertyName = "priority")]
public int? Priority { get; set; }
/// <summary>
/// Gets or sets the execution constraints for the job.
/// </summary>
[JsonProperty(PropertyName = "constraints")]
public JobConstraints Constraints { get; set; }
/// <summary>
/// Gets or sets details of a Job Manager task to be launched when the
/// job is started.
/// </summary>
[JsonProperty(PropertyName = "jobManagerTask")]
public JobManagerTask JobManagerTask { get; set; }
/// <summary>
/// Gets or sets the Job Preparation task.
/// </summary>
[JsonProperty(PropertyName = "jobPreparationTask")]
public JobPreparationTask JobPreparationTask { get; set; }
/// <summary>
/// Gets or sets the Job Release task.
/// </summary>
[JsonProperty(PropertyName = "jobReleaseTask")]
public JobReleaseTask JobReleaseTask { get; set; }
/// <summary>
/// Gets or sets the list of common environment variable settings.
/// These environment variables are set for all tasks in the job
/// (including the Job Manager, Job Preparation and Job Release
/// tasks).
/// </summary>
[JsonProperty(PropertyName = "commonEnvironmentSettings")]
public IList<EnvironmentSetting> CommonEnvironmentSettings { get; set; }
/// <summary>
/// Gets or sets the pool on which the Batch service runs the job's
/// tasks.
/// </summary>
[JsonProperty(PropertyName = "poolInfo")]
public PoolInformation PoolInfo { get; set; }
/// <summary>
/// Gets or sets the action the Batch service should take when all
/// tasks in the job are in the completed state. Possible values
/// include: 'noAction', 'terminateJob'
/// </summary>
[JsonProperty(PropertyName = "onAllTasksComplete")]
public OnAllTasksComplete? OnAllTasksComplete { get; set; }
/// <summary>
/// Gets or sets the action the Batch service should take when any
/// task in the job fails. A task is considered to have failed if it
/// completes with a non-zero exit code and has exhausted its retry
/// count, or if it had a scheduling error. Possible values include:
/// 'noAction', 'performExitOptionsJobAction'
/// </summary>
[JsonProperty(PropertyName = "onTaskFailure")]
public OnTaskFailure? OnTaskFailure { get; set; }
/// <summary>
/// Gets or sets a list of name-value pairs associated with the job as
/// metadata.
/// </summary>
[JsonProperty(PropertyName = "metadata")]
public IList<MetadataItem> Metadata { get; set; }
/// <summary>
/// Gets or sets the flag that determines if this job will use tasks
/// with dependencies.
/// </summary>
[JsonProperty(PropertyName = "usesTaskDependencies")]
public bool? UsesTaskDependencies { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Id == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Id");
}
if (PoolInfo == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "PoolInfo");
}
if (this.JobManagerTask != null)
{
this.JobManagerTask.Validate();
}
if (this.JobPreparationTask != null)
{
this.JobPreparationTask.Validate();
}
if (this.JobReleaseTask != null)
{
this.JobReleaseTask.Validate();
}
if (this.CommonEnvironmentSettings != null)
{
foreach (var element in this.CommonEnvironmentSettings)
{
if (element != null)
{
element.Validate();
}
}
}
if (this.PoolInfo != null)
{
this.PoolInfo.Validate();
}
if (this.Metadata != null)
{
foreach (var element1 in this.Metadata)
{
if (element1 != null)
{
element1.Validate();
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Continuum.Master.Host.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
namespace PCSComUtils.Common
{
/// <summary>
/// Summary description for Action, control on form. Default =0,Add = 1,Edit = 2,Copy = 3,Delete = 4
/// </summary>
public enum EnumAction
{
/// <summary>
/// 0
/// </summary>
Default =0,
/// <summary>
/// 1
/// </summary>
Add = 1,
/// <summary>
/// 2
/// </summary>
Edit = 2,
/// <summary>
/// 3
/// </summary>
Copy = 3,
/// <summary>
/// 4
/// </summary>
Delete = 4
}
/// <summary>
/// sys_TableField.SoftType: Sort type using in table configuration: None = 0,Ascending = 1,Descending = 2
/// </summary>
public enum EnumSortType
{
/// <summary>
/// 0
/// </summary>
None = 0,
/// <summary>
/// 1
/// </summary>
Ascending = 1,
/// <summary>
/// 2
/// </summary>
Descending = 2
}
/// <summary>
/// MoveDirection: Up,Down
/// </summary>
public enum MoveDirection
{
Up,
Down
}
/// <summary>
/// GutterPosition: Top = 1,Left = 0
/// </summary>
public enum GutterPosition
{
Top = 1,
Left = 0
}
/// <summary>
/// ViewReportMode: Normal = 0,History = 1
/// </summary>
public enum ViewReportMode
{
Normal = 0,
History = 1
}
/// <summary>
/// CostMethodEnum: ACT = 0,STD = 1,AVG = 2
/// </summary>
public enum CostMethodEnum
{
/// <summary>
/// 0
/// </summary>
ACT = 0,
/// <summary>
/// 1
/// </summary>
STD = 1,
/// <summary>
/// 2
/// </summary>
AVG = 2
}
/// <summary>
/// QAStatusEnum: REQUIRE_INSPECTION = 1,NOT_REQUIRE_INSPECTION = 2,QUALITY_ASSURED = 3
/// </summary>
public enum QAStatusEnum
{
REQUIRE_INSPECTION = 1,
NOT_REQUIRE_INSPECTION = 2,
QUALITY_ASSURED = 3
}
public enum LikeCondition
{
/// <summary>
/// Contain text
/// </summary>
Contain = 0,
/// <summary>
/// Start with text
/// </summary>
StartWith = 1,
/// <summary>
/// End with text
/// </summary>
EndWith = 2
}
/// <summary>
/// PartyTypeEnum: CUSTOMER = 0,VENDOR = 1,BOTH = 2, VENDOR-OUTSIDE = 3
/// </summary>
public enum PartyTypeEnum
{
/// <summary>
/// 0
/// </summary>
CUSTOMER = 0,
/// <summary>
/// 1
/// </summary>
VENDOR = 1,
/// <summary>
/// 2
/// </summary>
BOTH = 2,
/// <summary>
/// 3: Vendor-Outside
/// </summary>
OUTSIDE = 3,
}
/// <summary>
/// CapacityPeriod: Yearly = 0,Monthly = 1,Weekly = 2,Daily = 3
/// </summary>
public enum CapacityPeriod
{
/// <summary>
/// 0
/// </summary>
Yearly = 0,
/// <summary>
/// 1
/// </summary>
Monthly = 1,
/// <summary>
/// 2
/// </summary>
Weekly = 2,
/// <summary>
/// 3
/// </summary>
Daily = 3
}
/// <summary>
/// WOLineStatus: Unreleased = 1,Released = 2,MfgClose = 3,FinClose = 4
/// </summary>
public enum WOLineStatus
{
/// <summary>
/// 1
/// </summary>
Unreleased = 1,
/// <summary>
/// 2
/// </summary>
Released = 2,
/// <summary>
/// 3
/// </summary>
MfgClose = 3,
/// <summary>
/// 4
/// </summary>
FinClose = 4
}
/// <summary>
/// WOScheduleCode: B = 1,F = 2,U = 3
/// </summary>
public enum WOScheduleCode
{
/// <summary>
/// 1
/// </summary>
B = 1,
/// <summary>
/// 2
/// </summary>
F = 2,
/// <summary>
/// 3
/// </summary>
U = 3
}
/// <summary>
/// Type of Operation: Inside = 0,Outside = 1
/// </summary>
public enum OperationType
{
/// <summary>
/// 0
/// </summary>
Inside = 0,
/// <summary>
/// 1
/// </summary>
Outside = 1
}
/// <summary>
/// InspectionStatus: Waiting = 1,OnHold = 2,Accepted = 3,Rejected = 4
/// </summary>
public enum InspectionStatus
{
/// <summary>
/// 1
/// </summary>
Waiting = 1,
/// <summary>
/// 2
/// </summary>
OnHold = 2,
/// <summary>
/// 3
/// </summary>
Accepted = 3,
/// <summary>
/// 4
/// </summary>
Rejected = 4
}
/// <summary>
/// Type of planning: MRP = 1,MPS = 2
/// </summary>
public enum PlanTypeEnum
{
/// <summary>
/// 1
/// </summary>
MRP = 1,
/// <summary>
/// 2
/// </summary>
MPS = 2
}
/// <summary>
/// Schedule Method: Forward = 1,Backward = 2
/// </summary>
public enum ScheduleMethodEnum
{
/// <summary>
/// 1
/// </summary>
Forward = 1,
/// <summary>
/// 2
/// </summary>
Backward = 2
}
/// <summary>
/// DistributionMethodEnum: ByQuantity =1, ByMaterial = 2, ByPercent = 3, ByLeadTime = 4
/// </summary>
public enum DistributionMethodEnum
{
/// <summary>
/// 1
/// </summary>
ByQuantity =1,
/// <summary>
/// 2
/// </summary>
ByMaterial = 2,
/// <summary>
/// 3
/// </summary>
ByPercent = 3,
/// <summary>
/// 4
/// </summary>
ByLeadTime = 4
}
/// <summary>
/// Type of Schedule: InfiniteScheduling= 0,LoadAveraging = 1,FiniteScheduling =2
/// </summary>
public enum ScheduleType
{
/// <summary>
/// 0
/// </summary>
InfiniteScheduling= 0,
/// <summary>
/// 1
/// </summary>
LoadAveraging = 1,
/// <summary>
/// 2
/// </summary>
FiniteScheduling =2
}
/// <summary>
/// Type of WC: Labor= 0,Machine = 1
/// </summary>
public enum WCType
{
/// <summary>
/// 0: WC using Labor
/// </summary>
Labor= 0,
/// <summary>
/// 0: WC using Machine
/// </summary>
Machine = 1
}
/// <summary>
/// Routing.Pacer using in routing: B= 'B',M = 'M',L = 'L'
/// </summary>
public enum PacerEnum
{
/// <summary>
/// 'B': Both Machine and Labor
/// </summary>
B = 'B',
/// <summary>
/// 'M': Machine only
/// </summary>
M = 'M',
/// <summary>
/// 'L': Labor only
/// </summary>
L = 'L'
}
/// <summary>
/// Level group of field: One = 1,Two = 2
/// </summary>
public enum GroupFieldLevel
{
/// <summary>
/// 1: Level one
/// </summary>
One = 1,
/// <summary>
/// 2: Level two
/// </summary>
Two = 2
}
/// <summary>
/// Sys_Menu_Entry.Type column enum VisibleBoth = 0, InvisibleBoth = 1, InvisibleMenu = 2, VisibleMenu = 3
/// </summary>
public enum MenuTypeEnum
{
/// <summary>
/// 0 : visible in both menu and right assignment
/// </summary>
VisibleBoth = 0,
/// <summary>
/// 1 : invisible in both menu and right assignment
/// </summary>
InvisibleBoth = 1,
/// <summary>
/// 2 : invisible in menu but visible in right assignment
/// </summary>
InvisibleMenu = 2,
/// <summary>
/// 3 : visible in menu but invisible in right assignment
/// </summary>
VisibleMenu = 3
}
// HACK: SonHT 2005-10-13: using System.Drawing.Printing.PaperKind
// /// <summary>
// /// PaperSize enum: A3 = 1,A4 = 2,Legal = 3,Letter = 4
// /// </summary>
// public enum PaperSizeEnum
// {
// /// <summary>
// /// 1 : A3 paper size
// /// </summary>
// A3 = 1,
// /// <summary>
// /// 2 : A4 paper size
// /// </summary>
// A4 = 2,
// /// <summary>
// /// 3 : Legal paper size
// /// </summary>
// Legal = 3,
// /// <summary>
// /// 4 : Letter paper size
// /// </summary>
// Letter = 4
// }
// END: SonHT 2005-10-DD
/// <summary>
/// Sys_Menu_Entry.ParentChild enum: RootMenu = 1,NormalMenu = 2,LeafMenu = 3,SpecialLeafMenu = 10
/// </summary>
public enum MenuParentChildEnum
{
/// <summary>
/// 1: Root menu
/// </summary>
RootMenu = 1,
/// <summary>
/// 2: Normal menu (middle menu)
/// </summary>
NormalMenu = 2,
/// <summary>
/// 3: Leaf menu
/// </summary>
LeafMenu = 3,
/// <summary>
/// 10: Special menu (hidden menu)
/// </summary>
SpecialLeafMenu = 10
}
/// <summary>
/// Character-case format in table framework: Normal = 0, Upper = 1, Lower = 2
/// </summary>
public enum CharacterCaseEnum
{
/// <summary>
/// 0: Normal character
/// </summary>
Normal = 0,
/// <summary>
/// 1: Upper character
/// </summary>
Upper = 1,
/// <summary>
/// 2: Lower character
/// </summary>
Lower = 2
}
/// <summary>
/// DCPResultDetail.Type: 0 - Running, 1 - Change category, 2 - CheckPoint
/// </summary>
public enum DCPResultTypeEnum
{
/// <summary>
/// 0: Running time
/// </summary>
Running = 0,
/// <summary>
/// 1: Change category time
/// </summary>
ChangeCategory = 1,
/// <summary>
/// 2: Check point time
/// </summary>
CheckPoint = 2
}
/// <summary>
/// Sys_ReportField.Type - Display type of field: Default, Bar Chart or Record Counter
/// </summary>
public enum FieldTypeEnum
{
/// <summary>
/// Default display type
/// </summary>
Default = 0,
/// <summary>
/// Display field as Bar Chart
/// </summary>
BarChart = 1,
/// <summary>
/// Display field and record counter
/// </summary>
RecordCounter = 2
}
/// <summary>
/// Specifies the border style of a report
/// </summary>
public enum TableBoderEnum
{
/// <summary>
/// No border
/// </summary>
None = 0,
/// <summary>
/// Vertical line border
/// </summary>
Vertical = 1,
/// <summary>
/// Horizontal line border
/// </summary>
Horizontal = 2,
/// <summary>
/// Vertical and Horizontal line border
/// </summary>
Both = 3
}
/// <summary>
/// Visibility Group Type Enum
/// </summary>
public enum VisibilityGroupTypeEnum
{
/// <summary>
/// Nature group: Container control or C1TrueDBGrid
/// </summary>
Container = 1,
/// <summary>
/// Define group: Group of control
/// </summary>
GroupNormal = 2,
}
/// <summary>
/// Visibility Item Type Enum
/// </summary>
public enum VisibilityItemTypeEnum
{
/// <summary>
/// Column of C1TrueDBGrid
/// </summary>
ColumnTrueDBGrid = 1,
/// <summary>
/// Special item
/// </summary>
SpecialItem = 2,
}
/// <summary>
/// Type of transaction
/// </summary>
public enum TransactionTypeEnum
{
/// <summary>
/// Sale order transaction
/// </summary>
SaleOrder = 0,
/// <summary>
/// Return goods receive transaction
/// </summary>
SOReturnGoodsReceive = 1,
/// <summary>
/// Cancel commitment transaction
/// </summary>
SOCancelCommitment = 2,
/// <summary>
/// Confirm shipment transaction
/// </summary>
SOConfirmShipment = 3,
/// <summary>
/// Purchase order transaction
/// </summary>
POPurchaseOrder = 4,
/// <summary>
/// Purchase order receipt transaction
/// </summary>
POPurchaseOrderReceipts = 5,
/// <summary>
/// Return to vendor transaction
/// </summary>
POReturnToVendor = 6,
/// <summary>
/// Material Receipt transaction
/// </summary>
IVMaterialReceipt = 7,
/// <summary>
/// Material Issue transaction
/// </summary>
IVMaterialIssue = 8,
/// <summary>
/// Material Scrap transaction
/// </summary>
IVMaterialScrap = 9,
/// <summary>
/// Loc to loc transfer
/// </summary>
IVLocToLocTransfer = 10,
/// <summary>
/// Inventory Adjusment transaction
/// </summary>
IVInventoryAdjustment = 11,
/// <summary>
///public const string INSPECTION_RESULT = "IVInspectionResult";
/// </summary>
IVInspectionResult = 12,
/// <summary>
///public const string MRB_RESULT = "IVMRBResult";
/// </summary>
IVMRBResult = 13,
/// <summary>
/// Work order completion transaction
/// </summary>
PROWorkOrderCompletion = 14,
/// <summary>
///public const string WO_REVERSAL ="WOReversal";
/// </summary>
WOReversal = 15,
/// <summary>
/// Issue material for work order transaction
/// </summary>
PROIssueMaterial = 16,
/// <summary>
/// Shipping management transaction
/// </summary>
ShippingManagement = 17,
/// <summary>
/// Sale order commitment transaction
/// </summary>
SOCommitment = 18,
/// <summary>
/// 19. Miscellaneous Issue transaction
/// </summary>
IVMiscellaneousIssue = 19,
RecoverableMaterial = 20,
/// <summary>
/// Shipping adjustment transaction
/// </summary>
ShippingAdjustment = 26,
/// <summary>
/// 27.Delete transaction
/// </summary>
DeleteTransaction = 27
}
public enum OrderPolicyEnum
{
Daily,
Weekly,
Monthly,
Quarterly,
Yearly
}
/// <summary>
/// Specifies identifiers to indicate the grouping method when running MPS
/// </summary>
public enum MPSGroupByEnum
{
/// <summary>
/// Group by Hour
/// </summary>
ByHour = 0,
/// <summary>
/// Group by Day
/// </summary>
ByDay = 1
}
public enum TransactionHistoryType
{
/// <summary>
/// Out, xuat hang khoi kho
/// </summary>
Out = 0,
/// <summary>
/// In, nhap hang vao kho
/// </summary>
In = 1,
/// <summary>
/// Both, vu xuat vua nhap
/// </summary>
Both = 2,
/// <summary>
/// Booking, commit kho
/// </summary>
Booking = 3
}
/// <summary>
/// Type of PO Receipt
/// </summary>
public enum POReceiptTypeEnum
{
/// <summary>
/// Receipt By Purchase Order
/// </summary>
ByPO = 0,
/// <summary>
/// Receipt By Item
/// </summary>
ByItem = 1,
/// <summary>
/// Receipt By Delivery Slip
/// </summary>
ByDeliverySlip = 2,
/// <summary>
/// Receipt By Invoice
/// </summary>
ByInvoice = 3,
/// <summary>
/// Receipt By Outside
/// </summary>
ByOutside = 4
}
/// <summary>
/// Purpose
/// </summary>
public enum PurposeEnum
{
/// <summary>
/// Xuat Ke Hoach
/// </summary>
Plan = 1,
/// <summary>
/// Xuat Bat Thuong
/// </summary>
Misc = 2,
/// <summary>
/// Xuat Bu Hong
/// </summary>
Compensation = 3,
/// <summary>
/// Xuat tra lai nha cung cap
/// </summary>
ReturnToVendor = 4,
/// <summary>
/// Xuat tra lai cong doan truoc
/// </summary>
ReturnPrevious = 5,
/// <summary>
/// QC
/// </summary>
QC = 6,
/// <summary>
/// Xuat hang gia cong ngoai
/// </summary>
Outside = 7,
/// <summary>
/// Xuat ban hang
/// </summary>
Ship = 8,
/// <summary>
/// Nhap hang tu nha cung cap
/// </summary>
Receipt = 9,
/// <summary>
/// Nhap san pham hoan thanh
/// </summary>
Completion = 10,
/// <summary>
/// Nhap hang tra lai tu khach hang
/// </summary>
ReturnGoodReceipt = 11,
/// <summary>
/// Xuat Chuyen Kho
/// </summary>
LocToLoc = 12,
/// <summary>
/// Chuyen tu kho NG den kho OK
/// </summary>
Transfer = 13,
/// <summary>
/// Xuat Huy
/// </summary>
Scrap = 14,
/// <summary>
/// Adjustment
/// </summary>
Adjustment = 15,
/// <summary>
/// Commit
/// </summary>
Commit = 16,
/// <summary>
/// Cancel Commitment
/// </summary>
CancelCommitment = 17,
/// <summary>
/// Nhap linh kien tan dung sau huy
/// </summary>
TanDungLinhKienSauHuy = 18,
/// <summary>
/// Thanh ly phe lieu sau huy
/// </summary>
ThanhLyLinhKienSauHuy = 19,
/// <summary>
/// In Compensation for Customer
/// </summary>
CompensationForCustomer = 20
}
/// <summary>
/// Location Type (Base on row ID)
/// </summary>
public enum LocationTypeEnum
{
/// <summary>
/// Warehouse
/// </summary>
WareHouse= 1,
/// <summary>
/// Manufacturing
/// </summary>
Manufacturing = 2
}
/// <summary>
/// BIN Type (Base on row ID)
/// </summary>
public enum BinTypeEnum
{
/// <summary>
/// OK
/// </summary>
OK = 1,
/// <summary>
/// No Good
/// </summary>
NG = 2,
/// <summary>
/// Destroy bin
/// </summary>
LS = 3,
/// <summary>
/// Incomming (Buffer bin)
/// </summary>
IN = 4
}
/// <summary>
/// Purchase Order Vendor Delivery Type
/// </summary>
public enum PODeliveryTypeEnum
{
/// <summary>
/// Daily
/// </summary>
Daily = 0,
/// <summary>
/// Weekly
/// </summary>
Weekly = 1,
/// <summary>
/// Monthly
/// </summary>
Monthly = 2
}
/// <summary>
/// Day Of Week
/// </summary>
public enum DayOfWeekEnum
{
/// <summary>
/// Sunday
/// </summary>
Sunday = 0,
/// <summary>
/// Monday
/// </summary>
Monday = 1,
/// <summary>
/// Tuesday
/// </summary>
Tuesday = 2,
/// <summary>
/// Wednesday
/// </summary>
Wednesday = 3,
/// <summary>
/// Thusday
/// </summary>
Thusday = 4,
/// <summary>
/// Friday
/// </summary>
Friday = 5,
/// <summary>
/// Saturday
/// </summary>
Saturday = 6
}
/// <summary>
/// Cost Element Type
/// </summary>
public enum CostElementType
{
/// <summary>
/// Machine
/// </summary>
Machine = 1,
/// <summary>
/// Labor
/// </summary>
Labor = 2,
/// <summary>
/// Raw Material
/// </summary>
Material = 3,
/// <summary>
/// Sub Material
/// </summary>
SubMaterial = 4,
/// <summary>
/// Over Head
/// </summary>
OverHead = 5
}
/// <summary>
/// Freight Type
/// </summary>
public enum FreightType
{
/// <summary>
/// ForPO
/// </summary>
ForPO = 1,
/// <summary>
/// ForInvoice
/// </summary>
ForInvoice = 0,
}
/// <summary>
/// Planning Group By
/// </summary>
public enum PlanningGroupBy
{
/// <summary>
/// By Date
/// </summary>
ByDate = 0,
/// <summary>
/// By Hour
/// </summary>
ByHour = 1,
/// <summary>
/// By Shift
/// </summary>
ByShift = 2
}
/// <summary>
/// Additional Charge Purpose
/// </summary>
public enum ACPurpose
{
/// <summary>
/// Freight
/// </summary>
Freight = 1,
/// <summary>
/// Import Tax
/// </summary>
ImportTax= 2,
/// <summary>
/// Credit Note
/// </summary>
CreditNote= 3,
/// <summary>
/// Debit Note
/// </summary>
DebitNote= 4
}
/// <summary>
/// Additional Charge Object
/// </summary>
public enum ACObject
{
/// <summary>
/// Receipt Transaction
/// </summary>
ReceiptTransaction = 1,
/// <summary>
/// Item Inventory
/// </summary>
ItemInventory = 2
}
/// <summary>
/// Type for Sale Order (Import/Export)
/// </summary>
public enum SOType
{
/// <summary>
/// Import
/// </summary>
Import = 1,
/// <summary>
/// Export
/// </summary>
Export = 2
}
/// <summary>
/// Type for Purchase Order (Domestic/Import/Outside)
/// </summary>
public enum POType
{
/// <summary>
/// Domestic
/// </summary>
Domestic = 1,
/// <summary>
/// Import
/// </summary>
Import = 2,
/// <summary>
/// Outside
/// </summary>
Outside = 3
}
/// <summary>
/// View Type for Shipping Management form
/// </summary>
public enum ShipViewType
{
/// <summary>
/// Print Invoice
/// </summary>
PrintInvoice = 0,
/// <summary>
/// Shipping
/// </summary>
Shipping = 1
}
/// <summary>
/// Receipt purose
/// </summary>
public enum ReceiptPurpose
{
/// <summary>
/// Plan
/// </summary>
Plan = 0,
/// <summary>
/// Compensation
/// </summary>
Compensation = 1
}
/// <summary>
/// Purpose for Post date configuration table
/// </summary>
public enum PostDateConfigPurpose
{
/// <summary>
/// Config for postdate
/// </summary>
PostDate,
/// <summary>
/// Config for search form condition
/// </summary>
SearchCondition
}
/// <summary>
/// Permission for menu of system
/// </summary>
public enum MenuPermission
{
/// <summary>
/// No permission
/// </summary>
None = 0,
/// <summary>
/// View
/// </summary>
View = 1,
/// <summary>
/// Full permission
/// </summary>
All = 31,
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using System.Diagnostics;
using System.Globalization;
using System.Collections;
using System.IO;
using System.Linq;
using MSBuild = Microsoft.Build.BuildEngine;
using System.Collections.Generic;
using Microsoft.VisualStudio.FSharp.LanguageService;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
/// <summary>
/// Implements the configuration dependent properties interface
/// </summary>
[CLSCompliant(false), ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class ProjectConfigProperties :
VSLangProj.ProjectConfigurationProperties
{
private ProjectConfig projectConfig;
internal ProjectConfigProperties(ProjectConfig projectConfig)
{
this.projectConfig = projectConfig;
}
public virtual string OutputPath
{
get
{
return this.projectConfig.GetConfigurationProperty(BuildPropertyPageTag.OutputPath.ToString(), true);
}
set
{
this.projectConfig.SetConfigurationProperty(BuildPropertyPageTag.OutputPath.ToString(), value);
}
}
public string __id
{
get { return UIThread.DoOnUIThread(() => projectConfig.ConfigName); }
}
public bool AllowUnsafeBlocks
{
get { return false; }
set { throw new NotImplementedException(); }
}
public uint BaseAddress
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool CheckForOverflowUnderflow
{
get { return false; }
set { throw new NotImplementedException(); }
}
public bool RemoveIntegerChecks
{
get { return false; }
set { throw new NotImplementedException(); }
}
public bool IncrementalBuild
{
get { return false; }
set { throw new NotImplementedException(); }
}
public bool StartWithIE
{
get { return false; }
set { throw new NotImplementedException(); }
}
public string ConfigurationOverrideFile
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string IntermediatePath
{
get { return UIThread.DoOnUIThread(() => projectConfig.GetConfigurationProperty("IntermediatePath", false)); }
set { UIThread.DoOnUIThread(() => { projectConfig.SetConfigurationProperty("IntermediatePath", value); }); }
}
public bool DebugSymbols
{
get { return UIThread.DoOnUIThread(() => projectConfig.DebugSymbols); }
set { projectConfig.DebugSymbols = value; }
}
public string DefineConstants
{
get { return UIThread.DoOnUIThread(() => projectConfig.DefineConstants); }
set { UIThread.DoOnUIThread(() => { projectConfig.DefineConstants = value; }); }
}
private bool IsDefined(string constant)
{
var constants = projectConfig.DefineConstants;
var array = constants.Split(';');
return array.Contains(constant);
}
private void SetDefine(string constant, bool value)
{
var constants = projectConfig.DefineConstants;
var array = constants.Split(';');
if (value && !array.Contains(constant))
{
var l = new List<string>(array);
l.Add(constant);
projectConfig.DefineConstants = String.Join(";", l);
}
else if (!value && array.Contains(constant))
{
projectConfig.DefineConstants = String.Join(";", array.All(s => s != constant));
}
}
public bool DefineDebug
{
get { return UIThread.DoOnUIThread(() => this.IsDefined("DEBUG")); }
set { UIThread.DoOnUIThread(() => { this.SetDefine("DEBUG", value); }); }
}
public bool DefineTrace
{
get { return UIThread.DoOnUIThread(() => this.IsDefined("TRACE")); }
set { UIThread.DoOnUIThread(() => { this.SetDefine("TRACE", value); }); }
}
public bool EnableASPDebugging
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool EnableASPXDebugging
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string StartPage
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public VSLangProj.prjStartAction StartAction
{
get
{
switch(UIThread.DoOnUIThread(() => projectConfig.StartAction))
{
case 1: return VSLangProj.prjStartAction.prjStartActionProgram;
case 2: return VSLangProj.prjStartAction.prjStartActionURL;
default: return VSLangProj.prjStartAction.prjStartActionProject;
}
}
set
{
int result;
switch(value)
{
case VSLangProj.prjStartAction.prjStartActionProject:
result = 0;
break;
case VSLangProj.prjStartAction.prjStartActionURL:
result = 2;
break;
case VSLangProj.prjStartAction.prjStartActionProgram:
result = 1;
break;
default:
result = 0;
break;
}
UIThread.DoOnUIThread(() => { projectConfig.StartAction = result; });
}
}
public VSLangProj.prjWarningLevel WarningLevel
{
get
{
var level = UIThread.DoOnUIThread(() => projectConfig.WarningLevel);
switch(level)
{
case 0: return VSLangProj.prjWarningLevel.prjWarningLevel0;
case 1: return VSLangProj.prjWarningLevel.prjWarningLevel1;
case 2: return VSLangProj.prjWarningLevel.prjWarningLevel2;
case 3: return VSLangProj.prjWarningLevel.prjWarningLevel3;
default: return VSLangProj.prjWarningLevel.prjWarningLevel4;
}
}
set
{
UIThread.DoOnUIThread(() => projectConfig.WarningLevel = (int)value);
}
}
public uint FileAlignment
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool RegisterForComInterop
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string ExtenderCATID
{
get
{
Guid catid = projectConfig.ProjectMgr.GetCATIDForType(this.GetType());
if (Guid.Empty.CompareTo(catid) == 0)
{
return null;
}
return catid.ToString("B");
}
}
public object ExtenderNames
{
get
{
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)projectConfig.ProjectMgr.GetService(typeof(EnvDTE.ObjectExtenders));
if (extenderService == null)
{
throw new InvalidOperationException();
}
return extenderService.GetExtenderNames(this.ExtenderCATID, projectConfig);
}
}
public object get_Extender(string extenderName)
{
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)projectConfig.ProjectMgr.GetService(typeof(EnvDTE.ObjectExtenders));
if (extenderService == null)
{
throw new InvalidOperationException();
}
return extenderService.GetExtender(this.ExtenderCATID, extenderName, projectConfig);
}
public string DocumentationFile
{
get { return UIThread.DoOnUIThread(() => projectConfig.DocumentationFile); }
set { UIThread.DoOnUIThread(() => { projectConfig.DocumentationFile = value; }); }
}
public string StartProgram
{
get { return UIThread.DoOnUIThread(() => projectConfig.StartProgram); }
set { UIThread.DoOnUIThread(() => { projectConfig.StartProgram = value; }); }
}
public string StartWorkingDirectory
{
get { return UIThread.DoOnUIThread(() => projectConfig.StartWorkingDirectory); }
set { UIThread.DoOnUIThread(() => { projectConfig.StartWorkingDirectory = value; }); }
}
public string StartURL
{
get { return UIThread.DoOnUIThread(() => projectConfig.StartURL); }
set { UIThread.DoOnUIThread(() => { projectConfig.StartURL = value; }); }
}
public string StartArguments
{
get { return UIThread.DoOnUIThread(() => projectConfig.StartArguments); }
set { UIThread.DoOnUIThread(() => { projectConfig.StartArguments = value; }); }
}
public bool Optimize
{
get { return UIThread.DoOnUIThread(() => projectConfig.Optimize); }
set { UIThread.DoOnUIThread(() => { projectConfig.Optimize = value; }); }
}
public bool EnableUnmanagedDebugging
{
get { return UIThread.DoOnUIThread(() => projectConfig.EnableUnmanagedDebugging); }
set { UIThread.DoOnUIThread(() => { projectConfig.EnableUnmanagedDebugging = value; }); }
}
public bool TreatWarningsAsErrors
{
get { return UIThread.DoOnUIThread(() => projectConfig.TreatWarningsAsErrors); }
set { UIThread.DoOnUIThread(() => { projectConfig.TreatWarningsAsErrors = value; }); }
}
public bool EnableSQLServerDebugging
{
get { return UIThread.DoOnUIThread(() => projectConfig.EnableSQLServerDebugging); }
set { UIThread.DoOnUIThread(() => { projectConfig.EnableSQLServerDebugging = value; }); }
}
public bool RemoteDebugEnabled
{
get { return UIThread.DoOnUIThread(() => projectConfig.RemoteDebugEnabled); }
set { UIThread.DoOnUIThread(() => { projectConfig.RemoteDebugEnabled = value; }); }
}
public string RemoteDebugMachine
{
get { return UIThread.DoOnUIThread(() => projectConfig.RemoteDebugMachine); }
set { UIThread.DoOnUIThread(() => { projectConfig.RemoteDebugMachine = 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.
/*=============================================================================
**
**
** Purpose: A circular-array implementation of a generic queue.
**
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
// A simple Queue of generic objects. Internally it is implemented as a
// circular buffer, so Enqueue can be O(n). Dequeue is O(1).
[DebuggerTypeProxy(typeof(QueueDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class Queue<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
{
private T[] _array;
private int _head; // The index from which to dequeue if the queue isn't empty.
private int _tail; // The index at which to enqueue if the queue isn't full.
private int _size; // Number of elements.
private int _version;
[NonSerialized]
private object _syncRoot;
private const int MinimumGrow = 4;
private const int GrowFactor = 200; // double each time
// Creates a queue with room for capacity objects. The default initial
// capacity and grow factor are used.
public Queue()
{
_array = Array.Empty<T>();
}
// Creates a queue with room for capacity objects. The default grow factor
// is used.
public Queue(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
_array = new T[capacity];
}
// Fills a Queue with the elements of an ICollection. Uses the enumerator
// to get each of the elements.
public Queue(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
_array = EnumerableHelpers.ToArray(collection, out _size);
if (_size != _array.Length) _tail = _size;
}
public int Count
{
get { return _size; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the queue.
public void Clear()
{
if (_size != 0)
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
if (_head < _tail)
{
Array.Clear(_array, _head, _size);
}
else
{
Array.Clear(_array, _head, _array.Length - _head);
Array.Clear(_array, 0, _tail);
}
}
_size = 0;
}
_head = 0;
_tail = 0;
_version++;
}
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
int arrayLen = array.Length;
if (arrayLen - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int numToCopy = _size;
if (numToCopy == 0) return;
int firstPart = Math.Min(_array.Length - _head, numToCopy);
Array.Copy(_array, _head, array, arrayIndex, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, arrayIndex + _array.Length - _head, numToCopy);
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
int arrayLen = array.Length;
if (index < 0 || index > arrayLen)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
if (arrayLen - index < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int numToCopy = _size;
if (numToCopy == 0) return;
try
{
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, index, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
// Adds item to the tail of the queue.
public void Enqueue(T item)
{
if (_size == _array.Length)
{
int newcapacity = (int)((long)_array.Length * (long)GrowFactor / 100);
if (newcapacity < _array.Length + MinimumGrow)
{
newcapacity = _array.Length + MinimumGrow;
}
SetCapacity(newcapacity);
}
_array[_tail] = item;
MoveNext(ref _tail);
_size++;
_version++;
}
// GetEnumerator returns an IEnumerator over this Queue. This
// Enumerator will support removing.
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
// Removes the object at the head of the queue and returns it. If the queue
// is empty, this method throws an
// InvalidOperationException.
public T Dequeue()
{
if (_size == 0)
{
ThrowForEmptyQueue();
}
T removed = _array[_head];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
_array[_head] = default(T);
}
MoveNext(ref _head);
_size--;
_version++;
return removed;
}
public bool TryDequeue(out T result)
{
if (_size == 0)
{
result = default(T);
return false;
}
result = _array[_head];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
_array[_head] = default(T);
}
MoveNext(ref _head);
_size--;
_version++;
return true;
}
// Returns the object at the head of the queue. The object remains in the
// queue. If the queue is empty, this method throws an
// InvalidOperationException.
public T Peek()
{
if (_size == 0)
{
ThrowForEmptyQueue();
}
return _array[_head];
}
public bool TryPeek(out T result)
{
if (_size == 0)
{
result = default(T);
return false;
}
result = _array[_head];
return true;
}
// Returns true if the queue contains at least one object equal to item.
// Equality is determined using EqualityComparer<T>.Default.Equals().
public bool Contains(T item)
{
if (_size == 0)
{
return false;
}
if (_head < _tail)
{
return Array.IndexOf(_array, item, _head, _size) >= 0;
}
// We've wrapped around. Check both partitions, the least recently enqueued first.
return
Array.IndexOf(_array, item, _head, _array.Length - _head) >= 0 ||
Array.IndexOf(_array, item, 0, _tail) >= 0;
}
// Iterates over the objects in the queue, returning an array of the
// objects in the Queue, or an empty array if the queue is empty.
// The order of elements in the array is first in to last in, the same
// order produced by successive calls to Dequeue.
public T[] ToArray()
{
if (_size == 0)
{
return Array.Empty<T>();
}
T[] arr = new T[_size];
if (_head < _tail)
{
Array.Copy(_array, _head, arr, 0, _size);
}
else
{
Array.Copy(_array, _head, arr, 0, _array.Length - _head);
Array.Copy(_array, 0, arr, _array.Length - _head, _tail);
}
return arr;
}
// PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity
// must be >= _size.
private void SetCapacity(int capacity)
{
T[] newarray = new T[capacity];
if (_size > 0)
{
if (_head < _tail)
{
Array.Copy(_array, _head, newarray, 0, _size);
}
else
{
Array.Copy(_array, _head, newarray, 0, _array.Length - _head);
Array.Copy(_array, 0, newarray, _array.Length - _head, _tail);
}
}
_array = newarray;
_head = 0;
_tail = (_size == capacity) ? 0 : _size;
_version++;
}
// Increments the index wrapping it if necessary.
private void MoveNext(ref int index)
{
// It is tempting to use the remainder operator here but it is actually much slower
// than a simple comparison and a rarely taken branch.
int tmp = index + 1;
index = (tmp == _array.Length) ? 0 : tmp;
}
private void ThrowForEmptyQueue()
{
Debug.Assert(_size == 0);
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
}
public void TrimExcess()
{
int threshold = (int)(((double)_array.Length) * 0.9);
if (_size < threshold)
{
SetCapacity(_size);
}
}
// Implements an enumerator for a Queue. The enumerator uses the
// internal version number of the list to ensure that no modifications are
// made to the list while an enumeration is in progress.
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
[Serializable]
public struct Enumerator : IEnumerator<T>,
System.Collections.IEnumerator
{
private readonly Queue<T> _q;
private readonly int _version;
private int _index; // -1 = not started, -2 = ended/disposed
private T _currentElement;
internal Enumerator(Queue<T> q)
{
_q = q;
_version = q._version;
_index = -1;
_currentElement = default(T);
}
public void Dispose()
{
_index = -2;
_currentElement = default(T);
}
public bool MoveNext()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
return false;
_index++;
if (_index == _q._size)
{
// We've run past the last element
_index = -2;
_currentElement = default(T);
return false;
}
// Cache some fields in locals to decrease code size
T[] array = _q._array;
int capacity = array.Length;
// _index represents the 0-based index into the queue, however the queue
// doesn't have to start from 0 and it may not even be stored contiguously in memory.
int arrayIndex = _q._head + _index; // this is the actual index into the queue's backing array
if (arrayIndex >= capacity)
{
// NOTE: Originally we were using the modulo operator here, however
// on Intel processors it has a very high instruction latency which
// was slowing down the loop quite a bit.
// Replacing it with simple comparison/subtraction operations sped up
// the average foreach loop by 2x.
arrayIndex -= capacity; // wrap around if needed
}
_currentElement = array[arrayIndex];
return true;
}
public T Current
{
get
{
if (_index < 0)
ThrowEnumerationNotStartedOrEnded();
return _currentElement;
}
}
private void ThrowEnumerationNotStartedOrEnded()
{
Debug.Assert(_index == -1 || _index == -2);
throw new InvalidOperationException(_index == -1 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded);
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -1;
_currentElement = default(T);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Web;
using ServiceStack.Common.Extensions;
using ServiceStack.Common.Web;
using ServiceStack.Logging;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceModel.Serialization;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Extensions;
namespace ServiceStack.WebHost.Endpoints.Support
{
public abstract class EndpointHandlerBase
: IServiceStackHttpHandler, IHttpHandler
{
private static readonly ILog Log = LogManager.GetLogger(typeof(EndpointHandlerBase));
private static readonly Dictionary<byte[], byte[]> NetworkInterfaceIpv4Addresses = new Dictionary<byte[], byte[]>();
private static readonly byte[][] NetworkInterfaceIpv6Addresses = new byte[0][];
public string RequestName { get; set; }
static EndpointHandlerBase()
{
try
{
IPAddressExtensions.GetAllNetworkInterfaceIpv4Addresses().ForEach((x, y) => NetworkInterfaceIpv4Addresses[x.GetAddressBytes()] = y.GetAddressBytes());
NetworkInterfaceIpv6Addresses = IPAddressExtensions.GetAllNetworkInterfaceIpv6Addresses().ConvertAll(x => x.GetAddressBytes()).ToArray();
}
catch (Exception ex)
{
Log.Warn("Failed to retrieve IP Addresses, some security restriction features may not work: " + ex.Message, ex);
}
}
public EndpointAttributes HandlerAttributes { get; set; }
public bool IsReusable
{
get { return false; }
}
public abstract object CreateRequest(IHttpRequest request, string operationName);
public abstract object GetResponse(IHttpRequest httpReq, IHttpResponse httpRes, object request);
public virtual void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
{
throw new NotImplementedException();
}
protected object DeserializeContentType(Type operationType, IHttpRequest httpReq, string contentType)
{
var httpMethod = httpReq.HttpMethod;
var queryString = httpReq.QueryString;
if (httpMethod == HttpMethods.Get || httpMethod == HttpMethods.Delete || httpMethod == HttpMethods.Options)
{
try
{
return KeyValueDataContractDeserializer.Instance.Parse(queryString, operationType);
}
catch (Exception ex)
{
var msg = "Could not deserialize '{0}' request using KeyValueDataContractDeserializer: '{1}'.\nError: '{2}'"
.Fmt(operationType, queryString, ex);
throw new SerializationException(msg);
}
}
var isFormData = httpReq.HasAnyOfContentTypes(ContentType.FormUrlEncoded, ContentType.MultiPartFormData);
if (isFormData)
{
try
{
return KeyValueDataContractDeserializer.Instance.Parse(httpReq.FormData, operationType);
}
catch (Exception ex)
{
throw new SerializationException("Error deserializing FormData: " + httpReq.FormData, ex);
}
}
try
{
var deserializer = EndpointHost.AppHost.ContentTypeFilters.GetStreamDeserializer(contentType);
return deserializer(operationType, httpReq.InputStream);
}
catch (Exception ex)
{
var msg = "Could not deserialize '{0}' request using {1}'\nError: {2}"
.Fmt(contentType, operationType, ex);
throw new SerializationException(msg);
}
}
protected static bool DefaultHandledRequest(HttpListenerContext context)
{
if (context.Request.HttpMethod == HttpMethods.Options)
{
foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders)
{
context.Response.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value);
}
return true;
}
return false;
}
protected static bool DefaultHandledRequest(HttpContext context)
{
if (context.Request.HttpMethod == HttpMethods.Options)
{
foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders)
{
context.Response.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value);
}
return true;
}
return false;
}
public virtual void ProcessRequest(HttpContext context)
{
var operationName = this.RequestName ?? context.Request.GetOperationName();
if (string.IsNullOrEmpty(operationName)) return;
if (DefaultHandledRequest(context)) return;
ProcessRequest(
new HttpRequestWrapper(operationName, context.Request),
new HttpResponseWrapper(context.Response),
operationName);
}
public virtual void ProcessRequest(HttpListenerContext context)
{
var operationName = this.RequestName ?? context.Request.GetOperationName();
if (string.IsNullOrEmpty(operationName)) return;
if (DefaultHandledRequest(context)) return;
ProcessRequest(
new HttpListenerRequestWrapper(operationName, context.Request),
new HttpListenerResponseWrapper(context.Response),
operationName);
}
public static ServiceManager ServiceManager { get; set; }
public static Type GetOperationType(string operationName)
{
return ServiceManager != null
? ServiceManager.ServiceOperations.GetOperationType(operationName)
: EndpointHost.ServiceOperations.GetOperationType(operationName);
}
protected static object ExecuteService(object request, EndpointAttributes endpointAttributes,
IHttpRequest httpReq, IHttpResponse httpRes)
{
return EndpointHost.ExecuteService(request, endpointAttributes, httpReq, httpRes);
}
public EndpointAttributes GetEndpointAttributes(System.ServiceModel.OperationContext operationContext)
{
if (!EndpointHost.Config.EnableAccessRestrictions) return default(EndpointAttributes);
var portRestrictions = default(EndpointAttributes);
var ipAddress = GetIpAddress(operationContext);
portRestrictions |= GetIpAddressEndpointAttributes(ipAddress);
//TODO: work out if the request was over a secure channel
//portRestrictions |= request.IsSecureConnection ? PortRestriction.Secure : PortRestriction.InSecure;
return portRestrictions;
}
public static IPAddress GetIpAddress(System.ServiceModel.OperationContext context)
{
#if !MONO
var prop = context.IncomingMessageProperties;
if (context.IncomingMessageProperties.ContainsKey(System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name))
{
var endpoint = prop[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name]
as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
if (endpoint != null)
{
return IPAddress.Parse(endpoint.Address);
}
}
#endif
return null;
}
public EndpointAttributes GetEndpointAttributes(IHttpRequest request)
{
var portRestrictions = EndpointAttributes.None;
portRestrictions |= HttpMethods.GetEndpointAttribute(request.HttpMethod);
portRestrictions |= request.IsSecureConnection ? EndpointAttributes.Secure : EndpointAttributes.InSecure;
if (request.UserHostAddress != null)
{
var isIpv4Address = request.UserHostAddress.IndexOf('.') != -1 &&
request.UserHostAddress.IndexOf("::") == -1;
var pieces = request.UserHostAddress.Split(new char[] {':' },StringSplitOptions.RemoveEmptyEntries);
var ipAddressNumber = isIpv4Address
? pieces[0]
: (pieces.Length == 9 || pieces.Length == 6 || pieces.Length == 4
? request.UserHostAddress.Substring(0, request.UserHostAddress.LastIndexOf(':'))
: request.UserHostAddress);
var ipAddress = IPAddress.Parse(ipAddressNumber);
portRestrictions |= GetIpAddressEndpointAttributes(ipAddress);
}
return portRestrictions;
}
private static EndpointAttributes GetIpAddressEndpointAttributes(IPAddress ipAddress)
{
if (IPAddress.IsLoopback(ipAddress))
return EndpointAttributes.Localhost;
return IsInLocalSubnet(ipAddress)
? EndpointAttributes.LocalSubnet
: EndpointAttributes.External;
}
private static bool IsInLocalSubnet(IPAddress ipAddress)
{
var ipAddressBytes = ipAddress.GetAddressBytes();
switch (ipAddress.AddressFamily)
{
case AddressFamily.InterNetwork:
foreach (var localIpv4AddressAndMask in NetworkInterfaceIpv4Addresses)
{
if (ipAddressBytes.IsInSameIpv4Subnet(localIpv4AddressAndMask.Key, localIpv4AddressAndMask.Value))
{
return true;
}
}
break;
case AddressFamily.InterNetworkV6:
foreach (var localIpv6Address in NetworkInterfaceIpv6Addresses)
{
if (ipAddressBytes.IsInSameIpv6Subnet(localIpv6Address))
{
return true;
}
}
break;
}
return false;
}
protected static void AssertOperationExists(string operationName, Type type)
{
if (type == null)
{
throw new NotImplementedException(
string.Format("The operation '{0}' does not exist for this service", operationName));
}
}
protected void HandleException(string responseContentType, IHttpResponse httpRes, string operationName, Exception ex)
{
var errorMessage = string.Format("Error occured while Processing Request: {0}", ex.Message);
Log.Error(errorMessage, ex);
try
{
var statusCode = ex is SerializationException ? HttpStatusCode.BadRequest : HttpStatusCode.InternalServerError;
//httpRes.WriteToResponse always calls .Close in it's finally statement so
//if there is a problem writing to response, by now it will be closed
if (!httpRes.IsClosed)
{
httpRes.WriteErrorToResponse(responseContentType, operationName, errorMessage, ex, statusCode);
}
}
catch (Exception writeErrorEx)
{
//Exception in writing to response should not hide the original exception
Log.Info("Failed to write error to response: {0}", writeErrorEx);
//rethrow the original exception
throw ex;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing API Operation Policy.
/// </summary>
internal partial class ApiOperationPolicyOperations : IServiceOperations<ApiManagementClient>, IApiOperationPolicyOperations
{
/// <summary>
/// Initializes a new instance of the ApiOperationPolicyOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ApiOperationPolicyOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Deletes specific API operation policy of the Api Management service
/// instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='oid'>
/// Required. Identifier of the API operation.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string aid, string oid, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (aid == null)
{
throw new ArgumentNullException("aid");
}
if (oid == null)
{
throw new ArgumentNullException("oid");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("aid", aid);
tracingParameters.Add("oid", oid);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/apis/";
url = url + Uri.EscapeDataString(aid);
url = url + "/operations/";
url = url + Uri.EscapeDataString(oid);
url = url + "/policy";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets specific API operation policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='oid'>
/// Required. Identifier of the API operation.
/// </param>
/// <param name='format'>
/// Required. Format of the policy. Supported formats:
/// application/vnd.ms-azure-apim.policy+xml
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get policy output operation.
/// </returns>
public async Task<PolicyGetResponse> GetAsync(string resourceGroupName, string serviceName, string aid, string oid, string format, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (aid == null)
{
throw new ArgumentNullException("aid");
}
if (oid == null)
{
throw new ArgumentNullException("oid");
}
if (format == null)
{
throw new ArgumentNullException("format");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("aid", aid);
tracingParameters.Add("oid", oid);
tracingParameters.Add("format", format);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/apis/";
url = url + Uri.EscapeDataString(aid);
url = url + "/operations/";
url = url + Uri.EscapeDataString(oid);
url = url + "/policy";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", format);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
PolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new PolicyGetResponse();
result.PolicyBytes = Encoding.UTF8.GetBytes(responseContent);
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Sets policy for API operation.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='oid'>
/// Required. Identifier of the API operation.
/// </param>
/// <param name='format'>
/// Required. Format of the policy. Supported formats:
/// application/vnd.ms-azure-apim.policy+xml
/// </param>
/// <param name='policyStream'>
/// Required. Policy stream.
/// </param>
/// <param name='etag'>
/// Optional. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> SetAsync(string resourceGroupName, string serviceName, string aid, string oid, string format, Stream policyStream, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (aid == null)
{
throw new ArgumentNullException("aid");
}
if (oid == null)
{
throw new ArgumentNullException("oid");
}
if (format == null)
{
throw new ArgumentNullException("format");
}
if (policyStream == null)
{
throw new ArgumentNullException("policyStream");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("aid", aid);
tracingParameters.Add("oid", oid);
tracingParameters.Add("format", format);
tracingParameters.Add("policyStream", policyStream);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "SetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/apis/";
url = url + Uri.EscapeDataString(aid);
url = url + "/operations/";
url = url + Uri.EscapeDataString(oid);
url = url + "/policy";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
Stream requestContent = policyStream;
httpRequest.Content = new StreamContent(requestContent);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(format);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using ClousotTests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
public class Options
{
private const string RelativeRoot = @"..\..\..\";
private const string TestHarnessDirectory = @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug";
private static readonly string RootDirectory;
static Options()
{
RootDirectory = Path.GetFullPath(RelativeRoot);
}
private readonly string OutDirectory;
public readonly string SourceFile;
private readonly string compilerCode;
private readonly string compilerOptions;
public string ClousotOptions;
public readonly List<string> LibPaths;
public readonly List<string> References;
public readonly bool UseContractReferenceAssemblies = true;
public string BuildFramework = "v3.5";
public string ContractFramework = "v3.5";
public bool UseBinDir = false;
public bool UseExe = false;
public readonly string TestGroupName;
public bool SkipForCCI2;
public bool SkipSlicing;
public bool GenerateUniqueOutputName = false;
public bool Fast = false;
public string Compiler
{
get
{
switch (compilerCode)
{
case "VB": return "vbc.exe";
default: return "csc.exe";
}
}
}
private bool IsV4 { get { return this.BuildFramework.Contains("v4"); } }
private bool IsV4Contracts { get { return this.ContractFramework.Contains("v4"); } }
private bool IsSilverlight { get { return this.BuildFramework.Contains("Silverlight"); } }
private string Moniker
{
get
{
if (IsSilverlight)
{
if (IsV4)
{
return "SILVERLIGHT_4_0";
}
else
{
return "SILVERLIGHT_3_0";
}
}
else
{
if (IsV4)
{
return "NETFRAMEWORK_4_0";
}
else
{
return "NETFRAMEWORK_3_5";
}
}
}
}
public string ContractMoniker
{
get
{
if (IsSilverlight)
{
if (IsV4Contracts)
{
return "SILVERLIGHT_4_0_CONTRACTS";
}
else
{
return "SILVERLIGHT_3_0_CONTRACTS";
}
}
else
{
if (IsV4Contracts)
{
return "NETFRAMEWORK_4_0_CONTRACTS";
}
else
{
return "NETFRAMEWORK_3_5_CONTRACTS";
}
}
}
}
private string DefaultCompilerOptions
{
get
{
switch (compilerCode)
{
case "VB":
return String.Format("/noconfig /nostdlib /define:\"DEBUG=-1,{0},CONTRACTS_FULL\",_MyType=\\\"Console\\\" " +
"/imports:Microsoft.VisualBasic,System,System.Collections,System.Collections.Generic,System.Data,System.Diagnostics,System.Linq,System.Xml.Linq " +
"/optioncompare:Binary /optionexplicit+ /optionstrict:custom /optioninfer+ {1}",
Moniker,
MakeAbsolute(@"Foxtrot\Contracts\ContractExtensions.vb")
);
default:
if (IsV4 && !UseContractReferenceAssemblies)
{
// work around a bug in mscorlib.dll which has warnings when we extract contracts from it
return String.Format("/noconfig /nostdlib /d:CONTRACTS_FULL;DEBUG;{0};{1} {2} {3}", Moniker, ContractMoniker,
MakeAbsolute(@"Microsoft.Research\RegressionTest\ClousotTests\NoWarn.cs"),
MakeAbsolute(@"Foxtrot\Contracts\ContractExtensions.cs")
);
}
else
{
return String.Format("/noconfig /nostdlib /d:CONTRACTS_FULL;DEBUG;{0};{1} {2}", Moniker, ContractMoniker,
MakeAbsolute(@"Foxtrot\Contracts\ContractExtensions.cs")
);
}
}
}
}
public string CompilerOptions(List<string> resolvedRefs)
{
if (compilerCode == "VB")
{
string mscorlib = null;
foreach (var p in resolvedRefs)
{
if (p.EndsWith("mscorlib.dll")) { mscorlib = Path.GetDirectoryName(p); break; }
}
if (mscorlib != null)
{
return String.Format("/sdkpath:\"{0}\" ", mscorlib) + DefaultCompilerOptions + " " + compilerOptions;
}
}
return DefaultCompilerOptions + " " + compilerOptions;
}
private static Dictionary<string, GroupInfo> groupInfo = new Dictionary<string, GroupInfo>();
private int instance;
public int Instance { get { return instance; } }
public readonly GroupInfo Group;
public Options(string testGroupName, TestContext context)
{
var dataRow = context.DataRow;
OutDirectory = context.TestDeploymentDir;
this.TestGroupName = testGroupName;
this.Group = GetTestGroup(testGroupName, RootDirectory, out instance);
this.SourceFile = LoadString(dataRow, "Name");
this.ClousotOptions = LoadString(dataRow, "Options");
this.UseContractReferenceAssemblies = LoadBool(dataRow, "ContractReferenceAssemblies", false);
this.UseExe = LoadBool(dataRow, "Exe", false);
compilerOptions = LoadString(dataRow, "CompilerOptions");
this.References = LoadList(dataRow, "References", "mscorlib.dll", "System.dll", "ClousotTestHarness.dll");
this.LibPaths = LoadList(dataRow, "LibPaths", MakeAbsolute(TestHarnessDirectory));
compilerCode = LoadString(dataRow, "Compiler", "CS");
this.SkipForCCI2 = LoadBool(dataRow, "SkipCCI2", false);
this.SkipSlicing = LoadBool(dataRow, "SkipSlicing", false);
}
private GroupInfo GetTestGroup(string testGroupName, string rootDir, out int instance)
{
if (testGroupName == null)
{
instance = 0;
return new GroupInfo(null, rootDir);
}
GroupInfo result;
if (groupInfo.TryGetValue(testGroupName, out result))
{
result.Increment(out instance);
return result;
}
instance = 0;
result = new GroupInfo(testGroupName, rootDir);
groupInfo.Add(testGroupName, result);
return result;
}
private static string LoadString(System.Data.DataRow dataRow, string name, string defaultValue = "")
{
if (!ColumnExists(dataRow, name))
return defaultValue;
var result = dataRow[name] as string;
if (String.IsNullOrEmpty(result))
return defaultValue;
return result;
}
private static List<string> LoadList(System.Data.DataRow dataRow, string name, params string[] initial)
{
if (!ColumnExists(dataRow, name)) return new List<string>();
string listdata = dataRow[name] as string;
var result = new List<string>(initial);
if (!string.IsNullOrEmpty(listdata))
{
result.AddRange(listdata.Split(';'));
}
return result;
}
private static bool ColumnExists(System.Data.DataRow dataRow, string name)
{
return dataRow.Table.Columns.IndexOf(name) >= 0;
}
private static bool LoadBool(System.Data.DataRow dataRow, string name, bool defaultValue)
{
if (!ColumnExists(dataRow, name)) return defaultValue;
var booloption = dataRow[name] as string;
if (!string.IsNullOrEmpty(booloption))
{
bool result;
if (bool.TryParse(booloption, out result))
{
return result;
}
}
return defaultValue;
}
/// <summary>
/// Not only makes the exe absolute but also tries to find it in the deployment dir to make code coverage work.
/// </summary>
public string GetFullExecutablePath(string relativePath)
{
var deployed = Path.Combine(OutDirectory, Path.GetFileName(relativePath));
if (File.Exists(deployed))
{
return deployed;
}
return MakeAbsolute(relativePath);
}
public string MakeAbsolute(string relativeToRoot)
{
return Path.Combine(RootDirectory, relativeToRoot); // MB: do not need Path.GetFullPath because RootDirectory is already an absolute path
}
public string TestName
{
get
{
var instance = this.Instance;
if (SourceFile != null) { return Path.GetFileNameWithoutExtension(SourceFile) + "_" + instance; }
else return instance.ToString();
}
}
public int TestInstance { get { return this.Instance; } }
public bool Skip
{
get
{
if (!System.Diagnostics.Debugger.IsAttached) return false;
// use only the previously failed file indices
return !Group.Selected;
}
}
public object Framework
{
get
{
if (this.BuildFramework.EndsWith("v3.5"))
{
return "v3.5";
}
if (this.BuildFramework.EndsWith("v4.0"))
{
return "v4.0";
}
if (this.BuildFramework.EndsWith("v4.5"))
{
return "v4.5";
}
else
{
return "none";
}
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using ThinMvvm.Applications.Infrastructure;
using ThinMvvm.DependencyInjection.Infrastructure;
using ThinMvvm.Infrastructure;
using ThinMvvm.Windows.Infrastructure;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// Bugs and quirks of Windows.UI.Xaml.Controls.Frame:
//
// - There is no way to obtain the current PageStackEntry, only the ones in the back/forward stacks.
// Thus it's impossible to directly re-inflate the current ViewModel when restoring the frame's state.
// Workaround: Navigate to a fake page, get the "previous" entry after navigation, then navigate back.
//
// - There is no way to reset it; even with its contents removed, navigation will add an entry to the back stack.
// Workaround: Mark the current view as transient when resetting the service.
//
// - Navigations cannot occur during a Navigated event.
// Workaround: Call Task.Yield() in an async void method, to ensure navigation is on a different thread. Yikes!
//
// - There is no way to disable the forward stack.
// Workaround: Manually clear it after every backwards navigation.
//
// - Pages in the forward stack remain cached (if caching is enabled), even when the forward stack is cleared.
// In other words, going A -> B -> back -> B will use the same instance of B, causing flickering.
// Workaround: Manually set the navigation cache mode to Disabled before navigating back.
//
// - If a navigation arg contains the null character ('\0'), the navigation state truncates the string.
// Not only does this cause data loss, but also weird behavior on the rest of the state.
// Workaround: Always serialize/deserialize strings when passing them as parameters.
// This has obvious perf implications, but also ensures that any other bug like this is worked around;
// attempting to detect null chars and serialize in that case would not provide such a guarantee.
//
// - The page cache is used even for forwards navigation, using pages from the back stack.
// For instance, going A -> B -> A will use the same instance of A twice.
// Workaround: Make sure forwards navigation don't try to use existing ViewModels.
namespace ThinMvvm.Windows
{
/// <summary>
/// <see cref="INavigationService" /> implementation for Windows.
/// </summary>
/// <remarks>
/// This class assumes it has complete ownership of the provided frame,
/// i.e. that nobody else will call any methods on it.
/// </remarks>
public sealed class WindowsNavigationService : NavigationServiceBase<Page, string>
{
// Sentinel for the state-restoring fake navigation hacks
private static readonly object NavigationParameterSentinel = new object();
// Stores the parameter of the current ViewModel in the state-restoring fake navigation hacks
private object _restoredParameter = NavigationParameterSentinel;
private readonly Frame _frame;
/// <summary>
/// Gets the current depth of the service's back stack.
/// </summary>
protected override int BackStackDepth
{
get { return _frame.BackStackDepth; }
}
/// <summary>
/// Gets the currently displayed view.
/// </summary>
protected override Page CurrentView
{
get { return (Page) _frame.Content; }
}
/// <summary>
/// Initializes a new instance of the <see cref="WindowsNavigationService" /> class
/// with the specified ViewModel creator, views, and navigation frame.
/// </summary>
/// <param name="viewModelCreator">The ViewModel creator.</param>
/// <param name="views">The views.</param>
/// <param name="savedStateExpirationTime">The expiration time of saved states.</param>
/// <param name="frame">The navigation frame.</param>
public WindowsNavigationService( ObjectCreator viewModelCreator, ViewRegistry views,
TimeSpan savedStateExpirationTime, Frame frame )
: base( viewModelCreator, views, savedStateExpirationTime )
{
_frame = frame;
_frame.Navigating += FrameNavigating;
_frame.Navigated += FrameNavigated;
Application.Current.Suspending += ( _, __ ) => StoreState();
SystemNavigationManager.GetForCurrentView().BackRequested += ( _, e ) =>
{
NavigateBack();
e.Handled = true;
};
}
/// <summary>
/// Navigates to the specified view, with the specified argument.
/// </summary>
protected override void NavigateTo<TArg>( Type viewType, TArg arg )
{
var convertedArg = ConvertArgument( arg );
_frame.Navigate( viewType, convertedArg );
}
/// <summary>
/// Navigates back to the previous ViewModel.
/// </summary>
public override async void NavigateBack()
{
if( CanNavigateBack )
{
( (Page) _frame.Content ).NavigationCacheMode = NavigationCacheMode.Disabled;
// HACK: Because of the popbackstack hack, need to do this here to allow popbackstack during onnavigatedfrom
await BeginNavigationAsync( NavigationKind.Backwards );
_frame.GoBack();
_frame.ForwardStack.Clear();
}
else
{
Application.Current.Exit();
}
}
/// <summary>
/// Resets the service, as if no navigation had occurred.
/// </summary>
public override void Reset()
{
_frame.BackStack.Clear();
_frame.Content = null;
IsCurrentViewTransient = true;
}
/// <summary>
/// Pops the last entry out of the service's back stack.
/// </summary>
protected override void PopBackStack()
{
_frame.BackStack.RemoveAt( _frame.BackStack.Count - 1 );
}
/// <summary>
/// Gets the current navigation state.
/// </summary>
protected override string GetNavigationState()
{
return _frame.GetNavigationState();
}
/// <summary>
/// Sets the current navigation state, which may trigger a navigation.
/// </summary>
protected override void SetNavigationState( string state )
{
_frame.SetNavigationState( state );
_frame.Navigate( typeof( Page ), NavigationParameterSentinel );
}
/// <summary>
/// Gets the ViewModel of the specified View.
/// </summary>
protected override IViewModel GetViewModel( Page view )
{
return (IViewModel) view.DataContext;
}
/// <summary>
/// Sets the ViewModel of the specified view.
/// </summary>
protected override void SetViewModel( Page view, IViewModel viewModel )
{
view.DataContext = viewModel;
}
/// <summary>
/// Gets a state store for the specified name.
/// </summary>
protected override IKeyValueStore GetStateStore( string name )
{
return new WindowsKeyValueStore( "ThinMvvm.Navigation." + name );
}
/// <summary>
/// Called when the frame is navigating.
/// </summary>
private async void FrameNavigating( object sender, NavigatingCancelEventArgs e )
{
if( e.Parameter == NavigationParameterSentinel || _restoredParameter != NavigationParameterSentinel )
{
return;
}
if( e.NavigationMode != NavigationMode.New )
{
// HACK, see GoBack: BeginNavigationAsync already done earlier.
return;
}
await BeginNavigationAsync( NavigationKind.Forwards );
}
/// <summary>
/// Called when the frame has finished navigating.
/// </summary>
private async void FrameNavigated( object sender, NavigationEventArgs e )
{
if( e.Parameter == NavigationParameterSentinel )
{
_restoredParameter = _frame.BackStack[_frame.BackStackDepth - 1].Parameter;
await Task.Yield();
NavigateBack();
return;
}
var navigationKind = e.NavigationMode == NavigationMode.New ? NavigationKind.Forwards : NavigationKind.Backwards;
var arg = e.Parameter;
if( _restoredParameter != NavigationParameterSentinel )
{
navigationKind = NavigationKind.Restore;
arg = _restoredParameter;
_restoredParameter = NavigationParameterSentinel;
}
var argType = GetParameterType( CurrentView.GetType() );
arg = ConvertBackArgument( arg, argType );
await EndNavigationAsync( navigationKind, arg );
}
/// <summary>
/// Converts the specified argument to an object serializable in the Frame's navigation state.
/// </summary>
private object ConvertArgument<TArg>( TArg arg )
{
if( arg == null )
{
return arg;
}
if( typeof( TArg ) != typeof( string ) && WindowsSerializer.IsTypeNativelySupported( typeof( TArg ) ) )
{
return arg;
}
return WindowsSerializer.Serialize( arg );
}
/// <summary>
/// Converts the specified argument back to the specified type.
/// </summary>
private object ConvertBackArgument( object arg, Type targetType )
{
if( arg == null )
{
return arg;
}
if( targetType != typeof( string ) && WindowsSerializer.IsTypeNativelySupported( targetType ) )
{
return arg;
}
return WindowsSerializer.Deserialize( targetType, (string) arg );
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Kiko.Web.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);
}
}
}
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Daniel Grunwald" email="[email protected]"/>
// <version>$Revision: 3644 $</version>
// </file>
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Xml;
namespace ICSharpCode.SharpDevelop.Dom
{
/// <summary>
/// Contains project contents read from external assemblies.
/// Caches loaded assemblies in memory and optionally also to disk.
/// </summary>
public class ProjectContentRegistry : IDisposable
{
internal DomPersistence persistence;
Dictionary<string, IProjectContent> contents = new Dictionary<string, IProjectContent>(StringComparer.InvariantCultureIgnoreCase);
/// <summary>
/// Disposes all project contents stored in this registry.
/// </summary>
public virtual void Dispose()
{
List<IProjectContent> list;
lock (contents) {
list = new List<IProjectContent>(contents.Values);
contents.Clear();
}
// dispose outside the lock
foreach (IProjectContent pc in list) {
pc.Dispose();
}
}
/// <summary>
/// Activate caching assemblies to disk.
/// Cache files will be saved in the specified directory.
/// </summary>
public DomPersistence ActivatePersistence(string cacheDirectory)
{
if (cacheDirectory == null) {
throw new ArgumentNullException("cacheDirectory");
} else if (persistence != null && cacheDirectory == persistence.CacheDirectory) {
return persistence;
} else {
persistence = new DomPersistence(cacheDirectory, this);
return persistence;
}
}
ReflectionProjectContent mscorlibContent;
/// <summary>
/// Runs the method inside the lock of the registry.
/// Use this method if you want to call multiple methods on the ProjectContentRegistry and ensure
/// that no other thread accesses the registry while your method runs.
/// </summary>
public void RunLocked(ThreadStart method)
{
lock (contents) {
method();
}
}
public virtual IProjectContent Mscorlib {
get {
if (mscorlibContent != null) return mscorlibContent;
lock (contents) {
if (contents.ContainsKey("mscorlib")) {
mscorlibContent = (ReflectionProjectContent)contents["mscorlib"];
return contents["mscorlib"];
}
int time = LoggingService.IsDebugEnabled ? Environment.TickCount : 0;
LoggingService.Debug("Loading PC for mscorlib...");
if (persistence != null) {
mscorlibContent = persistence.LoadProjectContentByAssemblyName(MscorlibAssembly.FullName);
if (mscorlibContent != null) {
if (time != 0) {
LoggingService.Debug("Loaded mscorlib from cache in " + (Environment.TickCount - time) + " ms");
}
}
}
if (mscorlibContent == null) {
// We're using Cecil now for everything to find bugs in CecilReader faster
//mscorlibContent = CecilReader.LoadAssembly(MscorlibAssembly.Location, this);
// After SD 2.1 Beta 2, we're back to Reflection
mscorlibContent = new ReflectionProjectContent(MscorlibAssembly, this);
if (time != 0) {
//LoggingService.Debug("Loaded mscorlib with Cecil in " + (Environment.TickCount - time) + " ms");
LoggingService.Debug("Loaded mscorlib with Reflection in " + (Environment.TickCount - time) + " ms");
}
if (persistence != null) {
persistence.SaveProjectContent(mscorlibContent);
LoggingService.Debug("Saved mscorlib to cache");
}
}
contents["mscorlib"] = mscorlibContent;
contents[mscorlibContent.AssemblyFullName] = mscorlibContent;
contents[mscorlibContent.AssemblyLocation] = mscorlibContent;
return mscorlibContent;
}
}
}
public virtual ICollection<IProjectContent> GetLoadedProjectContents()
{
lock (contents) { // we need to return a copy because we have to lock
return new List<IProjectContent>(contents.Values);
}
}
/// <summary>
/// Unloads the specified project content, causing it to be reloaded when
/// GetProjectContentForReference is called the next time.
/// Warning: do not unload project contents that are still in use! Doing so will result
/// in an ObjectDisposedException when the unloaded project content is used the next time!
/// </summary>
public void UnloadProjectContent(IProjectContent pc)
{
if (pc == null)
throw new ArgumentNullException("pc");
LoggingService.Debug("ProjectContentRegistry.UnloadProjectContent: " + pc);
lock (contents) {
// find all keys used for the project content - might be the short name/full name/file name
List<string> keys = new List<string>();
foreach (KeyValuePair<string, IProjectContent> pair in contents) {
if (pair.Value == pc) keys.Add(pair.Key);
}
foreach (string key in keys) {
contents.Remove(key);
}
}
pc.Dispose();
}
public IProjectContent GetExistingProjectContent(DomAssemblyName assembly)
{
return GetExistingProjectContent(assembly.FullName);
}
public virtual IProjectContent GetExistingProjectContent(string fileNameOrAssemblyName)
{
lock (contents) {
if (contents.ContainsKey(fileNameOrAssemblyName)) {
return contents[fileNameOrAssemblyName];
}
}
// GetProjectContentForReference supports redirecting .NET base assemblies to the correct version,
// so GetExistingProjectContent must support it, too (otherwise assembly interdependencies fail
// to resolve correctly when a .NET 1.0 assembly is used in a .NET 2.0 project)
int pos = fileNameOrAssemblyName.IndexOf(',');
if (pos > 0) {
string shortName = fileNameOrAssemblyName.Substring(0, pos);
Assembly assembly = GetDefaultAssembly(shortName);
if (assembly != null) {
lock (contents) {
if (contents.ContainsKey(assembly.FullName)) {
return contents[assembly.FullName];
}
}
}
}
return null;
}
public virtual IProjectContent GetProjectContentForReference(string itemInclude, string itemFileName)
{
lock (contents) {
IProjectContent pc = GetExistingProjectContent(itemFileName);
if (pc != null) {
return pc;
}
LoggingService.Debug("Loading PC for " + itemInclude);
string shortName = itemInclude;
int pos = shortName.IndexOf(',');
if (pos > 0)
shortName = shortName.Substring(0, pos);
#if DEBUG
int time = Environment.TickCount;
#endif
try {
pc = LoadProjectContent(itemInclude, itemFileName);
} catch (Exception ex) {
HostCallback.ShowAssemblyLoadErrorInternal(itemFileName, itemInclude, "Error loading assembly:\n" + ex.ToString());
} finally {
#if DEBUG
LoggingService.Debug(string.Format("Loaded {0} in {1}ms", itemInclude, Environment.TickCount - time));
#endif
}
if (pc != null) {
ReflectionProjectContent reflectionProjectContent = pc as ReflectionProjectContent;
if (reflectionProjectContent != null) {
reflectionProjectContent.InitializeReferences();
if (reflectionProjectContent.AssemblyFullName != null) {
contents[reflectionProjectContent.AssemblyFullName] = pc;
}
}
contents[itemInclude] = pc;
contents[itemFileName] = pc;
}
return pc;
}
}
protected virtual IProjectContent LoadProjectContent(string itemInclude, string itemFileName)
{
string shortName = itemInclude;
int pos = shortName.IndexOf(',');
if (pos > 0)
shortName = shortName.Substring(0, pos);
Assembly assembly = GetDefaultAssembly(shortName);
ReflectionProjectContent pc = null;
if (assembly != null) {
if (persistence != null) {
pc = persistence.LoadProjectContentByAssemblyName(assembly.FullName);
}
if (pc == null) {
pc = new ReflectionProjectContent(assembly, this);
if (persistence != null) {
persistence.SaveProjectContent(pc);
}
}
} else {
// find real file name for cecil:
if (File.Exists(itemFileName)) {
if (persistence != null) {
pc = persistence.LoadProjectContentByAssemblyName(itemFileName);
}
if (pc == null) {
pc = CecilReader.LoadAssembly(itemFileName, this);
if (persistence != null) {
persistence.SaveProjectContent(pc);
}
}
} else {
DomAssemblyName asmName = GacInterop.FindBestMatchingAssemblyName(itemInclude);
if (persistence != null && asmName != null) {
//LoggingService.Debug("Looking up in DOM cache: " + asmName.FullName);
pc = persistence.LoadProjectContentByAssemblyName(asmName.FullName);
}
if (pc == null && asmName != null) {
string subPath = Path.Combine(asmName.ShortName, GetVersion__Token(asmName));
subPath = Path.Combine(subPath, asmName.ShortName + ".dll");
foreach (string dir in Directory.GetDirectories(GacInterop.GacRootPath, "GAC*")) {
itemFileName = Path.Combine(dir, subPath);
if (File.Exists(itemFileName)) {
pc = CecilReader.LoadAssembly(itemFileName, this);
if (persistence != null) {
persistence.SaveProjectContent(pc);
}
break;
}
}
}
if (pc == null) {
HostCallback.ShowAssemblyLoadErrorInternal(itemFileName, itemInclude, "Could not find assembly file.");
}
}
}
return pc;
}
static string GetVersion__Token(DomAssemblyName asmName)
{
StringBuilder b = new StringBuilder(asmName.Version.ToString());
b.Append("__");
b.Append(asmName.PublicKeyToken);
return b.ToString();
}
public static Assembly MscorlibAssembly {
get {
return typeof(object).Assembly;
}
}
public static Assembly SystemAssembly {
get {
return typeof(Uri).Assembly;
}
}
protected virtual Assembly GetDefaultAssembly(string shortName)
{
// These assemblies are already loaded by SharpDevelop, so we
// don't need to load them in a separate AppDomain/with Cecil.
switch (shortName) {
case "mscorlib":
return MscorlibAssembly;
case "System": // System != mscorlib !!!
return SystemAssembly;
case "System.Core":
return typeof(System.Linq.Enumerable).Assembly;
case "System.Xml":
case "System.XML":
return typeof(XmlReader).Assembly;
case "System.Data":
case "System.Windows.Forms":
case "System.Runtime.Remoting":
return Assembly.Load(shortName + ", Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
case "System.Configuration":
case "System.Design":
case "System.Deployment":
case "System.Drawing":
case "System.Drawing.Design":
case "System.ServiceProcess":
case "System.Security":
case "System.Management":
case "System.Messaging":
case "System.Web":
case "System.Web.Services":
return Assembly.Load(shortName + ", Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
case "Microsoft.VisualBasic":
return Assembly.Load("Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
default:
return null;
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Globalization;
using System.Text;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
namespace System.Management.Automation.Help
{
/// <summary>
/// Positional parameter comparer
/// </summary>
internal class PositionalParameterComparer : IComparer
{
/// <summary>
///
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(object x, object y)
{
CommandParameterInfo a = x as CommandParameterInfo;
CommandParameterInfo b = y as CommandParameterInfo;
Debug.Assert(a != null && b != null);
return (a.Position - b.Position);
}
}
/// <summary>
/// The help object builder class attempts to create a full HelpInfo object from
/// a CmdletInfo object. This is used to generate the default UX when no help content
/// is present in the box. This class mimics the exact same structure as that of a MAML
/// node, so that the default UX does not introduce regressions.
/// </summary>
internal class DefaultCommandHelpObjectBuilder
{
internal static string TypeNameForDefaultHelp = "ExtendedCmdletHelpInfo";
/// <summary>
/// Generates a HelpInfo PSObject from a CmdletInfo object
/// </summary>
/// <param name="input">command info</param>
/// <returns>HelpInfo PSObject</returns>
internal static PSObject GetPSObjectFromCmdletInfo(CommandInfo input)
{
// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
// sets based on Dynamic Parameters (+ optional arguments)
CommandInfo commandInfo = input.CreateGetCommandCopy(null);
PSObject obj = new PSObject();
obj.TypeNames.Clear();
obj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#{1}#command", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName));
obj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#{1}", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName));
obj.TypeNames.Add(DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp);
obj.TypeNames.Add("CmdletHelpInfo");
obj.TypeNames.Add("HelpInfo");
if (commandInfo is CmdletInfo)
{
CmdletInfo cmdletInfo = commandInfo as CmdletInfo;
bool common = false;
bool commonWorkflow = false;
if (cmdletInfo.Parameters != null)
{
common = HasCommonParameters(cmdletInfo.Parameters);
commonWorkflow = ((cmdletInfo.CommandType & CommandTypes.Workflow) == CommandTypes.Workflow);
}
obj.Properties.Add(new PSNoteProperty("CommonParameters", common));
obj.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow));
AddDetailsProperties(obj, cmdletInfo.Name, cmdletInfo.Noun, cmdletInfo.Verb, TypeNameForDefaultHelp);
AddSyntaxProperties(obj, cmdletInfo.Name, cmdletInfo.ParameterSets, common, commonWorkflow, TypeNameForDefaultHelp);
AddParametersProperties(obj, cmdletInfo.Parameters, common, commonWorkflow, TypeNameForDefaultHelp);
AddInputTypesProperties(obj, cmdletInfo.Parameters);
AddRelatedLinksProperties(obj, commandInfo.CommandMetadata.HelpUri);
try
{
AddOutputTypesProperties(obj, cmdletInfo.OutputType);
}
catch (PSInvalidOperationException)
{
AddOutputTypesProperties(obj, new ReadOnlyCollection<PSTypeName>(new List<PSTypeName>()));
}
AddAliasesProperties(obj, cmdletInfo.Name, cmdletInfo.Context);
if (HasHelpInfoUri(cmdletInfo.Module, cmdletInfo.ModuleName))
{
AddRemarksProperties(obj, cmdletInfo.Name, cmdletInfo.CommandMetadata.HelpUri);
}
else
{
obj.Properties.Add(new PSNoteProperty("remarks", HelpDisplayStrings.None));
}
obj.Properties.Add(new PSNoteProperty("PSSnapIn", cmdletInfo.PSSnapIn));
}
else if (commandInfo is FunctionInfo)
{
FunctionInfo funcInfo = commandInfo as FunctionInfo;
bool common = HasCommonParameters(funcInfo.Parameters);
bool commonWorkflow = ((commandInfo.CommandType & CommandTypes.Workflow) == CommandTypes.Workflow);
obj.Properties.Add(new PSNoteProperty("CommonParameters", common));
obj.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow));
AddDetailsProperties(obj, funcInfo.Name, String.Empty, String.Empty, TypeNameForDefaultHelp);
AddSyntaxProperties(obj, funcInfo.Name, funcInfo.ParameterSets, common, commonWorkflow, TypeNameForDefaultHelp);
AddParametersProperties(obj, funcInfo.Parameters, common, commonWorkflow, TypeNameForDefaultHelp);
AddInputTypesProperties(obj, funcInfo.Parameters);
AddRelatedLinksProperties(obj, funcInfo.CommandMetadata.HelpUri);
try
{
AddOutputTypesProperties(obj, funcInfo.OutputType);
}
catch (PSInvalidOperationException)
{
AddOutputTypesProperties(obj, new ReadOnlyCollection<PSTypeName>(new List<PSTypeName>()));
}
AddAliasesProperties(obj, funcInfo.Name, funcInfo.Context);
if (HasHelpInfoUri(funcInfo.Module, funcInfo.ModuleName))
{
AddRemarksProperties(obj, funcInfo.Name, funcInfo.CommandMetadata.HelpUri);
}
else
{
obj.Properties.Add(new PSNoteProperty("remarks", HelpDisplayStrings.None));
}
}
obj.Properties.Add(new PSNoteProperty("alertSet", null));
obj.Properties.Add(new PSNoteProperty("description", null));
obj.Properties.Add(new PSNoteProperty("examples", null));
obj.Properties.Add(new PSNoteProperty("Synopsis", commandInfo.Syntax));
obj.Properties.Add(new PSNoteProperty("ModuleName", commandInfo.ModuleName));
obj.Properties.Add(new PSNoteProperty("nonTerminatingErrors", String.Empty));
obj.Properties.Add(new PSNoteProperty("xmlns:command", "http://schemas.microsoft.com/maml/dev/command/2004/10"));
obj.Properties.Add(new PSNoteProperty("xmlns:dev", "http://schemas.microsoft.com/maml/dev/2004/10"));
obj.Properties.Add(new PSNoteProperty("xmlns:maml", "http://schemas.microsoft.com/maml/2004/10"));
return obj;
}
/// <summary>
/// Adds the details properties
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="name">command name</param>
/// <param name="noun">command noun</param>
/// <param name="verb">command verb</param>
/// <param name="typeNameForHelp">type name for help</param>
/// <param name="synopsis">synopsis</param>
internal static void AddDetailsProperties(PSObject obj, string name, string noun, string verb, string typeNameForHelp,
string synopsis = null)
{
PSObject mshObject = new PSObject();
mshObject.TypeNames.Clear();
mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#details", typeNameForHelp));
mshObject.Properties.Add(new PSNoteProperty("name", name));
mshObject.Properties.Add(new PSNoteProperty("noun", noun));
mshObject.Properties.Add(new PSNoteProperty("verb", verb));
// add synopsis
if (!string.IsNullOrEmpty(synopsis))
{
PSObject descriptionObject = new PSObject();
descriptionObject.TypeNames.Clear();
descriptionObject.TypeNames.Add("MamlParaTextItem");
descriptionObject.Properties.Add(new PSNoteProperty("Text", synopsis));
mshObject.Properties.Add(new PSNoteProperty("Description", descriptionObject));
}
obj.Properties.Add(new PSNoteProperty("details", mshObject));
}
/// <summary>
/// Adds the syntax properties
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="cmdletName">command name</param>
/// <param name="parameterSets">parameter sets</param>
/// <param name="common">common parameters</param>
/// <param name="commonWorkflow">common workflow parameters</param>
/// <param name="typeNameForHelp">type name for help</param>
internal static void AddSyntaxProperties(PSObject obj, string cmdletName, ReadOnlyCollection<CommandParameterSetInfo> parameterSets, bool common, bool commonWorkflow, string typeNameForHelp)
{
PSObject mshObject = new PSObject();
mshObject.TypeNames.Clear();
mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#syntax", typeNameForHelp));
AddSyntaxItemProperties(mshObject, cmdletName, parameterSets, common, commonWorkflow, typeNameForHelp);
obj.Properties.Add(new PSNoteProperty("Syntax", mshObject));
}
/// <summary>
/// Add the syntax item properties
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="cmdletName">cmdlet name, you can't get this from parameterSets</param>
/// <param name="parameterSets">a collection of parameter sets</param>
/// <param name="common">common parameters</param>
/// <param name="commonWorkflow">common workflow parameters</param>
/// <param name="typeNameForHelp">type name for help</param>
private static void AddSyntaxItemProperties(PSObject obj, string cmdletName, ReadOnlyCollection<CommandParameterSetInfo> parameterSets, bool common, bool commonWorkflow, string typeNameForHelp)
{
ArrayList mshObjects = new ArrayList();
foreach (CommandParameterSetInfo parameterSet in parameterSets)
{
PSObject mshObject = new PSObject();
mshObject.TypeNames.Clear();
mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#syntaxItem", typeNameForHelp));
mshObject.Properties.Add(new PSNoteProperty("name", cmdletName));
mshObject.Properties.Add(new PSNoteProperty("CommonParameters", common));
mshObject.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow));
Collection<CommandParameterInfo> parameters = new Collection<CommandParameterInfo>();
// GenerateParameters parameters in display order
// ie., Positional followed by
// Named Mandatory (in alpha numeric) followed by
// Named (in alpha numeric)
parameterSet.GenerateParametersInDisplayOrder(commonWorkflow,
parameters.Add,
delegate { });
AddSyntaxParametersProperties(mshObject, parameters, common, commonWorkflow, parameterSet.Name);
mshObjects.Add(mshObject);
}
obj.Properties.Add(new PSNoteProperty("syntaxItem", mshObjects.ToArray()));
}
/// <summary>
/// Add the syntax parameters properties (these parameters are used to create the syntax section)
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="parameters">
/// a collection of parameters in display order
/// ie., Positional followed by
/// Named Mandatory (in alpha numeric) followed by
/// Named (in alpha numeric)
/// </param>
/// <param name="common">common parameters</param>
/// <param name="commonWorkflow">common workflow</param>
/// <param name="parameterSetName">Name of the parameter set for which the syntax is generated</param>
private static void AddSyntaxParametersProperties(PSObject obj, IEnumerable<CommandParameterInfo> parameters,
bool common, bool commonWorkflow, string parameterSetName)
{
ArrayList mshObjects = new ArrayList();
foreach (CommandParameterInfo parameter in parameters)
{
if (commonWorkflow && IsCommonWorkflowParameter(parameter.Name))
{
continue;
}
if (common && Cmdlet.CommonParameters.Contains(parameter.Name))
{
continue;
}
PSObject mshObject = new PSObject();
mshObject.TypeNames.Clear();
mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameter", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
Collection<Attribute> attributes = new Collection<Attribute>(parameter.Attributes);
AddParameterProperties(mshObject, parameter.Name, new Collection<string>(parameter.Aliases),
parameter.IsDynamic, parameter.ParameterType, attributes, parameterSetName);
Collection<ValidateSetAttribute> validateSet = GetValidateSetAttribute(attributes);
List<string> names = new List<string>();
foreach (ValidateSetAttribute set in validateSet)
{
foreach (string value in set.ValidValues)
{
names.Add(value);
}
}
if (names.Count != 0)
{
AddParameterValueGroupProperties(mshObject, names.ToArray());
}
else
{
if (parameter.ParameterType.GetTypeInfo().IsEnum && (Enum.GetNames(parameter.ParameterType) != null))
{
AddParameterValueGroupProperties(mshObject, Enum.GetNames(parameter.ParameterType));
}
else if (parameter.ParameterType.IsArray)
{
if (parameter.ParameterType.GetElementType().GetTypeInfo().IsEnum &&
Enum.GetNames(parameter.ParameterType.GetElementType()) != null)
{
AddParameterValueGroupProperties(mshObject, Enum.GetNames(parameter.ParameterType.GetElementType()));
}
}
else if (parameter.ParameterType.GetTypeInfo().IsGenericType)
{
Type[] types = parameter.ParameterType.GetGenericArguments();
if (types.Length != 0)
{
Type type = types[0];
if (type.GetTypeInfo().IsEnum && (Enum.GetNames(type) != null))
{
AddParameterValueGroupProperties(mshObject, Enum.GetNames(type));
}
else if (type.IsArray)
{
if (type.GetElementType().GetTypeInfo().IsEnum &&
Enum.GetNames(type.GetElementType()) != null)
{
AddParameterValueGroupProperties(mshObject, Enum.GetNames(type.GetElementType()));
}
}
}
}
}
mshObjects.Add(mshObject);
}
obj.Properties.Add(new PSNoteProperty("parameter", mshObjects.ToArray()));
}
/// <summary>
/// Adds a parameter value group (for enums)
/// </summary>
/// <param name="obj">object</param>
/// <param name="values">parameter group values</param>
private static void AddParameterValueGroupProperties(PSObject obj, string[] values)
{
PSObject paramValueGroup = new PSObject();
paramValueGroup.TypeNames.Clear();
paramValueGroup.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameterValueGroup", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
ArrayList paramValue = new ArrayList(values);
paramValueGroup.Properties.Add(new PSNoteProperty("parameterValue", paramValue.ToArray()));
obj.Properties.Add(new PSNoteProperty("parameterValueGroup", paramValueGroup));
}
/// <summary>
/// Add the parameters properties (these parameters are used to create the parameters section)
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="parameters">parameters</param>
/// <param name="common">common parameters</param>
/// <param name="commonWorkflow">common workflow parameters</param>
/// <param name="typeNameForHelp">type name for help</param>
internal static void AddParametersProperties(PSObject obj, Dictionary<string, ParameterMetadata> parameters, bool common, bool commonWorkflow, string typeNameForHelp)
{
PSObject paramsObject = new PSObject();
paramsObject.TypeNames.Clear();
paramsObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameters", typeNameForHelp));
ArrayList paramObjects = new ArrayList();
ArrayList sortedParameters = new ArrayList();
if (parameters != null)
{
foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters)
{
sortedParameters.Add(parameter.Key);
}
}
sortedParameters.Sort(StringComparer.Ordinal);
foreach (string parameter in sortedParameters)
{
if (commonWorkflow && IsCommonWorkflowParameter(parameter))
{
continue;
}
if (common && Cmdlet.CommonParameters.Contains(parameter))
{
continue;
}
PSObject paramObject = new PSObject();
paramObject.TypeNames.Clear();
paramObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameter", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
AddParameterProperties(paramObject, parameter, parameters[parameter].Aliases,
parameters[parameter].IsDynamic, parameters[parameter].ParameterType, parameters[parameter].Attributes);
paramObjects.Add(paramObject);
}
paramsObject.Properties.Add(new PSNoteProperty("parameter", paramObjects.ToArray()));
obj.Properties.Add(new PSNoteProperty("parameters", paramsObject));
}
/// <summary>
/// Adds the parameter properties
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="name">parameter name</param>
/// <param name="aliases">parameter aliases</param>
/// <param name="dynamic">is dynamic parameter?</param>
/// <param name="type">parameter type</param>
/// <param name="attributes">parameter attributes</param>
/// <param name="parameterSetName">Name of the parameter set for which the syntax is generated</param>
private static void AddParameterProperties(PSObject obj, string name, Collection<string> aliases, bool dynamic,
Type type, Collection<Attribute> attributes, string parameterSetName = null)
{
Collection<ParameterAttribute> attribs = GetParameterAttribute(attributes);
obj.Properties.Add(new PSNoteProperty("name", name));
if (attribs.Count == 0)
{
obj.Properties.Add(new PSNoteProperty("required", ""));
obj.Properties.Add(new PSNoteProperty("pipelineInput", ""));
obj.Properties.Add(new PSNoteProperty("isDynamic", ""));
obj.Properties.Add(new PSNoteProperty("parameterSetName", ""));
obj.Properties.Add(new PSNoteProperty("description", ""));
obj.Properties.Add(new PSNoteProperty("position", ""));
obj.Properties.Add(new PSNoteProperty("aliases", ""));
}
else
{
ParameterAttribute paramAttribute = attribs[0];
if (!string.IsNullOrEmpty(parameterSetName))
{
foreach (var attrib in attribs)
{
if (string.Equals(attrib.ParameterSetName, parameterSetName, StringComparison.OrdinalIgnoreCase))
{
paramAttribute = attrib;
break;
}
}
}
obj.Properties.Add(new PSNoteProperty("required", CultureInfo.CurrentCulture.TextInfo.ToLower(paramAttribute.Mandatory.ToString())));
obj.Properties.Add(new PSNoteProperty("pipelineInput", GetPipelineInputString(paramAttribute)));
obj.Properties.Add(new PSNoteProperty("isDynamic", CultureInfo.CurrentCulture.TextInfo.ToLower(dynamic.ToString())));
if (paramAttribute.ParameterSetName.Equals(ParameterAttribute.AllParameterSets, StringComparison.OrdinalIgnoreCase))
{
obj.Properties.Add(new PSNoteProperty("parameterSetName", StringUtil.Format(HelpDisplayStrings.AllParameterSetsName)));
}
else
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < attribs.Count; i++)
{
sb.Append(attribs[i].ParameterSetName);
if (i != (attribs.Count - 1))
{
sb.Append(", ");
}
}
obj.Properties.Add(new PSNoteProperty("parameterSetName", sb.ToString()));
}
if (paramAttribute.HelpMessage != null)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(paramAttribute.HelpMessage);
obj.Properties.Add(new PSNoteProperty("description", sb.ToString()));
}
// We do not show switch parameters in the syntax section
// (i.e. [-Syntax] not [-Syntax <SwitchParameter>]
if (type != typeof(SwitchParameter))
{
AddParameterValueProperties(obj, type, attributes);
}
AddParameterTypeProperties(obj, type, attributes);
if (paramAttribute.Position == int.MinValue)
{
obj.Properties.Add(new PSNoteProperty("position",
StringUtil.Format(HelpDisplayStrings.NamedParameter)));
}
else
{
obj.Properties.Add(new PSNoteProperty("position",
paramAttribute.Position.ToString(CultureInfo.InvariantCulture)));
}
if (aliases.Count == 0)
{
obj.Properties.Add(new PSNoteProperty("aliases", StringUtil.Format(
HelpDisplayStrings.None)));
}
else
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < aliases.Count; i++)
{
sb.Append(aliases[i]);
if (i != (aliases.Count - 1))
{
sb.Append(", ");
}
}
obj.Properties.Add(new PSNoteProperty("aliases", sb.ToString()));
}
}
}
/// <summary>
/// Adds the parameterType properties
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="parameterType">the type of a parameter</param>
/// <param name="attributes">the attributes of the parameter (needed to look for PSTypeName)</param>
private static void AddParameterTypeProperties(PSObject obj, Type parameterType, IEnumerable<Attribute> attributes)
{
PSObject mshObject = new PSObject();
mshObject.TypeNames.Clear();
mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
var parameterTypeString = CommandParameterSetInfo.GetParameterTypeString(parameterType, attributes);
mshObject.Properties.Add(new PSNoteProperty("name", parameterTypeString));
obj.Properties.Add(new PSNoteProperty("type", mshObject));
}
/// <summary>
/// Adds the parameterValue properties
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="parameterType">the type of a parameter</param>
/// <param name="attributes">the attributes of the parameter (needed to look for PSTypeName)</param>
private static void AddParameterValueProperties(PSObject obj, Type parameterType, IEnumerable<Attribute> attributes)
{
PSObject mshObject;
if (parameterType != null)
{
Type type = Nullable.GetUnderlyingType(parameterType) ?? parameterType;
var parameterTypeString = CommandParameterSetInfo.GetParameterTypeString(parameterType, attributes);
mshObject = new PSObject(parameterTypeString);
mshObject.Properties.Add(new PSNoteProperty("variableLength", parameterType.IsArray));
}
else
{
mshObject = new PSObject("System.Object");
mshObject.Properties.Add(new PSNoteProperty("variableLength",
StringUtil.Format(HelpDisplayStrings.FalseShort)));
}
mshObject.Properties.Add(new PSNoteProperty("required", "true"));
obj.Properties.Add(new PSNoteProperty("parameterValue", mshObject));
}
/// <summary>
/// Adds the InputTypes properties
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="parameters">command parameters</param>
internal static void AddInputTypesProperties(PSObject obj, Dictionary<string, ParameterMetadata> parameters)
{
Collection<string> inputs = new Collection<string>();
if (parameters != null)
{
foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters)
{
Collection<ParameterAttribute> attribs = GetParameterAttribute(parameter.Value.Attributes);
foreach (ParameterAttribute attrib in attribs)
{
if (attrib.ValueFromPipeline ||
attrib.ValueFromPipelineByPropertyName ||
attrib.ValueFromRemainingArguments)
{
if (!inputs.Contains(parameter.Value.ParameterType.FullName))
{
inputs.Add(parameter.Value.ParameterType.FullName);
}
}
}
}
}
if (inputs.Count == 0)
{
inputs.Add(StringUtil.Format(HelpDisplayStrings.None));
}
StringBuilder sb = new StringBuilder();
foreach (string input in inputs)
{
sb.AppendLine(input);
}
PSObject inputTypesObj = new PSObject();
inputTypesObj.TypeNames.Clear();
inputTypesObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#inputTypes", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
PSObject inputTypeObj = new PSObject();
inputTypeObj.TypeNames.Clear();
inputTypeObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#inputType", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
PSObject typeObj = new PSObject();
typeObj.TypeNames.Clear();
typeObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
typeObj.Properties.Add(new PSNoteProperty("name", sb.ToString()));
inputTypeObj.Properties.Add(new PSNoteProperty("type", typeObj));
inputTypesObj.Properties.Add(new PSNoteProperty("inputType", inputTypeObj));
obj.Properties.Add(new PSNoteProperty("inputTypes", inputTypesObj));
}
/// <summary>
/// Adds the OutputTypes properties
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="outputTypes">output types</param>
private static void AddOutputTypesProperties(PSObject obj, ReadOnlyCollection<PSTypeName> outputTypes)
{
PSObject returnValuesObj = new PSObject();
returnValuesObj.TypeNames.Clear();
returnValuesObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#returnValues", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
PSObject returnValueObj = new PSObject();
returnValueObj.TypeNames.Clear();
returnValueObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#returnValue", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
PSObject typeObj = new PSObject();
typeObj.TypeNames.Clear();
typeObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
if (outputTypes.Count == 0)
{
typeObj.Properties.Add(new PSNoteProperty("name", "System.Object"));
}
else
{
StringBuilder sb = new StringBuilder();
foreach (PSTypeName outputType in outputTypes)
{
sb.AppendLine(outputType.Name);
}
typeObj.Properties.Add(new PSNoteProperty("name", sb.ToString()));
}
returnValueObj.Properties.Add(new PSNoteProperty("type", typeObj));
returnValuesObj.Properties.Add(new PSNoteProperty("returnValue", returnValueObj));
obj.Properties.Add(new PSNoteProperty("returnValues", returnValuesObj));
}
/// <summary>
/// Adds the aliases properties
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="name">command name</param>
/// <param name="context">execution context</param>
private static void AddAliasesProperties(PSObject obj, string name, ExecutionContext context)
{
StringBuilder sb = new StringBuilder();
bool found = false;
if (context != null)
{
foreach (string alias in context.SessionState.Internal.GetAliasesByCommandName(name))
{
found = true;
sb.AppendLine(alias);
}
}
if (!found)
{
sb.AppendLine(StringUtil.Format(HelpDisplayStrings.None));
}
obj.Properties.Add(new PSNoteProperty("aliases", sb.ToString()));
}
/// <summary>
/// Adds the remarks properties
/// </summary>
/// <param name="obj">HelpInfo object</param>
/// <param name="cmdletName"></param>
/// <param name="helpUri"></param>
private static void AddRemarksProperties(PSObject obj, string cmdletName, string helpUri)
{
if (String.IsNullOrEmpty(helpUri))
{
obj.Properties.Add(new PSNoteProperty("remarks", StringUtil.Format(HelpDisplayStrings.GetLatestHelpContentWithoutHelpUri, cmdletName)));
}
else
{
obj.Properties.Add(new PSNoteProperty("remarks", StringUtil.Format(HelpDisplayStrings.GetLatestHelpContent, cmdletName, helpUri)));
}
}
/// <summary>
/// Adds the related links properties
/// </summary>
/// <param name="obj"></param>
/// <param name="relatedLink"></param>
internal static void AddRelatedLinksProperties(PSObject obj, string relatedLink)
{
if (!String.IsNullOrEmpty(relatedLink))
{
PSObject navigationLinkObj = new PSObject();
navigationLinkObj.TypeNames.Clear();
navigationLinkObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#navigationLinks", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
navigationLinkObj.Properties.Add(new PSNoteProperty("uri", relatedLink));
List<PSObject> navigationLinkValues = new List<PSObject> { navigationLinkObj };
// check if obj already has relatedLinks property
PSNoteProperty relatedLinksPO = obj.Properties["relatedLinks"] as PSNoteProperty;
if ((relatedLinksPO != null) && (relatedLinksPO.Value != null))
{
PSObject relatedLinksValue = PSObject.AsPSObject(relatedLinksPO.Value);
PSNoteProperty navigationLinkPO = relatedLinksValue.Properties["navigationLink"] as PSNoteProperty;
if ((navigationLinkPO != null) && (navigationLinkPO.Value != null))
{
PSObject navigationLinkValue = navigationLinkPO.Value as PSObject;
if (navigationLinkValue != null)
{
navigationLinkValues.Add(navigationLinkValue);
}
else
{
PSObject[] navigationLinkValueArray = navigationLinkPO.Value as PSObject[];
if (navigationLinkValueArray != null)
{
foreach (var psObject in navigationLinkValueArray)
{
navigationLinkValues.Add(psObject);
}
}
}
}
}
PSObject relatedLinksObj = new PSObject();
relatedLinksObj.TypeNames.Clear();
relatedLinksObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#relatedLinks", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp));
relatedLinksObj.Properties.Add(new PSNoteProperty("navigationLink", navigationLinkValues.ToArray()));
obj.Properties.Add(new PSNoteProperty("relatedLinks", relatedLinksObj));
}
}
/// <summary>
/// Gets the parameter attribute from parameter metadata
/// </summary>
/// <param name="attributes">parameter attributes</param>
/// <returns>parameter attributes</returns>
private static Collection<ParameterAttribute> GetParameterAttribute(Collection<Attribute> attributes)
{
Collection<ParameterAttribute> paramAttributes = new Collection<ParameterAttribute>();
foreach (Attribute attribute in attributes)
{
ParameterAttribute paramAttribute = (object)attribute as ParameterAttribute;
if (paramAttribute != null)
{
paramAttributes.Add(paramAttribute);
}
}
return paramAttributes;
}
/// <summary>
/// Gets the validate set attribute from parameter metadata
/// </summary>
/// <param name="attributes">parameter attributes</param>
/// <returns>parameter attributes</returns>
private static Collection<ValidateSetAttribute> GetValidateSetAttribute(Collection<Attribute> attributes)
{
Collection<ValidateSetAttribute> validateSetAttributes = new Collection<ValidateSetAttribute>();
foreach (Attribute attribute in attributes)
{
ValidateSetAttribute validateSetAttribute = (object)attribute as ValidateSetAttribute;
if (validateSetAttribute != null)
{
validateSetAttributes.Add(validateSetAttribute);
}
}
return validateSetAttributes;
}
/// <summary>
/// Gets the pipeline input type
/// </summary>
/// <param name="paramAttrib">parameter attribute</param>
/// <returns>pipeline input type</returns>
private static string GetPipelineInputString(ParameterAttribute paramAttrib)
{
Debug.Assert(paramAttrib != null);
ArrayList values = new ArrayList();
if (paramAttrib.ValueFromPipeline)
{
values.Add(StringUtil.Format(HelpDisplayStrings.PipelineByValue));
}
if (paramAttrib.ValueFromPipelineByPropertyName)
{
values.Add(StringUtil.Format(HelpDisplayStrings.PipelineByPropertyName));
}
if (paramAttrib.ValueFromRemainingArguments)
{
values.Add(StringUtil.Format(HelpDisplayStrings.PipelineFromRemainingArguments));
}
if (values.Count == 0)
{
return StringUtil.Format(HelpDisplayStrings.FalseShort);
}
StringBuilder sb = new StringBuilder();
sb.Append(StringUtil.Format(HelpDisplayStrings.TrueShort));
sb.Append(" (");
for (int i = 0; i < values.Count; i++)
{
sb.Append((string)values[i]);
if (i != (values.Count - 1))
{
sb.Append(", ");
}
}
sb.Append(")");
return sb.ToString();
}
/// <summary>
/// Checks if a set of parameters contains any of the common parameters
/// </summary>
/// <param name="parameters">parameters to check</param>
/// <returns>true if it contains common parameters, false otherwise</returns>
internal static bool HasCommonParameters(Dictionary<string, ParameterMetadata> parameters)
{
Collection<string> commonParams = new Collection<string>();
foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters)
{
if (Cmdlet.CommonParameters.Contains(parameter.Value.Name))
{
commonParams.Add(parameter.Value.Name);
}
}
return (commonParams.Count == Cmdlet.CommonParameters.Count);
}
/// <summary>
/// Checks if a parameter is a common workflow parameter
/// </summary>
/// <param name="name">parameter name</param>
/// <returns>true if it is a common parameter, false if not</returns>
private static bool IsCommonWorkflowParameter(string name)
{
foreach (string parameter in CommonParameters.CommonWorkflowParameters)
{
if (name == parameter)
return true;
}
return false;
}
/// <summary>
/// Checks if the module contains HelpInfoUri
/// </summary>
/// <param name="module"></param>
/// <param name="moduleName"></param>
/// <returns></returns>
private static bool HasHelpInfoUri(PSModuleInfo module, string moduleName)
{
// The core module is really a SnapIn, so module will be null
if (!String.IsNullOrEmpty(moduleName) && moduleName.Equals(InitialSessionState.CoreModule, StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (module == null)
{
return false;
}
return !String.IsNullOrEmpty(module.HelpInfoUri);
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// Section 5.3.6.6. Request from simulation manager to an entity
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(FixedDatum))]
[XmlInclude(typeof(VariableDatum))]
public partial class ActionRequestPdu : SimulationManagementPdu, IEquatable<ActionRequestPdu>
{
/// <summary>
/// Request ID that is unique
/// </summary>
private uint _requestID;
/// <summary>
/// identifies the action being requested
/// </summary>
private uint _actionID;
/// <summary>
/// Number of fixed datum records
/// </summary>
private uint _fixedDatumRecordCount;
/// <summary>
/// Number of variable datum records
/// </summary>
private uint _variableDatumRecordCount;
/// <summary>
/// variable length list of fixed datums
/// </summary>
private List<FixedDatum> _fixedDatums = new List<FixedDatum>();
/// <summary>
/// variable length list of variable length datums
/// </summary>
private List<VariableDatum> _variableDatums = new List<VariableDatum>();
/// <summary>
/// Initializes a new instance of the <see cref="ActionRequestPdu"/> class.
/// </summary>
public ActionRequestPdu()
{
PduType = (byte)16;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(ActionRequestPdu left, ActionRequestPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(ActionRequestPdu left, ActionRequestPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += 4; // this._requestID
marshalSize += 4; // this._actionID
marshalSize += 4; // this._fixedDatumRecordCount
marshalSize += 4; // this._variableDatumRecordCount
for (int idx = 0; idx < this._fixedDatums.Count; idx++)
{
FixedDatum listElement = (FixedDatum)this._fixedDatums[idx];
marshalSize += listElement.GetMarshalledSize();
}
for (int idx = 0; idx < this._variableDatums.Count; idx++)
{
VariableDatum listElement = (VariableDatum)this._variableDatums[idx];
marshalSize += listElement.GetMarshalledSize();
}
return marshalSize;
}
/// <summary>
/// Gets or sets the Request ID that is unique
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "requestID")]
public uint RequestID
{
get
{
return this._requestID;
}
set
{
this._requestID = value;
}
}
/// <summary>
/// Gets or sets the identifies the action being requested
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "actionID")]
public uint ActionID
{
get
{
return this._actionID;
}
set
{
this._actionID = value;
}
}
/// <summary>
/// Gets or sets the Number of fixed datum records
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getfixedDatumRecordCount method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(uint), ElementName = "fixedDatumRecordCount")]
public uint FixedDatumRecordCount
{
get
{
return this._fixedDatumRecordCount;
}
set
{
this._fixedDatumRecordCount = value;
}
}
/// <summary>
/// Gets or sets the Number of variable datum records
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getvariableDatumRecordCount method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(uint), ElementName = "variableDatumRecordCount")]
public uint VariableDatumRecordCount
{
get
{
return this._variableDatumRecordCount;
}
set
{
this._variableDatumRecordCount = value;
}
}
/// <summary>
/// Gets the variable length list of fixed datums
/// </summary>
[XmlElement(ElementName = "fixedDatumsList", Type = typeof(List<FixedDatum>))]
public List<FixedDatum> FixedDatums
{
get
{
return this._fixedDatums;
}
}
/// <summary>
/// Gets the variable length list of variable length datums
/// </summary>
[XmlElement(ElementName = "variableDatumsList", Type = typeof(List<VariableDatum>))]
public List<VariableDatum> VariableDatums
{
get
{
return this._variableDatums;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
dos.WriteUnsignedInt((uint)this._requestID);
dos.WriteUnsignedInt((uint)this._actionID);
dos.WriteUnsignedInt((uint)this._fixedDatums.Count);
dos.WriteUnsignedInt((uint)this._variableDatums.Count);
for (int idx = 0; idx < this._fixedDatums.Count; idx++)
{
FixedDatum aFixedDatum = (FixedDatum)this._fixedDatums[idx];
aFixedDatum.Marshal(dos);
}
for (int idx = 0; idx < this._variableDatums.Count; idx++)
{
VariableDatum aVariableDatum = (VariableDatum)this._variableDatums[idx];
aVariableDatum.Marshal(dos);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._requestID = dis.ReadUnsignedInt();
this._actionID = dis.ReadUnsignedInt();
this._fixedDatumRecordCount = dis.ReadUnsignedInt();
this._variableDatumRecordCount = dis.ReadUnsignedInt();
for (int idx = 0; idx < this.FixedDatumRecordCount; idx++)
{
FixedDatum anX = new FixedDatum();
anX.Unmarshal(dis);
this._fixedDatums.Add(anX);
}
for (int idx = 0; idx < this.VariableDatumRecordCount; idx++)
{
VariableDatum anX = new VariableDatum();
anX.Unmarshal(dis);
this._variableDatums.Add(anX);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<ActionRequestPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>");
sb.AppendLine("<actionID type=\"uint\">" + this._actionID.ToString(CultureInfo.InvariantCulture) + "</actionID>");
sb.AppendLine("<fixedDatums type=\"uint\">" + this._fixedDatums.Count.ToString(CultureInfo.InvariantCulture) + "</fixedDatums>");
sb.AppendLine("<variableDatums type=\"uint\">" + this._variableDatums.Count.ToString(CultureInfo.InvariantCulture) + "</variableDatums>");
for (int idx = 0; idx < this._fixedDatums.Count; idx++)
{
sb.AppendLine("<fixedDatums" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"FixedDatum\">");
FixedDatum aFixedDatum = (FixedDatum)this._fixedDatums[idx];
aFixedDatum.Reflection(sb);
sb.AppendLine("</fixedDatums" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
for (int idx = 0; idx < this._variableDatums.Count; idx++)
{
sb.AppendLine("<variableDatums" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"VariableDatum\">");
VariableDatum aVariableDatum = (VariableDatum)this._variableDatums[idx];
aVariableDatum.Reflection(sb);
sb.AppendLine("</variableDatums" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("</ActionRequestPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as ActionRequestPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(ActionRequestPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (this._requestID != obj._requestID)
{
ivarsEqual = false;
}
if (this._actionID != obj._actionID)
{
ivarsEqual = false;
}
if (this._fixedDatumRecordCount != obj._fixedDatumRecordCount)
{
ivarsEqual = false;
}
if (this._variableDatumRecordCount != obj._variableDatumRecordCount)
{
ivarsEqual = false;
}
if (this._fixedDatums.Count != obj._fixedDatums.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._fixedDatums.Count; idx++)
{
if (!this._fixedDatums[idx].Equals(obj._fixedDatums[idx]))
{
ivarsEqual = false;
}
}
}
if (this._variableDatums.Count != obj._variableDatums.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._variableDatums.Count; idx++)
{
if (!this._variableDatums[idx].Equals(obj._variableDatums[idx]))
{
ivarsEqual = false;
}
}
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._requestID.GetHashCode();
result = GenerateHash(result) ^ this._actionID.GetHashCode();
result = GenerateHash(result) ^ this._fixedDatumRecordCount.GetHashCode();
result = GenerateHash(result) ^ this._variableDatumRecordCount.GetHashCode();
if (this._fixedDatums.Count > 0)
{
for (int idx = 0; idx < this._fixedDatums.Count; idx++)
{
result = GenerateHash(result) ^ this._fixedDatums[idx].GetHashCode();
}
}
if (this._variableDatums.Count > 0)
{
for (int idx = 0; idx < this._variableDatums.Count; idx++)
{
result = GenerateHash(result) ^ this._variableDatums[idx].GetHashCode();
}
}
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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BlendInt162()
{
var test = new ImmBinaryOpTest__BlendInt162();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__BlendInt162
{
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__BlendInt162 testClass)
{
var result = Avx2.Blend(_fld1, _fld2, 2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable;
static ImmBinaryOpTest__BlendInt162()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public ImmBinaryOpTest__BlendInt162()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Blend(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Blend(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Blend(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Blend(
_clsVar1,
_clsVar2,
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx2.Blend(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__BlendInt162();
var result = Avx2.Blend(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Blend(_fld1, _fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Blend(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (((2 & (1 << 0)) == 0) ? left[0] : right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((i < 8) ? (((2 & (1 << i)) == 0) ? left[i] : right[i]) : (((2 & (1 << (i - 8))) == 0) ? left[i] : right[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<Int16>(Vector256<Int16>.2, Vector256<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* A Two-Pass Authenticated-Encryption Scheme Optimized for Simplicity and
* Efficiency - by M. Bellare, P. Rogaway, D. Wagner.
*
* http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf
*
* EAX is an AEAD scheme based on CTR and OMAC1/CMAC, that uses a single block
* cipher to encrypt and authenticate data. It's on-line (the length of a
* message isn't needed to begin processing it), has good performances, it's
* simple and provably secure (provided the underlying block cipher is secure).
*
* Of course, this implementations is NOT thread-safe.
*/
public class EaxBlockCipher
: IAeadBlockCipher
{
private enum Tag : byte { N, H, C };
private SicBlockCipher cipher;
private bool forEncryption;
private int blockSize;
private IMac mac;
private byte[] nonceMac;
private byte[] associatedTextMac;
private byte[] macBlock;
private int macSize;
private byte[] bufBlock;
private int bufOff;
/**
* Constructor that accepts an instance of a block cipher engine.
*
* @param cipher the engine to use
*/
public EaxBlockCipher(
IBlockCipher cipher)
{
blockSize = cipher.GetBlockSize();
mac = new CMac(cipher);
macBlock = new byte[blockSize];
bufBlock = new byte[blockSize * 2];
associatedTextMac = new byte[mac.GetMacSize()];
nonceMac = new byte[mac.GetMacSize()];
this.cipher = new SicBlockCipher(cipher);
}
public virtual string AlgorithmName
{
get { return cipher.GetUnderlyingCipher().AlgorithmName + "/EAX"; }
}
public virtual int GetBlockSize()
{
return cipher.GetBlockSize();
}
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.forEncryption = forEncryption;
byte[] nonce, associatedText;
ICipherParameters keyParam;
if (parameters is AeadParameters)
{
AeadParameters param = (AeadParameters) parameters;
nonce = param.GetNonce();
associatedText = param.GetAssociatedText();
macSize = param.MacSize / 8;
keyParam = param.Key;
}
else if (parameters is ParametersWithIV)
{
ParametersWithIV param = (ParametersWithIV) parameters;
nonce = param.GetIV();
associatedText = new byte[0];
macSize = mac.GetMacSize() / 2;
keyParam = param.Parameters;
}
else
{
throw new ArgumentException("invalid parameters passed to EAX");
}
byte[] tag = new byte[blockSize];
mac.Init(keyParam);
tag[blockSize - 1] = (byte) Tag.H;
mac.BlockUpdate(tag, 0, blockSize);
mac.BlockUpdate(associatedText, 0, associatedText.Length);
mac.DoFinal(associatedTextMac, 0);
tag[blockSize - 1] = (byte) Tag.N;
mac.BlockUpdate(tag, 0, blockSize);
mac.BlockUpdate(nonce, 0, nonce.Length);
mac.DoFinal(nonceMac, 0);
tag[blockSize - 1] = (byte) Tag.C;
mac.BlockUpdate(tag, 0, blockSize);
cipher.Init(true, new ParametersWithIV(keyParam, nonceMac));
}
private void calculateMac()
{
byte[] outC = new byte[blockSize];
mac.DoFinal(outC, 0);
for (int i = 0; i < macBlock.Length; i++)
{
macBlock[i] = (byte)(nonceMac[i] ^ associatedTextMac[i] ^ outC[i]);
}
}
public virtual void Reset()
{
Reset(true);
}
private void Reset(
bool clearMac)
{
cipher.Reset();
mac.Reset();
bufOff = 0;
Array.Clear(bufBlock, 0, bufBlock.Length);
if (clearMac)
{
Array.Clear(macBlock, 0, macBlock.Length);
}
byte[] tag = new byte[blockSize];
tag[blockSize - 1] = (byte) Tag.C;
mac.BlockUpdate(tag, 0, blockSize);
}
public virtual int ProcessByte(
byte input,
byte[] outBytes,
int outOff)
{
return process(input, outBytes, outOff);
}
public virtual int ProcessBytes(
byte[] inBytes,
int inOff,
int len,
byte[] outBytes,
int outOff)
{
int resultLen = 0;
for (int i = 0; i != len; i++)
{
resultLen += process(inBytes[inOff + i], outBytes, outOff + resultLen);
}
return resultLen;
}
public virtual int DoFinal(
byte[] outBytes,
int outOff)
{
int extra = bufOff;
byte[] tmp = new byte[bufBlock.Length];
bufOff = 0;
if (forEncryption)
{
cipher.ProcessBlock(bufBlock, 0, tmp, 0);
cipher.ProcessBlock(bufBlock, blockSize, tmp, blockSize);
Array.Copy(tmp, 0, outBytes, outOff, extra);
mac.BlockUpdate(tmp, 0, extra);
calculateMac();
Array.Copy(macBlock, 0, outBytes, outOff + extra, macSize);
Reset(false);
return extra + macSize;
}
else
{
if (extra > macSize)
{
mac.BlockUpdate(bufBlock, 0, extra - macSize);
cipher.ProcessBlock(bufBlock, 0, tmp, 0);
cipher.ProcessBlock(bufBlock, blockSize, tmp, blockSize);
Array.Copy(tmp, 0, outBytes, outOff, extra - macSize);
}
calculateMac();
if (!verifyMac(bufBlock, extra - macSize))
throw new InvalidCipherTextException("mac check in EAX failed");
Reset(false);
return extra - macSize;
}
}
public virtual byte[] GetMac()
{
byte[] mac = new byte[macSize];
Array.Copy(macBlock, 0, mac, 0, macSize);
return mac;
}
public virtual int GetUpdateOutputSize(
int len)
{
return ((len + bufOff) / blockSize) * blockSize;
}
public virtual int GetOutputSize(
int len)
{
if (forEncryption)
{
return len + bufOff + macSize;
}
return len + bufOff - macSize;
}
private int process(
byte b,
byte[] outBytes,
int outOff)
{
bufBlock[bufOff++] = b;
if (bufOff == bufBlock.Length)
{
int size;
if (forEncryption)
{
size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
mac.BlockUpdate(outBytes, outOff, blockSize);
}
else
{
mac.BlockUpdate(bufBlock, 0, blockSize);
size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
}
bufOff = blockSize;
Array.Copy(bufBlock, blockSize, bufBlock, 0, blockSize);
return size;
}
return 0;
}
private bool verifyMac(byte[] mac, int off)
{
for (int i = 0; i < macSize; i++)
{
if (macBlock[i] != mac[off + i])
{
return false;
}
}
return true;
}
}
}
| |
using OpenKh.Common;
using OpenKh.Tools.Common;
using OpenKh.Tools.ModsManager.Interfaces;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OpenKh.Tools.ModsManager.Services
{
public class Pcsx2Injector
{
private class Offsets
{
public string GameName { get; init; }
public int LoadFile { get; init; }
public int GetFileSize { get; init; }
public int RegionInit { get; init; }
public int BufferPointer { get; init; }
public int RegionForce { get; init; }
public int RegionId { get; init; }
public int RegionPtr { get; init; }
public int LanguagePtr { get; init; }
}
private class Patch
{
public string Game { get; init; }
public string Name { get; init; }
public int Address { get; init; }
public uint[] Pattern { get; init; }
public uint[] NewPattern { get; init; }
}
private const string KH2FM = "SLPM_666.75;1";
private const uint Zero = 0x00;
private const uint AT = 0x01;
private const uint V0 = 0x02;
private const uint V1 = 0x03;
private const uint A0 = 0x04;
private const uint A1 = 0x05;
private const uint A2 = 0x06;
private const uint A3 = 0x07;
private const uint T0 = 0x08;
private const uint T1 = 0x09;
private const uint T2 = 0x0A;
private const uint T3 = 0x0B;
private const uint T4 = 0x0C;
private const uint T5 = 0x0D;
private const uint T6 = 0x0E;
private const uint T7 = 0x0F;
private const uint S0 = 0x10;
private const uint S1 = 0x11;
private const uint S2 = 0x12;
private const uint S3 = 0x13;
private const uint S4 = 0x14;
private const uint S5 = 0x15;
private const uint S6 = 0x16;
private const uint S7 = 0x17;
private const uint T8 = 0x18;
private const uint T9 = 0x19;
private const uint SP = 0x1D;
private const uint RA = 0x1F;
private static uint NOP() => 0x00000000;
private static uint JR(uint reg) => 0x00000008U | (reg << 21);
private static uint SYSCALL() => 0x0000000C;
private static uint JAL(uint offset) =>
0x0C000000U | (offset / 4);
private static uint BLTZ(uint reg, short jump) =>
0x04000000U | (0 << 16) | (reg << 21) | (ushort)jump;
private static uint BGEZ(uint reg, short jump) =>
0x04000000U | (1 << 16) | (reg << 21) | (ushort)jump;
private static uint BLTZL(uint reg, short jump) =>
0x04000000U | (2 << 16) | (reg << 21) | (ushort)jump;
private static uint BGEZL(uint reg, short jump) =>
0x04000000U | (1 << 16) | (reg << 21) | (ushort)jump;
private static uint BEQ(uint left, uint right, short jump) =>
0x10000000U | (right << 16) | (left << 21) | (ushort)jump;
private static uint BNE(uint left, uint right, short jump) =>
0x14000000U | (right << 16) | (left << 21) | (ushort)jump;
private static uint ADDIU(uint dst, uint src, short value) =>
0x24000000U | (dst << 16) | (src << 21) | (ushort)value;
private static uint LUI(uint dst, ushort value) =>
0x3C000000U | (dst << 16) | value;
private static uint LW(uint dst, uint src, short offset) =>
0x8C000000U | (dst << 16) | (src << 21) | (ushort)offset;
private static uint SW(uint src, uint dst, short offset) =>
0xAC000000U | (src << 16) | (dst << 21) | (ushort)offset;
private static uint LD(uint src, uint dst, short offset) =>
0xDC000000U | (src << 16) | (dst << 21) | (ushort)offset;
private static uint SD(uint src, uint dst, short offset) =>
0xFC000000U | (src << 16) | (dst << 21) | (ushort)offset;
public enum Operation
{
HookExit,
LoadFile,
GetFileSize
}
private const uint BaseHookPtr = 0xFFF00;
private const int HookStack = 0x0F;
private const int ParamOperator = -0x04;
private const int Param1 = -0x08;
private const int Param2 = -0x0C;
private const int Param3 = -0x10;
private const int Param4 = -0x14;
private const int ParamReturn = Param1;
private static readonly uint[] LoadFileHook = new uint[]
{
// Input:
// T4 return program counter
// T5 Operation
// RA fallback program counter
//
// Work:
// T6 Hook stack
// V0 Return value
// V1 syscall parameter
//
LUI(T6, HookStack),
SW(A0, T6, Param1),
SW(A1, T6, Param2),
SW(T5, T6, ParamOperator),
LW(T5, T6, ParamOperator),
BNE(T5, (byte)Operation.HookExit, -2),
LW(V0, T6, ParamReturn),
BEQ(V0, Zero, 2),
NOP(),
ADDIU(RA, RA, 4),
ADDIU(SP, SP, -0x10),
SD(T4, SP, 0x08),
SD(S0, SP, 0x00),
JR(RA),
NOP(),
};
private static readonly uint[] GetFileSizeHook = new uint[]
{
// Input:
// A0 const char* fileName
// T4 return program counter
// T5 Operation
// RA fallback program counter
//
// Work:
// T6 Hook stack
// V0 Return value
// V1 syscall parameter
//
LUI(T6, HookStack),
SW(A0, T6, Param1),
SW(A1, T6, Param2),
SW(A2, T6, Param3),
SW(A3, T6, Param4),
SW(T5, T6, ParamOperator),
LW(T5, T6, ParamOperator),
BNE(T5, (byte)Operation.HookExit, -2),
LW(V0, T6, ParamReturn),
BEQ(V0, Zero, 2),
NOP(),
JR(T4),
NOP(),
ADDIU(SP, SP, -0x10),
SD(T4, SP, 0x08),
SD(S0, SP, 0x00),
JR(RA),
NOP(),
};
private static readonly uint[] RegionInitPatch = new uint[]
{
JR(RA),
NOP(),
};
private static readonly string[] MemoryCardPatch = new string[]
{
"SLPM", "666", "75",
"SLPM", "666", "75",
"SLPM", "666", "75", "666", "75", "75", "75",
};
private static readonly Offsets[] _offsets = new Offsets[]
{
new Offsets
{
GameName = "SLPM_662.33;1",
LoadFile = 0x167F20,
GetFileSize = 0x1AC698,
RegionInit = 0x105CA0,
BufferPointer = 0x35E680,
RegionForce = 0x37FCC8,
RegionId = 0x349514,
RegionPtr = 0x349510,
LanguagePtr = 0x349510, // same as Region
},
new Offsets
{
GameName = "SLUS_210.05;1",
LoadFile = 0x167C50,
GetFileSize = 0x1AC760,
RegionInit = 0x105CB0,
BufferPointer = 0x35EE98,
RegionForce = 0x3806D8,
RegionId = 0x349D44,
RegionPtr = 0x349D40,
LanguagePtr = 0x349D40, // same as Region
},
new Offsets
{
GameName = "SLES_541.14;1",
LoadFile = 0x167CA8,
GetFileSize = 0x1AC858,
RegionInit = 0x105CB0,
BufferPointer = 0x35F3A8,
RegionForce = 0x378378,
RegionId = 0x34A24C,
RegionPtr = 0x34A240,
LanguagePtr = 0x34A244,
},
new Offsets
{
GameName = "SLES_542.32;1",
LoadFile = 0x167CA8,
GetFileSize = 0x1AC858,
RegionInit = 0x105CB0,
BufferPointer = 0x35F3A8,
RegionForce = 0x378378,
RegionId = 0x34A24C,
RegionPtr = 0x34A240,
LanguagePtr = 0x34A244,
},
new Offsets
{
GameName = "SLES_542.33;1",
LoadFile = 0x167CA8,
GetFileSize = 0x1AC858,
RegionInit = 0x105CB0,
BufferPointer = 0x35F3A8,
RegionForce = 0x378378,
RegionId = 0x34A24C,
RegionPtr = 0x34A240,
LanguagePtr = 0x34A244,
},
new Offsets
{
GameName = "SLES_542.34;1",
LoadFile = 0x167CA8,
GetFileSize = 0x1AC858,
RegionInit = 0x105CB0,
BufferPointer = 0x35F3A8,
RegionForce = 0x378378,
RegionId = 0x34A24C,
RegionPtr = 0x34A240,
LanguagePtr = 0x34A244,
},
new Offsets
{
GameName = "SLES_542.35;1",
LoadFile = 0x167CA8,
GetFileSize = 0x1AC858,
RegionInit = 0x105CB0,
BufferPointer = 0x35F3A8,
RegionForce = 0x378378,
RegionId = 0x34A24C,
RegionPtr = 0x34A240,
LanguagePtr = 0x34A244,
},
new Offsets
{
GameName = KH2FM,
LoadFile = 0x1682b8,
GetFileSize = 0x1AE1B0,
RegionInit = 0x105AF8,
BufferPointer = 0x350E88,
RegionForce = 0x369E98,
RegionId = 0x33CAFC,
RegionPtr = 0x33CAF0,
LanguagePtr = 0x33CAF4,
},
};
private readonly IOperationDispatcher _operationDispatcher;
private const int OperationAddress = (HookStack << 16) - 4;
private CancellationTokenSource _cancellationTokenSource;
private CancellationToken _cancellationToken;
private Task _injectorTask;
private uint _hookPtr;
private uint _nextHookPtr;
private Offsets _myOffsets;
public Pcsx2Injector(IOperationDispatcher operationDispatcher)
{
_operationDispatcher = operationDispatcher;
}
public int RegionId { get; set; }
public string Region { get; set; }
public string Language { get; set; }
public void Run(Process process, IDebugging debugging)
{
_cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = _cancellationTokenSource.Token;
_injectorTask = Task.Run(async () =>
{
Log.Info("Waiting for the game to boot");
var gameName = await Pcsx2MemoryService.GetPcsx2ApplicationName(process, _cancellationToken);
using var processStream = new ProcessStream(process, 0x20000000, 0x2000000);
Log.Info("Injecting code");
_myOffsets = _offsets.FirstOrDefault(x => x.GameName == gameName);
if (_myOffsets == null)
{
Log.Err($"Game {gameName} not recognized. Exiting from the injector service.");
return;
}
WritePatch(processStream, _myOffsets);
Log.Info("Executing the injector main loop");
MainLoop(processStream, debugging);
debugging.HideDebugger();
}, _cancellationToken);
}
public void Stop()
{
try
{
_cancellationTokenSource?.Cancel();
_injectorTask?.Wait();
}
catch
{
}
}
private void MainLoop(Stream stream, IDebugging debugging)
{
var isProcessDead = false;
while (!_cancellationToken.IsCancellationRequested && !isProcessDead)
{
var operation = stream.SetPosition(OperationAddress).ReadInt32();
if (stream.Position == OperationAddress)
break; // The emulator stopped its execution
switch ((Operation)operation)
{
case Operation.LoadFile:
OperationCopyFile(stream);
break;
case Operation.GetFileSize:
OperationGetFileSize(stream);
break;
default:
break;
case Operation.HookExit:
Thread.Sleep(1);
continue;
}
stream.SetPosition(OperationAddress).Write((int)Operation.HookExit);
}
}
private void OperationCopyFile(Stream stream)
{
const int ParameterCount = 2;
stream.SetPosition(OperationAddress - ParameterCount * sizeof(uint));
var ptrMemDst = stream.ReadInt32();
var ptrFileName = stream.ReadInt32();
var fileName = ReadString(stream, ptrFileName);
if (string.IsNullOrEmpty(fileName))
return;
var returnValue = _operationDispatcher.LoadFile(stream.SetPosition(ptrMemDst), fileName);
stream.SetPosition(OperationAddress - 4).Write(returnValue);
}
private void OperationGetFileSize(Stream stream)
{
const int ParameterCount = 1;
stream.SetPosition(OperationAddress - ParameterCount * sizeof(uint));
var ptrFileName = stream.ReadInt32();
var fileName = ReadString(stream, ptrFileName);
if (string.IsNullOrEmpty(fileName))
return;
var returnValue = _operationDispatcher.GetFileSize(fileName);
stream.SetPosition(OperationAddress - 4).Write(returnValue);
}
private void WritePatch(Stream stream, Offsets offsets)
{
ResetHooks();
if (offsets != null)
{
if (offsets.LoadFile > 0)
{
Log.Info("Injecting {0} function", offsets.LoadFile);
WritePatch(stream, offsets.LoadFile,
ADDIU(T4, RA, 0),
JAL(WriteHook(stream, LoadFileHook)),
ADDIU(T5, Zero, (byte)Operation.LoadFile));
}
if (offsets.GetFileSize > 0)
{
Log.Info("Injecting {0} function", offsets.GetFileSize);
var subGetFileSizePtr = stream.SetPosition(offsets.GetFileSize + 8).ReadUInt32();
WritePatch(stream, offsets.GetFileSize,
ADDIU(T4, RA, 0),
JAL(WriteHook(stream, GetFileSizeHook)),
ADDIU(T5, Zero, (byte)Operation.GetFileSize),
subGetFileSizePtr,
NOP(),
BEQ(V0, Zero, 2),
NOP(),
LW(V0, V0, 0x0C),
LD(RA, SP, 0x08),
JR(RA),
ADDIU(SP, SP, 0x10));
}
if (RegionId > 0)
{
Log.Info("Injecting {0} function", "RegionInit");
WritePatch(stream, offsets.RegionInit, RegionInitPatch);
WritePatch(stream, offsets.RegionForce, Region);
WritePatch(stream, offsets.RegionForce + 8, Language);
WritePatch(stream, offsets.RegionId, RegionId);
WritePatch(stream, offsets.RegionPtr, offsets.RegionForce);
WritePatch(stream, offsets.LanguagePtr, offsets.RegionForce + 8);
if (offsets.GameName == KH2FM)
PatchKh2FmPs2(stream);
}
}
}
private void PatchKh2FmPs2(Stream stream)
{
// Always use "SLPM" for memory card regardless the region
WritePatch(stream, 0x240138,
ADDIU(V0, Zero, (int)Kh2.Constants.RegionId.FinalMix));
// Always use "BI" for memory card regardless the region
WritePatch(stream, 0x2402E8,
ADDIU(V0, Zero, (int)Kh2.Constants.RegionId.FinalMix),
NOP());
// Always use "KH2J" header for saves
WritePatch(stream, 0x105870,
LUI(V0, 0x4A32),
ADDIU(V0, V0, 0x484B),
JR(RA),
NOP());
// Fix weird game bug where KH2FM would crash on map change
// when the region is different from JP or FM.
WritePatch(stream, 0x015ABE8, ADDIU(V0, Zero, 1));
// Fix issue where KH2FM fails to load movie cutscenes
// when the region is different from FM.
WritePatch(stream, 0x022BC68, ADDIU(A2, A1, -0x6130));
}
private void ResetHooks() => _nextHookPtr = BaseHookPtr;
private uint WriteHook(Stream stream, params uint[] patch)
{
_hookPtr = _nextHookPtr;
_nextHookPtr += WritePatch(stream, _hookPtr, patch);
return _hookPtr;
}
private uint WritePatch(Stream stream, long offset, params uint[] patch)
{
if (offset == 0)
return 0;
stream.SetPosition(offset);
foreach (var word in patch)
stream.Write(word);
stream.Flush();
return (uint)(patch.Length * sizeof(uint));
}
private void WritePatch(Stream stream, long offset, int patch)
{
if (offset == 0)
return;
stream.SetPosition(offset).Write(patch);
}
private void WritePatch(Stream stream, long offset, string patch)
{
if (offset == 0)
return;
stream.SetPosition(offset);
foreach (var ch in patch)
stream.Write((byte)ch);
}
private static string ReadString(Stream stream, int ptr)
{
const int MaxFileNameLength = 0x30;
static bool IsValidFileName(string fileName) => fileName.Length >= 2 &&
char.IsLetterOrDigit(fileName[0]) && char.IsLetterOrDigit(fileName[1]);
var rawFileName = stream.SetPosition(ptr).ReadBytes(MaxFileNameLength);
var sbFileName = new StringBuilder();
for (var i = 0; i < rawFileName.Length; i++)
{
var ch = (char)rawFileName[i];
if (ch == '\0')
break;
sbFileName.Append(ch);
}
var fileName = sbFileName.ToString();
if (!IsValidFileName(fileName))
return null;
return fileName;
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Compiler;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace Microsoft.Contracts.Foxtrot
{
/// <summary>
/// This one expects to visit the OOB assembly
/// </summary>
[ContractVerification(true)]
internal sealed class CopyOutOfBandContracts : Inspector
{
//private Duplicator outOfBandDuplicator;
private readonly ForwardingDuplicator outOfBandDuplicator;
private readonly AssemblyNode targetAssembly;
private readonly List<KeyValuePair<Member, TypeNode>> toBeDuplicatedMembers =
new List<KeyValuePair<Member, TypeNode>>();
private TrivialHashtable duplicatedMembers;
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"),
SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.toBeDuplicatedMembers != null);
Contract.Invariant(this.outOfBandDuplicator != null);
Contract.Invariant(this.duplicatedMembers != null);
}
[Conditional("CONTRACTTRACE")]
private static void Trace(string format, params object[] args)
{
Console.WriteLine(format, args);
}
public CopyOutOfBandContracts(AssemblyNode targetAssembly, AssemblyNode sourceAssembly,
ContractNodes contractNodes, ContractNodes targetContractNodes)
{
Contract.Requires(targetAssembly != null);
Contract.Requires(sourceAssembly != null);
Contract.Requires(contractNodes != null);
if (targetAssembly == sourceAssembly)
{
// this happened when a reference assembly for mscorlib had the assembly name "mscorlib"
// instead of "mscorlib.Contracts" because only one assembly named "mscorlib" can be
// loaded
throw new ExtractorException("CopyOutOfBandContracts was given the same assembly as both the source and target!");
}
this.outOfBandDuplicator = new ForwardingDuplicator(targetAssembly, null, contractNodes, targetContractNodes);
this.targetAssembly = targetAssembly;
FuzzilyForwardReferencesFromSource2Target(targetAssembly, sourceAssembly);
CopyMissingMembers();
// FixupMissingProperties(); shouldn't be needed with new duplicator
}
private void CopyMissingMembers()
{
Contract.Ensures(this.duplicatedMembers != null);
this.duplicatedMembers = new TrivialHashtable(this.toBeDuplicatedMembers.Count*2);
foreach (var missing in this.toBeDuplicatedMembers)
{
Contract.Assume(missing.Value != null);
Contract.Assume(missing.Key != null);
InstanceInitializer ctor = missing.Key as InstanceInitializer;
if (ctor != null && ctor.ParameterCount == 0) continue;
var targetType = missing.Value;
Trace("COPYOOB: copying {0} to {1}", missing.Key.FullName, targetType.FullName);
this.Duplicator.TargetType = targetType;
var dup = (Member) this.Duplicator.Visit(missing.Key);
targetType.Members.Add(dup);
duplicatedMembers[missing.Key.UniqueKey] = missing;
}
}
private Duplicator Duplicator
{
get
{
Contract.Ensures(Contract.Result<Duplicator>() != null);
return this.outOfBandDuplicator;
}
}
// Methods for setting up a duplicator to use to copy out-of-band contracts
[ContractVerification(false)]
private static bool FuzzyEqual(TypeNode t1, TypeNode t2)
{
return t1 == t2 ||
(t1 != null &&
t2 != null &&
t1.Namespace != null &&
t2.Namespace != null &&
t1.Name != null &&
t2.Name != null &&
t1.Namespace.Name == t2.Namespace.Name &&
t1.Name.Name == t2.Name.Name);
}
private static bool FuzzyEqual(Parameter p1, Parameter p2)
{
if (p1 == null && p2 == null) return true;
if (p1 == null) return false;
if (p2 == null) return false;
return FuzzyEqual(p1.Type, p2.Type);
}
private static bool FuzzyEqual(ParameterList xs, ParameterList ys)
{
if (xs == null && ys == null) return true;
if (xs == null) return false;
if (ys == null) return false;
if (xs.Count != ys.Count) return false;
for (int i = 0, n = xs.Count; i < n; i++)
{
if (!FuzzyEqual(xs[i], ys[i])) return false;
}
return true;
}
[Pure]
private static Member FuzzilyGetMatchingMember(TypeNode t, Member m)
{
Contract.Requires(t != null);
Contract.Requires(m != null);
var candidates = t.GetMembersNamed(m.Name);
Contract.Assert(candidates != null, "Clousot can prove it");
for (int i = 0, n = candidates.Count; i < n; i++)
{
Member mem = candidates[i];
if (mem == null) continue;
if (!mem.Name.Matches(m.Name)) continue;
// type case statement would be *so* nice right now
// Can't test the NodeType because for mscorlib.Contracts, structs are read in as classes
// because they don't extend the "real" System.ValueType, but the one declared in mscorlib.Contracts.
//if (mem.NodeType != m.NodeType) continue;
Method x = mem as Method; // handles regular Methods and InstanceInitializers
if (x != null)
{
Method m_prime = m as Method;
if (m_prime == null) continue;
if ((x.TemplateParameters == null) != (m_prime.TemplateParameters == null)) continue;
if (FuzzyEqual(m_prime.Parameters, x.Parameters)
&& FuzzyEqual(m_prime.ReturnType, x.ReturnType)
&& TemplateParameterCount(x) == TemplateParameterCount(m_prime))
{
return mem;
}
continue;
}
Field memAsField = mem as Field;
if (memAsField != null)
{
Field mAsField = m as Field;
if (mAsField == null) continue;
if (FuzzyEqual(mAsField.Type, memAsField.Type)) return mem;
continue;
}
Event memAsEvent = mem as Event;
if (memAsEvent != null)
{
Event mAsEvent = m as Event;
if (mAsEvent == null) continue;
if (FuzzyEqual(mAsEvent.HandlerType, memAsEvent.HandlerType)) return mem;
continue;
}
Property memAsProperty = mem as Property;
if (memAsProperty != null)
{
Property mAsProperty = m as Property;
if (mAsProperty == null) continue;
if (FuzzyEqual(mAsProperty.Type, memAsProperty.Type)) return mem;
continue;
}
TypeNode memAsTypeNode = mem as TypeNode; // handles Class, Interface, etc.
if (memAsTypeNode != null)
{
TypeNode mAsTypeNode = m as TypeNode;
if (mAsTypeNode == null) continue;
if (FuzzyEqual(mAsTypeNode, memAsTypeNode)) return mem;
continue;
}
Contract.Assume(false, "Pseudo-typecase failed to find a match");
}
return null;
}
private void FuzzilyForwardReferencesFromSource2Target(AssemblyNode targetAssembly, AssemblyNode sourceAssembly)
{
Contract.Requires(targetAssembly != null);
Contract.Requires(sourceAssembly != null);
for (int i = 1, n = sourceAssembly.Types.Count; i < n; i++)
{
TypeNode currentType = sourceAssembly.Types[i];
if (currentType == null) continue;
TypeNode targetType = targetAssembly.GetType(currentType.Namespace, currentType.Name);
if (targetType == null)
{
if (Duplicator.TypesToBeDuplicated[currentType.UniqueKey] == null)
{
Duplicator.FindTypesToBeDuplicated(new TypeNodeList(currentType));
}
Trace("COPYOOB: type to be duplicated {0}", currentType.FullName);
}
else
{
if (HelperMethods.IsContractTypeForSomeOtherType(currentType as Class))
{
// dummy contract target type. Ignore it.
targetType.Members = new MemberList();
targetType.ClearMemberTable();
}
Contract.Assume(TemplateParameterCount(currentType) == TemplateParameterCount(targetType),
"Name mangling should ensure this");
Duplicator.DuplicateFor[currentType.UniqueKey] = targetType;
Trace("COPYOOB: forwarding {1} to {0}", currentType.FullName, targetType.FullName);
FuzzilyForwardType(currentType, targetType);
}
}
}
[Pure]
private static int TemplateParameterCount(TypeNode type)
{
Contract.Requires(type != null);
Contract.Ensures(type.TemplateParameters != null || Contract.Result<int>() == 0);
return type.TemplateParameters == null ? 0 : type.TemplateParameters.Count;
}
[Pure]
private static int TemplateParameterCount(Method method)
{
Contract.Requires(method != null);
Contract.Ensures(method.TemplateParameters != null || Contract.Result<int>() == 0);
return method.TemplateParameters == null ? 0 : method.TemplateParameters.Count;
}
private void FuzzilyForwardType(TypeNode currentType, TypeNode targetType)
{
// forward any type parameters that the type has
Contract.Requires(currentType != null);
Contract.Requires(targetType != null);
Contract.Requires(TemplateParameterCount(currentType) == TemplateParameterCount(targetType));
for (int j = 0, m = TemplateParameterCount(currentType); j < m; j++)
{
Contract.Assert(TemplateParameterCount(targetType) > 0);
TypeNode currentTypeParameter = currentType.TemplateParameters[j];
if (currentTypeParameter == null) continue;
Duplicator.DuplicateFor[currentTypeParameter.UniqueKey] = targetType.TemplateParameters[j];
}
FuzzilyForwardTypeMembersFromSource2Target(currentType, targetType);
}
[ContractVerification(true)]
private void FuzzilyForwardTypeMembersFromSource2Target(TypeNode currentType, TypeNode targetType)
{
Contract.Requires(currentType != null);
Contract.Requires(targetType != null);
for (int j = 0, o = currentType.Members.Count; j < o; j++)
{
Member currentMember = currentType.Members[j];
if (currentMember == null) continue;
Member existingMember = FuzzilyGetMatchingMember(targetType, currentMember);
if (existingMember != null)
{
FuzzilyForwardTypeMemberFromSource2Target(targetType, currentMember, existingMember);
}
else
{
this.toBeDuplicatedMembers.Add(new KeyValuePair<Member, TypeNode>(currentMember, targetType));
// For types, prepare a bit more.
var nestedType = currentMember as TypeNode;
if (nestedType != null)
{
if (Duplicator.TypesToBeDuplicated[nestedType.UniqueKey] == null)
{
Duplicator.FindTypesToBeDuplicated(new TypeNodeList(nestedType));
}
}
}
}
}
private void FuzzilyForwardTypeMemberFromSource2Target(TypeNode targetType, Member currentMember,
Member existingMember)
{
Contract.Requires(targetType != null);
Contract.Requires(currentMember != null);
Contract.Requires(existingMember != null);
Trace("COPYOOB: Forwarding member {0} to {1}", currentMember.FullName, existingMember.FullName);
Duplicator.DuplicateFor[currentMember.UniqueKey] = existingMember;
Method method = currentMember as Method;
if (method != null)
{
Method existingMethod = (Method) existingMember;
Contract.Assume(TemplateParameterCount(method) == TemplateParameterCount(existingMethod));
// forward any type parameters that the method has
for (int i = 0, n = TemplateParameterCount(method); i < n; i++)
{
Contract.Assert(TemplateParameterCount(existingMethod) > 0);
TypeNode currentTypeParameter = method.TemplateParameters[i];
if (currentTypeParameter == null) continue;
Duplicator.DuplicateFor[currentTypeParameter.UniqueKey] = existingMethod.TemplateParameters[i];
}
}
TypeNode currentNested = currentMember as TypeNode;
TypeNode targetNested = existingMember as TypeNode;
if (currentNested != null)
{
Contract.Assume(targetNested != null);
Contract.Assume(TemplateParameterCount(currentNested) == TemplateParameterCount(targetNested),
"should be true by mangled name matching");
FuzzilyForwardType(currentNested, targetNested);
}
}
/// <summary>
/// Visiting a method in the shadow assembly
/// </summary>
public override void VisitMethod(Method method)
{
if (method == null) return;
// we might have copied this method already
if (this.duplicatedMembers[method.UniqueKey] != null)
{
return;
}
Method targetMethod = method.FindShadow(this.targetAssembly);
if (targetMethod != null)
{
Contract.Assume(targetMethod.ParameterCount == method.ParameterCount);
for (int i = 0, n = method.ParameterCount; i < n; i++)
{
Contract.Assert(targetMethod.ParameterCount > 0);
var parameter = method.Parameters[i];
if (parameter == null) continue;
this.outOfBandDuplicator.DuplicateFor[parameter.UniqueKey] = targetMethod.Parameters[i];
}
CopyAttributesWithoutDuplicateUnlessAllowMultiple(targetMethod, method);
CopyReturnAttributesWithoutDuplicateUnlessAllowMultiple(targetMethod, method);
targetMethod.SetDelayedContract((m, dummy) =>
{
var savedMethod = this.outOfBandDuplicator.TargetMethod;
this.outOfBandDuplicator.TargetMethod = method;
this.outOfBandDuplicator.TargetType = method.DeclaringType;
Contract.Assume(method.DeclaringType != null);
this.outOfBandDuplicator.TargetModule = method.DeclaringType.DeclaringModule;
MethodContract mc = this.outOfBandDuplicator.VisitMethodContract(method.Contract);
targetMethod.Contract = mc;
if (savedMethod != null)
{
this.outOfBandDuplicator.TargetMethod = savedMethod;
this.outOfBandDuplicator.TargetType = savedMethod.DeclaringType;
}
});
}
}
public override void VisitTypeNode(TypeNode typeNode)
{
if (typeNode == null) return;
// we might have copied this type already
if (this.duplicatedMembers[typeNode.UniqueKey] != null)
{
return;
}
TypeNode targetType = typeNode.FindShadow(this.targetAssembly);
if (targetType != null)
{
if (targetType.Contract == null)
{
targetType.Contract = new TypeContract(targetType, true);
}
this.outOfBandDuplicator.TargetType = targetType;
if (typeNode.Contract != null)
{
InvariantList duplicatedInvariants =
this.outOfBandDuplicator.VisitInvariantList(typeNode.Contract.Invariants);
targetType.Contract.Invariants = duplicatedInvariants;
}
CopyAttributesWithoutDuplicateUnlessAllowMultiple(targetType, typeNode);
base.VisitTypeNode(typeNode);
}
else
{
// target type does not exist. Copy it
if (typeNode.DeclaringType != null)
{
// nested types are members and have been handled by CopyMissingMembers
}
else
{
this.outOfBandDuplicator.VisitTypeNode(typeNode);
}
}
}
private void CopyAttributesWithoutDuplicateUnlessAllowMultiple(Member targetMember, Member sourceMember)
{
Contract.Requires(targetMember != null);
Contract.Requires(sourceMember != null);
// if (sourceMember.Attributes == null) return;
// if (targetMember.Attributes == null) targetMember.Attributes = new AttributeList();
var attrs = this.outOfBandDuplicator.VisitAttributeList(sourceMember.Attributes);
Contract.Assume(attrs != null, "We fail to specialize the ensures");
foreach (var a in attrs)
{
if (a == null) continue;
// Can't look at a.Type because that doesn't get visited by the VisitAttributeList above
// (Seems like a bug in the StandardVisitor...)
TypeNode typeOfA = AttributeType(a);
if (!a.AllowMultiple && targetMember.GetAttribute(typeOfA) != null)
{
continue;
}
targetMember.Attributes.Add(a);
}
}
private static TypeNode AttributeType(AttributeNode a)
{
Contract.Requires(a != null);
var ctor = a.Constructor as MemberBinding;
if (ctor == null) return null;
var mb = ctor.BoundMember;
if (mb == null) return null;
return mb.DeclaringType;
}
private void CopyReturnAttributesWithoutDuplicateUnlessAllowMultiple(Method targetMember, Method sourceMember)
{
Contract.Requires(sourceMember != null);
Contract.Requires(targetMember != null);
if (sourceMember.ReturnAttributes == null) return;
if (targetMember.ReturnAttributes == null) targetMember.ReturnAttributes = new AttributeList();
var attrs = this.outOfBandDuplicator.VisitAttributeList(sourceMember.ReturnAttributes);
Contract.Assume(attrs != null, "We fail to specialize the ensures");
foreach (var a in attrs)
{
if (a == null) continue;
// Can't look at a.Type because that doesn't get visited by the VisitAttributeList above
// (Seems like a bug in the StandardVisitor...)
TypeNode typeOfA = AttributeType(a);
if (!a.AllowMultiple && HasAttribute(targetMember.ReturnAttributes, typeOfA))
{
continue;
}
targetMember.ReturnAttributes.Add(a);
}
}
private static bool HasAttribute(AttributeList attributes, TypeNode attributeType)
{
if (attributeType == null) return false;
if (attributes == null) return false;
for (int i = 0, n = attributes.Count; i < n; i++)
{
AttributeNode attr = attributes[i];
if (attr == null) continue;
MemberBinding mb = attr.Constructor as MemberBinding;
if (mb != null)
{
if (mb.BoundMember == null) continue;
if (mb.BoundMember.DeclaringType != attributeType) continue;
return true;
}
Literal lit = attr.Constructor as Literal;
if (lit == null) continue;
if ((lit.Value as TypeNode) != attributeType) continue;
return true;
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Tests
{
public static partial class TimeZoneInfoTests
{
[Fact]
public static void ClearCachedData()
{
TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(s_strSydney);
TimeZoneInfo local = TimeZoneInfo.Local;
TimeZoneInfo.ClearCachedData();
Assert.ThrowsAny<ArgumentException>(() =>
{
TimeZoneInfo.ConvertTime(DateTime.Now, local, cst);
});
}
[Fact]
public static void ConvertTime_DateTimeOffset_NullDestination_ArgumentNullException()
{
DateTimeOffset time1 = new DateTimeOffset(2006, 5, 12, 0, 0, 0, TimeSpan.Zero);
VerifyConvertException<ArgumentNullException>(time1, null);
}
public static IEnumerable<object[]> ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException_MemberData()
{
yield return new object[] { string.Empty };
yield return new object[] { " " };
yield return new object[] { "\0" };
yield return new object[] { s_strPacific.Substring(0, s_strPacific.Length / 2) }; // whole string must match
yield return new object[] { s_strPacific + " Zone" }; // no extra characters
yield return new object[] { " " + s_strPacific }; // no leading space
yield return new object[] { s_strPacific + " " }; // no trailing space
yield return new object[] { "\0" + s_strPacific }; // no leading null
yield return new object[] { s_strPacific + "\0" }; // no trailing null
yield return new object[] { s_strPacific + "\\ " }; // no trailing null
yield return new object[] { s_strPacific + "\\Display" };
yield return new object[] { s_strPacific + "\n" }; // no trailing newline
yield return new object[] { new string('a', 100) }; // long string
}
[Theory]
[MemberData(nameof(ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException_MemberData))]
public static void ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException(string destinationId)
{
DateTimeOffset time1 = new DateTimeOffset(2006, 5, 12, 0, 0, 0, TimeSpan.Zero);
VerifyConvertException<TimeZoneNotFoundException>(time1, destinationId);
}
[Fact]
public static void ConvertTimeFromUtc()
{
// destination timezone is null
Assert.Throws<ArgumentNullException>(() =>
{
DateTime dt = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2007, 5, 3, 11, 8, 0), null);
});
// destination timezone is UTC
DateTime now = DateTime.UtcNow;
DateTime convertedNow = TimeZoneInfo.ConvertTimeFromUtc(now, TimeZoneInfo.Utc);
Assert.Equal(now, convertedNow);
}
[Fact]
public static void ConvertTimeToUtc()
{
// null source
VerifyConvertToUtcException<ArgumentNullException>(new DateTime(2007, 5, 3, 12, 16, 0), null);
TimeZoneInfo london = CreateCustomLondonTimeZone();
// invalid DateTime
DateTime invalidDate = new DateTime(2007, 3, 25, 1, 30, 0);
VerifyConvertToUtcException<ArgumentException>(invalidDate, london);
// DateTimeKind and source types don't match
VerifyConvertToUtcException<ArgumentException>(new DateTime(2007, 5, 3, 12, 8, 0, DateTimeKind.Utc), london);
// correct UTC conversion
DateTime date = new DateTime(2007, 01, 01, 0, 0, 0);
Assert.Equal(date.ToUniversalTime(), TimeZoneInfo.ConvertTimeToUtc(date));
}
[Fact]
public static void ConvertTimeFromToUtc()
{
TimeZoneInfo london = CreateCustomLondonTimeZone();
DateTime utc = DateTime.UtcNow;
Assert.Equal(DateTimeKind.Utc, utc.Kind);
DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Utc);
Assert.Equal(DateTimeKind.Utc, converted.Kind);
DateTime back = TimeZoneInfo.ConvertTimeToUtc(converted, TimeZoneInfo.Utc);
Assert.Equal(DateTimeKind.Utc, back.Kind);
Assert.Equal(utc, back);
converted = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Local);
DateTimeKind expectedKind = (TimeZoneInfo.Local == TimeZoneInfo.Utc) ? DateTimeKind.Utc : DateTimeKind.Local;
Assert.Equal(expectedKind, converted.Kind);
back = TimeZoneInfo.ConvertTimeToUtc(converted, TimeZoneInfo.Local);
Assert.Equal(back.Kind, DateTimeKind.Utc);
Assert.Equal(utc, back);
}
[Fact]
[PlatformSpecific(Xunit.PlatformID.AnyUnix)]
public static void ConvertTimeFromToUtc_UnixOnly()
{
// DateTime Kind is Local
Assert.ThrowsAny<ArgumentException>(() =>
{
DateTime dt = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2007, 5, 3, 11, 8, 0, DateTimeKind.Local), TimeZoneInfo.Local);
});
TimeZoneInfo london = CreateCustomLondonTimeZone();
// winter (no DST)
DateTime winter = new DateTime(2007, 12, 25, 12, 0, 0);
DateTime convertedWinter = TimeZoneInfo.ConvertTimeFromUtc(winter, london);
Assert.Equal(winter, convertedWinter);
// summer (DST)
DateTime summer = new DateTime(2007, 06, 01, 12, 0, 0);
DateTime convertedSummer = TimeZoneInfo.ConvertTimeFromUtc(summer, london);
Assert.Equal(summer + new TimeSpan(1, 0, 0), convertedSummer);
// Kind and source types don't match
VerifyConvertToUtcException<ArgumentException>(new DateTime(2007, 5, 3, 12, 8, 0, DateTimeKind.Local), london);
// convert to London time and back
DateTime utc = DateTime.UtcNow;
Assert.Equal(DateTimeKind.Utc, utc.Kind);
DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utc, london);
Assert.Equal(converted.Kind, DateTimeKind.Unspecified);
DateTime back = TimeZoneInfo.ConvertTimeToUtc(converted, london);
Assert.Equal(back.Kind, DateTimeKind.Utc);
Assert.Equal(utc, back);
}
[Fact]
public static void CreateCustomTimeZone()
{
TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 3, 2, DayOfWeek.Sunday);
TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 2, DayOfWeek.Sunday);
TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(1, 0, 0), s1, e1);
// supports DST
TimeZoneInfo tz1 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1 });
Assert.True(tz1.SupportsDaylightSavingTime);
// doesn't support DST
TimeZoneInfo tz2 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(4, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1 }, true);
Assert.False(tz2.SupportsDaylightSavingTime);
TimeZoneInfo tz3 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(6, 0, 0), null, null, null, null);
Assert.False(tz3.SupportsDaylightSavingTime);
}
[Fact]
public static void CreateCustomTimeZone_Invalid()
{
VerifyCustomTimeZoneException<ArgumentNullException>(null, new TimeSpan(0), null, null); // null Id
VerifyCustomTimeZoneException<ArgumentException>("", new TimeSpan(0), null, null); // empty string Id
VerifyCustomTimeZoneException<ArgumentException>("mytimezone", new TimeSpan(0, 0, 55), null, null); // offset not minutes
VerifyCustomTimeZoneException<ArgumentException>("mytimezone", new TimeSpan(14, 1, 0), null, null); // offset too big
VerifyCustomTimeZoneException<ArgumentException>("mytimezone", - new TimeSpan(14, 1, 0), null, null); // offset too small
}
[Fact]
public static void CreateCustomTimeZone_InvalidTimeZone()
{
TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 3, 2, DayOfWeek.Sunday);
TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 2, DayOfWeek.Sunday);
TimeZoneInfo.TransitionTime s2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 2, 2, DayOfWeek.Sunday);
TimeZoneInfo.TransitionTime e2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 11, 2, DayOfWeek.Sunday);
TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(1, 0, 0), s1, e1);
// AdjustmentRules overlap
TimeZoneInfo.AdjustmentRule r2 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2004, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2);
VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1, r2 });
// AdjustmentRules not ordered
TimeZoneInfo.AdjustmentRule r3 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2006, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2);
VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r3, r1 });
// Offset out of range
TimeZoneInfo.AdjustmentRule r4 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(3, 0, 0), s1, e1);
VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(12, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r4 });
// overlapping AdjustmentRules for a date
TimeZoneInfo.AdjustmentRule r5 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2005, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2);
VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1, r5 });
// null AdjustmentRule
VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(12, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { null });
}
[Fact]
[PlatformSpecific(Xunit.PlatformID.AnyUnix)]
public static void HasSameRules_RomeAndVatican()
{
TimeZoneInfo rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
TimeZoneInfo vatican = TimeZoneInfo.FindSystemTimeZoneById("Europe/Vatican");
Assert.True(rome.HasSameRules(vatican));
}
[Fact]
public static void HasSameRules_NullAdjustmentRules()
{
TimeZoneInfo utc = TimeZoneInfo.Utc;
TimeZoneInfo custom = TimeZoneInfo.CreateCustomTimeZone("Custom", new TimeSpan(0), "Custom", "Custom");
Assert.True(utc.HasSameRules(custom));
}
private static TimeZoneInfo CreateCustomLondonTimeZone()
{
TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 1, 0, 0), 3, 5, DayOfWeek.Sunday);
TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday);
TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan(1, 0, 0), start, end);
return TimeZoneInfo.CreateCustomTimeZone("Europe/London", new TimeSpan(0), "Europe/London", "British Standard Time", "British Summer Time", new TimeZoneInfo.AdjustmentRule[] { rule });
}
private static void VerifyConvertToUtcException<EXCTYPE>(DateTime dateTime, TimeZoneInfo sourceTimeZone) where EXCTYPE : Exception
{
Assert.ThrowsAny<EXCTYPE>(() =>
{
DateTime dt = TimeZoneInfo.ConvertTimeToUtc(dateTime, sourceTimeZone);
});
}
private static void VerifyCustomTimeZoneException<ExceptionType>(string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName = null, TimeZoneInfo.AdjustmentRule[] adjustmentRules = null) where ExceptionType : Exception
{
Assert.ThrowsAny<ExceptionType>(() =>
{
if (daylightDisplayName == null && adjustmentRules == null)
{
TimeZoneInfo tz = TimeZoneInfo.CreateCustomTimeZone(id, baseUtcOffset, displayName, standardDisplayName);
}
else
{
TimeZoneInfo tz = TimeZoneInfo.CreateCustomTimeZone(id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules);
}
});
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using ga = Google.Api;
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Logging.V2.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedLoggingServiceV2ClientTest
{
[xunit::FactAttribute]
public void DeleteLogRequestObject()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
DeleteLogRequest request = new DeleteLogRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteLog(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
client.DeleteLog(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteLogRequestObjectAsync()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
DeleteLogRequest request = new DeleteLogRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteLogAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
await client.DeleteLogAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteLogAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteLog()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
DeleteLogRequest request = new DeleteLogRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteLog(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
client.DeleteLog(request.LogName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteLogAsync()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
DeleteLogRequest request = new DeleteLogRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteLogAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
await client.DeleteLogAsync(request.LogName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteLogAsync(request.LogName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteLogResourceNames()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
DeleteLogRequest request = new DeleteLogRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteLog(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
client.DeleteLog(request.LogNameAsLogName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteLogResourceNamesAsync()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
DeleteLogRequest request = new DeleteLogRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteLogAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
await client.DeleteLogAsync(request.LogNameAsLogName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteLogAsync(request.LogNameAsLogName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void WriteLogEntriesRequestObject()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
WriteLogEntriesRequest request = new WriteLogEntriesRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
Resource = new ga::MonitoredResource(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Entries = { new LogEntry(), },
PartialSuccess = false,
DryRun = true,
};
WriteLogEntriesResponse expectedResponse = new WriteLogEntriesResponse { };
mockGrpcClient.Setup(x => x.WriteLogEntries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
WriteLogEntriesResponse response = client.WriteLogEntries(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task WriteLogEntriesRequestObjectAsync()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
WriteLogEntriesRequest request = new WriteLogEntriesRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
Resource = new ga::MonitoredResource(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Entries = { new LogEntry(), },
PartialSuccess = false,
DryRun = true,
};
WriteLogEntriesResponse expectedResponse = new WriteLogEntriesResponse { };
mockGrpcClient.Setup(x => x.WriteLogEntriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WriteLogEntriesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
WriteLogEntriesResponse responseCallSettings = await client.WriteLogEntriesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WriteLogEntriesResponse responseCancellationToken = await client.WriteLogEntriesAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void WriteLogEntries()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
WriteLogEntriesRequest request = new WriteLogEntriesRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
Resource = new ga::MonitoredResource(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Entries = { new LogEntry(), },
};
WriteLogEntriesResponse expectedResponse = new WriteLogEntriesResponse { };
mockGrpcClient.Setup(x => x.WriteLogEntries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
WriteLogEntriesResponse response = client.WriteLogEntries(request.LogName, request.Resource, request.Labels, request.Entries);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task WriteLogEntriesAsync()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
WriteLogEntriesRequest request = new WriteLogEntriesRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
Resource = new ga::MonitoredResource(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Entries = { new LogEntry(), },
};
WriteLogEntriesResponse expectedResponse = new WriteLogEntriesResponse { };
mockGrpcClient.Setup(x => x.WriteLogEntriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WriteLogEntriesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
WriteLogEntriesResponse responseCallSettings = await client.WriteLogEntriesAsync(request.LogName, request.Resource, request.Labels, request.Entries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WriteLogEntriesResponse responseCancellationToken = await client.WriteLogEntriesAsync(request.LogName, request.Resource, request.Labels, request.Entries, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void WriteLogEntriesResourceNames()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
WriteLogEntriesRequest request = new WriteLogEntriesRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
Resource = new ga::MonitoredResource(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Entries = { new LogEntry(), },
};
WriteLogEntriesResponse expectedResponse = new WriteLogEntriesResponse { };
mockGrpcClient.Setup(x => x.WriteLogEntries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
WriteLogEntriesResponse response = client.WriteLogEntries(request.LogNameAsLogName, request.Resource, request.Labels, request.Entries);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task WriteLogEntriesResourceNamesAsync()
{
moq::Mock<LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock<LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict);
WriteLogEntriesRequest request = new WriteLogEntriesRequest
{
LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"),
Resource = new ga::MonitoredResource(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Entries = { new LogEntry(), },
};
WriteLogEntriesResponse expectedResponse = new WriteLogEntriesResponse { };
mockGrpcClient.Setup(x => x.WriteLogEntriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WriteLogEntriesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null);
WriteLogEntriesResponse responseCallSettings = await client.WriteLogEntriesAsync(request.LogNameAsLogName, request.Resource, request.Labels, request.Entries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WriteLogEntriesResponse responseCancellationToken = await client.WriteLogEntriesAsync(request.LogNameAsLogName, request.Resource, request.Labels, request.Entries, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Transports.Msmq
{
using System;
using System.Collections.Generic;
using System.Messaging;
using System.Security.Principal;
using Exceptions;
using Logging;
public class MsmqEndpointManagement :
IEndpointManagement
{
static readonly string AdministratorsGroupName;
static readonly string AnonymousLoginAccountName;
static readonly string EveryoneAccountName;
static readonly ILog _log = Logger.Get(typeof (MsmqEndpointManagement));
readonly IMsmqEndpointAddress _address;
static MsmqEndpointManagement()
{
// WellKnowSidType.WorldSid == "Everyone";
// whoda thunk (http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/0737f978-a998-453d-9a6a-c348285d7ea3/)
AdministratorsGroupName = (new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null))
.Translate(typeof (NTAccount)).ToString();
EveryoneAccountName = (new SecurityIdentifier(WellKnownSidType.WorldSid, null))
.Translate(typeof (NTAccount)).ToString();
AnonymousLoginAccountName = (new SecurityIdentifier(WellKnownSidType.AnonymousSid, null))
.Translate(typeof (NTAccount)).ToString();
}
MsmqEndpointManagement(IEndpointAddress address)
{
_address = address as MsmqEndpointAddress ?? new MsmqEndpointAddress(address.Uri);
}
public void Create(bool transactional)
{
if (!_address.IsLocal)
throw new InvalidOperationException("A remote queue cannot be created: " + _address);
if (CheckForExistingQueue(transactional))
return;
using (MessageQueue queue = MessageQueue.Create(_address.LocalName, transactional))
{
_log.Debug("A queue was created: " + _address + (transactional ? " (transactional)" : ""));
queue.SetPermissions(AdministratorsGroupName, MessageQueueAccessRights.FullControl,
AccessControlEntryType.Allow);
queue.SetPermissions(EveryoneAccountName, MessageQueueAccessRights.GenericWrite,
AccessControlEntryType.Allow);
queue.SetPermissions(AnonymousLoginAccountName, MessageQueueAccessRights.GenericWrite,
AccessControlEntryType.Allow);
}
VerifyQueueSendAndReceive();
}
public long Count()
{
return Count(long.MaxValue);
}
public long Count(long limit)
{
long count = 0;
using (var queue = new MessageQueue(_address.InboundFormatName, QueueAccessMode.Receive))
{
using (MessageEnumerator enumerator = queue.GetMessageEnumerator2())
{
while (enumerator.MoveNext(TimeSpan.Zero))
{
if (++count >= limit)
break;
}
}
}
return count;
}
public void Purge()
{
using (var queue = new MessageQueue(_address.LocalName, QueueAccessMode.ReceiveAndAdmin))
{
queue.Purge();
}
}
public bool Exists
{
get { return MessageQueue.Exists(_address.LocalName); }
}
public bool IsTransactional
{
get
{
if (!_address.IsLocal)
return true;
using (var queue = new MessageQueue(_address.InboundFormatName, QueueAccessMode.ReceiveAndAdmin))
{
return queue.Transactional;
}
}
}
public Dictionary<string, int> MessageTypes()
{
var dict = new Dictionary<string, int>();
using (var queue = new MessageQueue(_address.InboundFormatName, QueueAccessMode.Receive))
{
using (MessageEnumerator enumerator = queue.GetMessageEnumerator2())
{
while (enumerator.MoveNext(TimeSpan.Zero))
{
Message q = enumerator.Current;
if (!dict.ContainsKey(q.Label))
dict.Add(q.Label, 0);
dict[q.Label]++;
}
}
}
return dict;
}
void VerifyQueueSendAndReceive()
{
using (var queue = new MessageQueue(_address.InboundFormatName, QueueAccessMode.SendAndReceive))
{
if (!queue.CanRead)
throw new InvalidOperationException("A queue was created but cannot be read: " + _address);
if (!queue.CanWrite)
throw new InvalidOperationException("A queue was created but cannot be written: " + _address);
}
}
bool CheckForExistingQueue(bool transactional)
{
if (!MessageQueue.Exists(_address.LocalName))
return false;
using (var queue = new MessageQueue(_address.InboundFormatName, QueueAccessMode.ReceiveAndAdmin))
{
if (transactional && !queue.Transactional)
{
throw new InvalidOperationException(
"A non-transactional queue already exists with the same name: " + _address);
}
if (!transactional && queue.Transactional)
{
throw new InvalidOperationException("A transactional queue already exists with the same name: " +
_address);
}
}
_log.Debug("The queue already exists: " + _address);
return true;
}
public static void Manage(IEndpointAddress address, Action<IEndpointManagement> action)
{
try
{
var management = new MsmqEndpointManagement(address);
action(management);
}
catch (EndpointException)
{
throw;
}
catch (Exception ex)
{
throw new TransportException(address.Uri, "There was a problem managing the transport", ex);
}
}
public static IEndpointManagement New(Uri uri)
{
try
{
var address = new MsmqEndpointAddress(uri);
return New(address);
}
catch (UriFormatException ex)
{
throw new EndpointException(uri, "The MSMQ queue address is invalid.", ex);
}
}
public static IEndpointManagement New(IEndpointAddress address)
{
return new MsmqEndpointManagement(address);
}
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Linq.Expressions;
namespace Lambda2Js.Tests
{
[TestClass]
public class EnumTests
{
[TestMethod]
public void EnumAsInteger0()
{
Expression<Func<SomeFlagsEnum>> expr = () => 0;
var js = expr.CompileToJavascript(new JavascriptCompilationOptions(JsCompilationFlags.BodyOnly));
Assert.AreEqual(@"0", js);
}
[TestMethod]
public void EnumAsInteger1()
{
Expression<Func<SomeFlagsEnum>> expr = () => SomeFlagsEnum.A;
var js = expr.CompileToJavascript(new JavascriptCompilationOptions(JsCompilationFlags.BodyOnly));
Assert.AreEqual(@"1", js);
}
[TestMethod]
public void EnumCompareAsInteger0()
{
Expression<Func<MyClassWithEnum, bool>> expr = o => o.SomeFlagsEnum == 0;
var js = expr.CompileToJavascript();
Assert.AreEqual(@"SomeFlagsEnum===0", js);
}
[TestMethod]
public void EnumCompareAsInteger1()
{
Expression<Func<MyClassWithEnum, bool>> expr = o => o.SomeFlagsEnum == SomeFlagsEnum.A;
var js = expr.CompileToJavascript();
Assert.AreEqual(@"SomeFlagsEnum===1", js);
}
[TestMethod]
public void EnumCompareAsInteger2()
{
Expression<Func<MyClassWithEnum, bool>> expr = o => o.SomeFlagsEnum == (SomeFlagsEnum.A | SomeFlagsEnum.B);
var js = expr.CompileToJavascript();
Assert.AreEqual(@"SomeFlagsEnum===3", js);
}
[TestMethod]
public void EnumCompareWithEnclosed()
{
SomeFlagsEnum enclosed = SomeFlagsEnum.B;
Expression<Func<MyClassWithEnum, bool>> expr = o => o.SomeFlagsEnum == (SomeFlagsEnum.A ^ ~enclosed);
var js = expr.CompileToJavascript();
Assert.AreEqual(@"SomeFlagsEnum===(1^~2)", js);
}
[TestMethod]
public void EnumCallWithEnumParam()
{
Expression<Action<MyClassWithEnum>> expr = o => o.SetGender(SomeFlagsEnum.B);
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new MyCustomClassEnumMethods()));
Assert.AreEqual(@"o.SetGender(2)", js);
}
[TestMethod]
public void EnumCallWithEnumParam2()
{
Expression<Action<MyClassWithEnum>> expr = o => o.SetGender(SomeFlagsEnum.A | SomeFlagsEnum.B);
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new MyCustomClassEnumMethods()));
Assert.AreEqual(@"o.SetGender(3)", js);
}
[TestMethod]
public void EnumAsString0()
{
Expression<Func<SomeFlagsEnum>> expr = () => 0;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new EnumConversionExtension(EnumOptions.UseStrings)));
Assert.AreEqual(@"""""", js);
}
[TestMethod]
public void EnumAsString1()
{
Expression<Func<SomeFlagsEnum>> expr = () => SomeFlagsEnum.A;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new EnumConversionExtension(EnumOptions.UseStrings)));
Assert.AreEqual(@"""A""", js);
}
[TestMethod]
public void EnumAsString2()
{
Expression<Func<SomeFlagsEnum>> expr = () => SomeFlagsEnum.A | SomeFlagsEnum.B;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new EnumConversionExtension(EnumOptions.FlagsAsStringWithSeparator | EnumOptions.UseStrings)));
Assert.AreEqual(@"""B|A""", js);
}
[TestMethod]
public void EnumAsString3()
{
Expression<Func<SomeStrangeFlagsEnum>> expr = () => SomeStrangeFlagsEnum.A | SomeStrangeFlagsEnum.B;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new EnumConversionExtension(EnumOptions.FlagsAsStringWithSeparator | EnumOptions.UseStrings)));
Assert.AreEqual(@"""C|1""", js);
}
[TestMethod]
public void EnumAsArrayOfStrings0()
{
Expression<Func<SomeFlagsEnum>> expr = () => 0;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new EnumConversionExtension(EnumOptions.FlagsAsArray | EnumOptions.UseStrings)));
Assert.AreEqual(@"[]", js);
}
[TestMethod]
public void EnumAsArrayOfStrings1()
{
Expression<Func<SomeFlagsEnum>> expr = () => SomeFlagsEnum.A;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new EnumConversionExtension(EnumOptions.FlagsAsArray | EnumOptions.UseStrings)));
Assert.AreEqual(@"[""A""]", js);
}
[TestMethod]
public void EnumAsArrayOfStrings2()
{
Expression<Func<SomeFlagsEnum>> expr = () => SomeFlagsEnum.A | SomeFlagsEnum.B;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new EnumConversionExtension(EnumOptions.FlagsAsArray | EnumOptions.UseStrings)));
Assert.AreEqual(@"[""B"",""A""]", js);
}
[TestMethod]
public void EnumAsStringEquals()
{
Expression<Func<MyClassWithEnum, bool>> expr = doc => doc.SomeFlagsEnum == SomeFlagsEnum.B;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new EnumConversionExtension(EnumOptions.UseStrings)));
Assert.AreEqual(@"doc.SomeFlagsEnum===""B""", js);
}
[TestMethod]
public void EnumAsStringNotEquals()
{
Expression<Func<MyClassWithEnum, bool>> expr = doc => doc.SomeFlagsEnum != SomeFlagsEnum.B;
var js = expr.CompileToJavascript(
new JavascriptCompilationOptions(
JsCompilationFlags.BodyOnly,
new EnumConversionExtension(EnumOptions.UseStrings)));
Assert.AreEqual(@"doc.SomeFlagsEnum!==""B""", js);
}
}
public class MyCustomClassEnumMethods : JavascriptConversionExtension
{
public override void ConvertToJavascript(JavascriptConversionContext context)
{
var methodCall = context.Node as MethodCallExpression;
if (methodCall != null)
if (methodCall.Method.DeclaringType == typeof(MyClassWithEnum))
{
switch (methodCall.Method.Name)
{
case "SetGender":
{
context.PreventDefault();
using (context.Operation(JavascriptOperationTypes.Call))
{
using (context.Operation(JavascriptOperationTypes.IndexerProperty))
{
context.WriteNode(methodCall.Object);
context.WriteAccessor("SetGender");
}
context.WriteManyIsolated('(', ')', ',', methodCall.Arguments);
}
return;
}
}
}
}
}
class MyClassWithEnum : MyClass
{
public SomeFlagsEnum SomeFlagsEnum { get; }
public SomeLongEnum SomeLongEnum { get; }
public SomeUnorderedFlagsEnum SomeUnorderedFlagsEnum { get; }
public void SetGender(SomeFlagsEnum someFlagsEnum) { }
}
[Flags]
enum SomeFlagsEnum
{
A = 1,
B = 2,
}
[Flags]
enum SomeStrangeFlagsEnum
{
A = 0x011,
B = 0x101,
C = 0x110,
}
enum SomeLongEnum : long
{
A = 1,
B = 2,
}
[Flags]
enum SomeUnorderedFlagsEnum
{
AB = 3,
A = 1,
B = 2,
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.ServiceAuth;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class GridServicesConnector : BaseServiceConnector, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
private ExpiringCache<ulong, GridRegion> m_regionCache =
new ExpiringCache<ulong, GridRegion>();
public GridServicesConnector()
{
}
public GridServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public GridServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[GRID CONNECTOR]: GridService missing from OpenSim.ini");
throw new Exception("Grid connector init error");
}
string serviceURI = gridConfig.GetString("GridServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[GRID CONNECTOR]: No Server URI named in section GridService");
throw new Exception("Grid connector init error");
}
m_ServerURI = serviceURI;
base.Initialise(source, "GridService");
}
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
Dictionary<string, object> rinfo = regionInfo.ToKeyValuePairs();
Dictionary<string, object> sendData = new Dictionary<string,object>();
foreach (KeyValuePair<string, object> kvp in rinfo)
sendData[kvp.Key] = (string)kvp.Value;
sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "register";
string reqString = ServerUtils.BuildQueryString(sendData);
string uri = m_ServerURI + "/grid";
// m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString);
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "success"))
{
return String.Empty;
}
else if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "failure"))
{
m_log.ErrorFormat(
"[GRID CONNECTOR]: Registration failed: {0} when contacting {1}", replyData["Message"], uri);
return replyData["Message"].ToString();
}
else if (!replyData.ContainsKey("Result"))
{
m_log.ErrorFormat(
"[GRID CONNECTOR]: reply data does not contain result field when contacting {0}", uri);
}
else
{
m_log.ErrorFormat(
"[GRID CONNECTOR]: unexpected result {0} when contacting {1}", replyData["Result"], uri);
return "Unexpected result " + replyData["Result"].ToString();
}
}
else
{
m_log.ErrorFormat(
"[GRID CONNECTOR]: RegisterRegion received null reply when contacting grid server at {0}", uri);
}
}
catch (Exception e)
{
m_log.ErrorFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
}
return string.Format("Error communicating with the grid service at {0}", uri);
}
public bool DeregisterRegion(UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "deregister";
string uri = m_ServerURI + "/grid";
try
{
string reply
= SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData["Result"] != null) && (replyData["Result"].ToString().ToLower() == "success"))
return true;
}
else
m_log.DebugFormat("[GRID CONNECTOR]: DeregisterRegion received null reply");
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
}
return false;
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_neighbours";
List<GridRegion> rinfos = new List<GridRegion>();
string reqString = ServerUtils.BuildQueryString(sendData);
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
//m_log.DebugFormat("[GRID CONNECTOR]: get neighbours returned {0} elements", rinfosList.Count);
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received null response",
scopeID, regionID);
return rinfos;
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_region_by_uuid";
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData), m_Auth);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
// scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID received null reply");
return rinfo;
}
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
GridRegion rinfo = null;
ulong regionHandle = Util.UIntsToLong((uint)x, (uint)y);
// this cache includes NULL regions
if (m_regionCache.TryGetValue(regionHandle, out rinfo))
return rinfo;
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["X"] = x.ToString();
sendData["Y"] = y.ToString();
sendData["METHOD"] = "get_region_by_position";
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), m_Auth);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return null;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received no region",
// scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received null response",
scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition received null reply");
m_regionCache.Add(regionHandle, rinfo, TimeSpan.FromSeconds(600));
return rinfo;
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["NAME"] = regionName;
sendData["METHOD"] = "get_region_by_name";
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), m_Auth);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1} received null response",
scopeID, regionName);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByName received null reply");
return rinfo;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["NAME"] = name;
sendData["MAX"] = maxNumber.ToString();
sendData["METHOD"] = "get_regions_by_name";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), m_Auth);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received null response",
scopeID, name, maxNumber);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName received null reply");
return rinfos;
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["XMIN"] = xmin.ToString();
sendData["XMAX"] = xmax.ToString();
sendData["YMIN"] = ymin.ToString();
sendData["YMAX"] = ymax.ToString();
sendData["METHOD"] = "get_region_range";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), m_Auth);
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange {0}, {1}-{2} {3}-{4} received null response",
scopeID, xmin, xmax, ymin, ymax);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange received null reply");
return rinfos;
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["METHOD"] = "get_default_regions";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), m_Auth);
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions {0} received null response",
scopeID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions received null reply");
return rinfos;
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["METHOD"] = "get_default_hypergrid_regions";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), m_Auth);
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultHypergridRegions {0} received null response",
scopeID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultHypergridRegions received null reply");
return rinfos;
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["X"] = x.ToString();
sendData["Y"] = y.ToString();
sendData["METHOD"] = "get_fallback_regions";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), m_Auth);
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions {0}, {1}-{2} received null response",
scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions received null reply");
return rinfos;
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["METHOD"] = "get_hyperlinks";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), m_Auth);
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks {0} received null response",
scopeID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks received null reply");
return rinfos;
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_region_flags";
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), m_Auth);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
return -1;
}
int flags = -1;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null))
{
Int32.TryParse((string)replyData["result"], out flags);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags {0}, {1} received wrong type {2}",
// scopeID, regionID, replyData["result"].GetType());
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags {0}, {1} received null response",
scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags received null reply");
return flags;
}
public Dictionary<string, object> GetExtraFeatures()
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
Dictionary<string, object> extraFeatures = new Dictionary<string, object>();
sendData["METHOD"] = "get_grid_extra_features";
string reply = string.Empty;
string uri = m_ServerURI + "/grid";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), m_Auth);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: GetExtraFeatures - Exception when contacting grid server at {0}: {1}", uri, e.Message);
return extraFeatures;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && replyData.Count > 0)
{
foreach (string key in replyData.Keys)
{
extraFeatures[key] = replyData[key].ToString();
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetExtraServiceURLs received null reply");
return extraFeatures;
}
#endregion
}
}
| |
/*
* 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.Threading;
using System.Collections.Generic;
using Apache.NMS.Stomp.Commands;
namespace Apache.NMS.Stomp.Util
{
public class MessageDispatchChannel
{
private readonly Mutex mutex = new Mutex();
private readonly ManualResetEvent waiter = new ManualResetEvent(false);
private bool closed;
private bool running;
private readonly LinkedList<MessageDispatch> channel = new LinkedList<MessageDispatch>();
public MessageDispatchChannel()
{
}
#region Properties
public object SyncRoot
{
get{ return this.mutex; }
}
public bool Closed
{
get
{
lock(this.mutex)
{
return this.closed;
}
}
set
{
lock(this.mutex)
{
this.closed = value;
}
}
}
public bool Running
{
get
{
lock(this.mutex)
{
return this.running;
}
}
set
{
lock(this.mutex)
{
this.running = value;
}
}
}
public bool Empty
{
get
{
lock(mutex)
{
return channel.Count == 0;
}
}
}
public long Count
{
get
{
lock(mutex)
{
return channel.Count;
}
}
}
#endregion
public void Start()
{
lock(this.mutex)
{
if(!Closed)
{
this.running = true;
this.waiter.Reset();
}
}
}
public void Stop()
{
lock(mutex)
{
this.running = false;
this.waiter.Set();
}
}
public void Close()
{
lock(mutex)
{
if(!Closed)
{
this.running = false;
this.closed = true;
}
this.waiter.Set();
}
}
public void Enqueue(MessageDispatch dispatch)
{
lock(this.mutex)
{
this.channel.AddLast(dispatch);
this.waiter.Set();
}
}
public void EnqueueFirst(MessageDispatch dispatch)
{
lock(this.mutex)
{
this.channel.AddFirst(dispatch);
this.waiter.Set();
}
}
public MessageDispatch Dequeue(TimeSpan timeout)
{
MessageDispatch result = null;
this.mutex.WaitOne();
// Wait until the channel is ready to deliver messages.
if( timeout != TimeSpan.Zero && !Closed && ( Empty || !Running ) )
{
// This isn't the greatest way to do this but to work on the
// .NETCF its the only solution I could find so far. This
// code will only really work for one Thread using the event
// channel to wait as all waiters are going to drop out of
// here regardless of the fact that only one message could
// be on the Queue.
this.waiter.Reset();
this.mutex.ReleaseMutex();
this.waiter.WaitOne((int)timeout.TotalMilliseconds, false);
this.mutex.WaitOne();
}
if( !Closed && Running && !Empty )
{
result = DequeueNoWait();
}
this.mutex.ReleaseMutex();
return result;
}
public MessageDispatch DequeueNoWait()
{
MessageDispatch result = null;
lock(this.mutex)
{
if( Closed || !Running || Empty )
{
return null;
}
result = channel.First.Value;
this.channel.RemoveFirst();
}
return result;
}
public MessageDispatch Peek()
{
lock(this.mutex)
{
if( Closed || !Running || Empty )
{
return null;
}
return channel.First.Value;
}
}
public void Clear()
{
lock(mutex)
{
this.channel.Clear();
}
}
public MessageDispatch[] RemoveAll()
{
MessageDispatch[] result;
lock(mutex)
{
result = new MessageDispatch[this.Count];
channel.CopyTo(result, 0);
channel.Clear();
}
return result;
}
}
}
| |
//-----------------------------------------------------------------------------
// MainForm.Designer.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace TrueTypeConverter
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.FontName = new System.Windows.Forms.ComboBox();
this.FontStyle = new System.Windows.Forms.ComboBox();
this.FontSize = new System.Windows.Forms.ComboBox();
this.Antialias = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.Sample = new System.Windows.Forms.Label();
this.Export = new System.Windows.Forms.Button();
this.MaxChar = new System.Windows.Forms.TextBox();
this.MinChar = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// FontName
//
this.FontName.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.FontName.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.FontName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple;
this.FontName.FormattingEnabled = true;
this.FontName.Location = new System.Drawing.Point(15, 30);
this.FontName.Name = "FontName";
this.FontName.Size = new System.Drawing.Size(189, 176);
this.FontName.TabIndex = 1;
this.FontName.SelectedIndexChanged += new System.EventHandler(this.FontName_SelectedIndexChanged);
//
// FontStyle
//
this.FontStyle.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.FontStyle.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.FontStyle.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple;
this.FontStyle.FormattingEnabled = true;
this.FontStyle.Items.AddRange(new object[] {
"Regular",
"Italic",
"Bold",
"Bold, Italic"});
this.FontStyle.Location = new System.Drawing.Point(218, 30);
this.FontStyle.Name = "FontStyle";
this.FontStyle.Size = new System.Drawing.Size(80, 176);
this.FontStyle.TabIndex = 3;
this.FontStyle.Text = "Regular";
this.FontStyle.SelectedIndexChanged += new System.EventHandler(this.FontStyle_SelectedIndexChanged);
//
// FontSize
//
this.FontSize.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple;
this.FontSize.FormattingEnabled = true;
this.FontSize.Items.AddRange(new object[] {
"8",
"9",
"10",
"11",
"12",
"14",
"16",
"18",
"20",
"22",
"23",
"24",
"26",
"28",
"36",
"48",
"72"});
this.FontSize.Location = new System.Drawing.Point(312, 30);
this.FontSize.Name = "FontSize";
this.FontSize.Size = new System.Drawing.Size(49, 176);
this.FontSize.TabIndex = 5;
this.FontSize.Text = "23";
this.FontSize.SelectedIndexChanged += new System.EventHandler(this.FontSize_SelectedIndexChanged);
this.FontSize.TextUpdate += new System.EventHandler(this.FontSize_TextUpdate);
//
// Antialias
//
this.Antialias.AutoSize = true;
this.Antialias.Checked = true;
this.Antialias.CheckState = System.Windows.Forms.CheckState.Checked;
this.Antialias.Location = new System.Drawing.Point(182, 234);
this.Antialias.Name = "Antialias";
this.Antialias.Size = new System.Drawing.Size(77, 17);
this.Antialias.TabIndex = 10;
this.Antialias.Text = "&Antialiased";
this.Antialias.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 215);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(51, 13);
this.label1.TabIndex = 6;
this.label1.Text = "M&in char:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(215, 14);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(55, 13);
this.label2.TabIndex = 2;
this.label2.Text = "Font s&tyle:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(310, 14);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(30, 13);
this.label3.TabIndex = 4;
this.label3.Text = "&Size:";
//
// Sample
//
this.Sample.AutoEllipsis = true;
this.Sample.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Sample.Location = new System.Drawing.Point(12, 269);
this.Sample.Name = "Sample";
this.Sample.Size = new System.Drawing.Size(354, 172);
this.Sample.TabIndex = 12;
this.Sample.Text = "The quick brown fox jumped over the LAZY camel";
this.Sample.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// Export
//
this.Export.Location = new System.Drawing.Point(286, 228);
this.Export.Name = "Export";
this.Export.Size = new System.Drawing.Size(75, 23);
this.Export.TabIndex = 11;
this.Export.Text = "&Export";
this.Export.UseVisualStyleBackColor = true;
this.Export.Click += new System.EventHandler(this.Export_Click);
//
// MaxChar
//
this.MaxChar.Location = new System.Drawing.Point(97, 231);
this.MaxChar.Name = "MaxChar";
this.MaxChar.Size = new System.Drawing.Size(63, 20);
this.MaxChar.TabIndex = 9;
this.MaxChar.Text = "0x7F";
//
// MinChar
//
this.MinChar.Location = new System.Drawing.Point(15, 231);
this.MinChar.Name = "MinChar";
this.MinChar.Size = new System.Drawing.Size(63, 20);
this.MinChar.TabIndex = 7;
this.MinChar.Text = "0x20";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(94, 215);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(54, 13);
this.label4.TabIndex = 8;
this.label4.Text = "Ma&x char:";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(12, 14);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(31, 13);
this.label5.TabIndex = 0;
this.label5.Text = "&Font:";
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(378, 450);
this.Controls.Add(this.MinChar);
this.Controls.Add(this.MaxChar);
this.Controls.Add(this.Export);
this.Controls.Add(this.Sample);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label4);
this.Controls.Add(this.label5);
this.Controls.Add(this.label1);
this.Controls.Add(this.Antialias);
this.Controls.Add(this.FontSize);
this.Controls.Add(this.FontStyle);
this.Controls.Add(this.FontName);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MainForm";
this.Text = "ttf2bmp";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox FontName;
private System.Windows.Forms.ComboBox FontStyle;
private System.Windows.Forms.ComboBox FontSize;
private System.Windows.Forms.CheckBox Antialias;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label Sample;
private System.Windows.Forms.Button Export;
private System.Windows.Forms.TextBox MaxChar;
private System.Windows.Forms.TextBox MinChar;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
}
}
| |
using System;
using System.Reflection;
using System.Windows.Forms;
using System.Collections.Generic;
using Microsoft.Win32;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Extensibility;
using NetOffice;
using NetOffice.OfficeApi.Native;
using Office = NetOffice.OfficeApi;
using Excel = NetOffice.ExcelApi;
using Word = NetOffice.WordApi;
using Outlook = NetOffice.OutlookApi;
using PowerPoint = NetOffice.PowerPointApi;
using Access = NetOffice.AccessApi;
namespace NetOfficeSamples.SuperAddinCS2
{
/// <summary>
/// the addin class
/// </summary>
[Guid("39AA1CDE-F186-456B-ADF6-30D03352C131")]
[ProgId("NetOfficeSample.SuperAddinCS2.Addin")]
[ComVisible(true)]
public class Addin : IDTExtensibility2, IRibbonExtensibility
{
public const string ADDIN_TITLE = "NetOffice SuperAddin Sample";
private static readonly string _progId = "NetOfficeSample.SuperAddinCS2.Addin";
private static readonly string _addinFriendlyName = "NetOffice SuperAddin Sample (IDTExtensibility2)";
private static readonly string _addinDescription = "This IDTExtensibility2 addin shows how to register single addin class to multiple Microsoft Office products.";
#region Fields
private ICOMObject _application;
private string _hostApplicationName;
#endregion
#region IDTExtensibility2 Members
public void OnConnection(object Application, ext_ConnectMode ConnectMode, object AddInInst, ref Array custom)
{
try
{
_application = Core.Default.CreateObjectFromComProxy(null, Application, false);
/*
* _application is stored as COMObject the common base type for all reference types in NetOffice
* because this addin is loaded in different office application.
*
* with the CreateObjectFromComProxy method the _application instance is created as corresponding wrapper based on the com proxy type
*/
if (_application is Excel.Application)
_hostApplicationName = "Excel";
else if (_application is Word.Application)
_hostApplicationName = "Word";
else if (_application is Outlook.Application)
_hostApplicationName = "Outlook";
else if (_application is PowerPoint.Application)
_hostApplicationName = "PowerPoint";
else if (_application is Access.Application)
_hostApplicationName = "Access";
}
catch (Exception exception)
{
if(_hostApplicationName != null)
OfficeRegistry.LogErrorMessage(_hostApplicationName, _progId, "Error occured in OnConnection. ", exception);
}
}
public void OnDisconnection(ext_DisconnectMode RemoveMode, ref Array custom)
{
try
{
if (null != _application)
_application.Dispose();
}
catch (Exception exception)
{
OfficeRegistry.LogErrorMessage(_hostApplicationName, _progId, "Error occured in OnDisconnection. ", exception);
}
}
public void OnStartupComplete(ref Array custom)
{
}
public void OnAddInsUpdate(ref Array custom)
{
}
public void OnBeginShutdown(ref Array custom)
{
}
#endregion
#region IRibbonExtensibility Members
public string GetCustomUI(string RibbonID)
{
try
{
return ReadTextFileFromRessource("RibbonUI.xml");
}
catch (Exception exception)
{
OfficeRegistry.LogErrorMessage(_hostApplicationName, _progId, "Error occured in GetCustomUI. ", exception);
return "";
}
}
public void OnAction(Office.IRibbonControl control)
{
try
{
string appInfo = string.Format("\n\nHost application: {0}.{1}\nVersion: {2}",
TypeDescriptor.GetComponentName(_application.UnderlyingObject),
_application.UnderlyingTypeName,
Invoker.Default.PropertyGet(_application, "Version")
);
switch (control.Id)
{
case "customButton1":
MessageBox.Show("This is the first sample button. " + appInfo, ADDIN_TITLE, MessageBoxButtons.OK);
break;
case "customButton2":
MessageBox.Show("This is the second sample button. " + appInfo, ADDIN_TITLE, MessageBoxButtons.OK);
break;
case "btnAbout":
MessageBox.Show("Sample add-in using IDTExtensibility2 interface that is registered to multiple Microsoft Office applications.", ADDIN_TITLE, MessageBoxButtons.OK);
break;
default:
MessageBox.Show("Unkown Control Id: " + control.Id, ADDIN_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
break;
}
}
catch (Exception ex)
{
string message = string.Format("Error occured: {0}", ex.Message);
MessageBox.Show(message, _progId, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region COM Register Functions
[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type type)
{
try
{
// add codebase entry
Assembly thisAssembly = Assembly.GetAssembly(typeof(Addin));
RegistryKey key = Registry.ClassesRoot.CreateSubKey("CLSID\\{" + type.GUID.ToString().ToUpper() + "}\\InprocServer32\\1.0.0.0");
key.SetValue("CodeBase", thisAssembly.CodeBase);
key.Close();
Registry.ClassesRoot.CreateSubKey(@"CLSID\{" + type.GUID.ToString().ToUpper() + @"}\Programmable");
// add bypass key
// http://support.microsoft.com/kb/948461
key = Registry.ClassesRoot.CreateSubKey("Interface\\{000C0601-0000-0000-C000-000000000046}");
string defaultValue = key.GetValue("") as string;
if (null == defaultValue)
key.SetValue("", "Office .NET Framework Lockback Bypass Key");
key.Close();
OfficeRegistry.CreateAddinKey("Excel" , _progId, _addinFriendlyName, _addinDescription);
OfficeRegistry.CreateAddinKey("Word", _progId, _addinFriendlyName, _addinDescription);
OfficeRegistry.CreateAddinKey("Outlook", _progId, _addinFriendlyName, _addinDescription);
OfficeRegistry.CreateAddinKey("PowerPoint", _progId, _addinFriendlyName, _addinDescription);
OfficeRegistry.CreateAddinKey("Access", _progId, _addinFriendlyName, _addinDescription);
}
catch (Exception exception)
{
string message = string.Format("An error occured.{0}{0}{1}", Environment.NewLine, exception.Message);
MessageBox.Show(message, _progId, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type type)
{
try
{
Registry.ClassesRoot.DeleteSubKey(@"CLSID\{" + type.GUID.ToString().ToUpper() + @"}\Programmable", false);
OfficeRegistry.DeleteAddinKey(OfficeRegistry.Excel + _progId);
OfficeRegistry.DeleteAddinKey(OfficeRegistry.Word + _progId);
OfficeRegistry.DeleteAddinKey(OfficeRegistry.Outlook + _progId);
OfficeRegistry.DeleteAddinKey(OfficeRegistry.PowerPoint + _progId);
OfficeRegistry.DeleteAddinKey(OfficeRegistry.Access + _progId);
}
catch (Exception exception)
{
string message = string.Format("An error occured.{0}{0}{1}", Environment.NewLine, exception.Message);
MessageBox.Show(message, _progId, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region Private Helper
private static string ReadTextFileFromRessource(string fileName)
{
Assembly assembly = typeof(Addin).Assembly;
System.IO.Stream ressourceStream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + fileName);
if (ressourceStream == null)
throw (new System.IO.IOException("Error accessing resource Stream."));
System.IO.StreamReader textStreamReader = new System.IO.StreamReader(ressourceStream);
if (textStreamReader == null)
throw (new System.IO.IOException("Error accessing resource File."));
string text = textStreamReader.ReadToEnd();
ressourceStream.Close();
textStreamReader.Close();
return text;
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input.Events;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Music;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays
{
public class NowPlayingOverlay : OsuFocusedOverlayContainer
{
private const float player_height = 130;
private const float transition_length = 800;
private const float progress_height = 10;
private const float bottom_black_area_height = 55;
private Drawable background;
private ProgressBar progressBar;
private IconButton prevButton;
private IconButton playButton;
private IconButton nextButton;
private IconButton playlistButton;
private SpriteText title, artist;
private PlaylistOverlay playlist;
private Container dragContainer;
private Container playerContainer;
/// <summary>
/// Provide a source for the toolbar height.
/// </summary>
public Func<float> GetToolbarHeight;
[Resolved]
private MusicController musicController { get; set; }
[Resolved]
private Bindable<WorkingBeatmap> beatmap { get; set; }
public NowPlayingOverlay()
{
Width = 400;
Margin = new MarginPadding(10);
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Children = new Drawable[]
{
dragContainer = new DragContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
playlist = new PlaylistOverlay
{
RelativeSizeAxes = Axes.X,
Y = player_height + 10,
},
playerContainer = new Container
{
RelativeSizeAxes = Axes.X,
Height = player_height,
Masking = true,
CornerRadius = 5,
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Colour = Color4.Black.Opacity(40),
Radius = 5,
},
Children = new[]
{
background = new Background(),
title = new OsuSpriteText
{
Origin = Anchor.BottomCentre,
Anchor = Anchor.TopCentre,
Position = new Vector2(0, 40),
Font = OsuFont.GetFont(size: 25, italics: true),
Colour = Color4.White,
Text = @"Nothing to play",
},
artist = new OsuSpriteText
{
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre,
Position = new Vector2(0, 45),
Font = OsuFont.GetFont(size: 15, weight: FontWeight.Bold, italics: true),
Colour = Color4.White,
Text = @"Nothing to play",
},
new Container
{
Padding = new MarginPadding { Bottom = progress_height },
Height = bottom_black_area_height,
RelativeSizeAxes = Axes.X,
Origin = Anchor.BottomCentre,
Anchor = Anchor.BottomCentre,
Children = new Drawable[]
{
new FillFlowContainer<IconButton>
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5),
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Children = new[]
{
prevButton = new MusicIconButton
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Action = () => musicController.PrevTrack(),
Icon = FontAwesome.Solid.StepBackward,
},
playButton = new MusicIconButton
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Scale = new Vector2(1.4f),
IconScale = new Vector2(1.4f),
Action = () => musicController.TogglePause(),
Icon = FontAwesome.Regular.PlayCircle,
},
nextButton = new MusicIconButton
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Action = () => musicController.NextTrack(),
Icon = FontAwesome.Solid.StepForward,
},
}
},
playlistButton = new MusicIconButton
{
Origin = Anchor.Centre,
Anchor = Anchor.CentreRight,
Position = new Vector2(-bottom_black_area_height / 2, 0),
Icon = FontAwesome.Solid.Bars,
Action = () => playlist.ToggleVisibility(),
},
}
},
progressBar = new ProgressBar
{
Origin = Anchor.BottomCentre,
Anchor = Anchor.BottomCentre,
Height = progress_height,
FillColour = colours.Yellow,
OnSeek = musicController.SeekTo
}
},
},
}
}
};
playlist.State.ValueChanged += s => playlistButton.FadeColour(s.NewValue == Visibility.Visible ? colours.Yellow : Color4.White, 200, Easing.OutQuint);
}
protected override void LoadComplete()
{
base.LoadComplete();
beatmap.BindDisabledChanged(beatmapDisabledChanged, true);
musicController.TrackChanged += trackChanged;
trackChanged(beatmap.Value);
}
protected override void PopIn()
{
base.PopIn();
this.FadeIn(transition_length, Easing.OutQuint);
dragContainer.ScaleTo(1, transition_length, Easing.OutElastic);
}
protected override void PopOut()
{
base.PopOut();
this.FadeOut(transition_length, Easing.OutQuint);
dragContainer.ScaleTo(0.9f, transition_length, Easing.OutQuint);
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
Height = dragContainer.Height;
dragContainer.Padding = new MarginPadding { Top = GetToolbarHeight?.Invoke() ?? 0 };
}
protected override void Update()
{
base.Update();
if (pendingBeatmapSwitch != null)
{
pendingBeatmapSwitch();
pendingBeatmapSwitch = null;
}
var track = beatmap.Value?.TrackLoaded ?? false ? beatmap.Value.Track : null;
if (track?.IsDummyDevice == false)
{
progressBar.EndTime = track.Length;
progressBar.CurrentTime = track.CurrentTime;
playButton.Icon = track.IsRunning ? FontAwesome.Regular.PauseCircle : FontAwesome.Regular.PlayCircle;
}
else
{
progressBar.CurrentTime = 0;
progressBar.EndTime = 1;
playButton.Icon = FontAwesome.Regular.PlayCircle;
}
}
private Action pendingBeatmapSwitch;
private void trackChanged(WorkingBeatmap beatmap, TrackChangeDirection direction = TrackChangeDirection.None)
{
// avoid using scheduler as our scheduler may not be run for a long time, holding references to beatmaps.
pendingBeatmapSwitch = delegate
{
// todo: this can likely be replaced with WorkingBeatmap.GetBeatmapAsync()
Task.Run(() =>
{
if (beatmap?.Beatmap == null) //this is not needed if a placeholder exists
{
title.Text = @"Nothing to play";
artist.Text = @"Nothing to play";
}
else
{
BeatmapMetadata metadata = beatmap.Metadata;
title.Text = new LocalisedString((metadata.TitleUnicode, metadata.Title));
artist.Text = new LocalisedString((metadata.ArtistUnicode, metadata.Artist));
}
});
LoadComponentAsync(new Background(beatmap) { Depth = float.MaxValue }, newBackground =>
{
switch (direction)
{
case TrackChangeDirection.Next:
newBackground.Position = new Vector2(400, 0);
newBackground.MoveToX(0, 500, Easing.OutCubic);
background.MoveToX(-400, 500, Easing.OutCubic);
break;
case TrackChangeDirection.Prev:
newBackground.Position = new Vector2(-400, 0);
newBackground.MoveToX(0, 500, Easing.OutCubic);
background.MoveToX(400, 500, Easing.OutCubic);
break;
}
background.Expire();
background = newBackground;
playerContainer.Add(newBackground);
});
};
}
private void beatmapDisabledChanged(bool disabled)
{
if (disabled)
playlist.Hide();
playButton.Enabled.Value = !disabled;
prevButton.Enabled.Value = !disabled;
nextButton.Enabled.Value = !disabled;
playlistButton.Enabled.Value = !disabled;
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (musicController != null)
musicController.TrackChanged -= trackChanged;
}
private class MusicIconButton : IconButton
{
public MusicIconButton()
{
AutoSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
HoverColour = colours.YellowDark.Opacity(0.6f);
FlashColour = colours.Yellow;
}
protected override void LoadComplete()
{
base.LoadComplete();
// works with AutoSizeAxes above to make buttons autosize with the scale animation.
Content.AutoSizeAxes = Axes.None;
Content.Size = new Vector2(DEFAULT_BUTTON_SIZE);
}
}
private class Background : BufferedContainer
{
private readonly Sprite sprite;
private readonly WorkingBeatmap beatmap;
public Background(WorkingBeatmap beatmap = null)
{
this.beatmap = beatmap;
Depth = float.MaxValue;
RelativeSizeAxes = Axes.Both;
CacheDrawnFrameBuffer = true;
Children = new Drawable[]
{
sprite = new Sprite
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.Gray(150),
FillMode = FillMode.Fill,
},
new Box
{
RelativeSizeAxes = Axes.X,
Height = bottom_black_area_height,
Origin = Anchor.BottomCentre,
Anchor = Anchor.BottomCentre,
Colour = Color4.Black.Opacity(0.5f)
}
};
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
sprite.Texture = beatmap?.Background ?? textures.Get(@"Backgrounds/bg4");
}
}
private class DragContainer : Container
{
protected override bool OnDragStart(DragStartEvent e)
{
return true;
}
protected override bool OnDrag(DragEvent e)
{
Vector2 change = e.MousePosition - e.MouseDownPosition;
// Diminish the drag distance as we go further to simulate "rubber band" feeling.
change *= change.Length <= 0 ? 0 : (float)Math.Pow(change.Length, 0.7f) / change.Length;
this.MoveTo(change);
return true;
}
protected override bool OnDragEnd(DragEndEvent e)
{
this.MoveTo(Vector2.Zero, 800, Easing.OutElastic);
return base.OnDragEnd(e);
}
}
}
}
| |
//
// SourceMethodBuilder.cs
//
// Authors:
// Martin Baulig ([email protected])
// Marek Safar ([email protected])
//
// (C) 2002 Ximian, Inc. http://www.ximian.com
// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
namespace Mono.CompilerServices.SymbolWriter
{
public class SourceMethodBuilder
{
List<LocalVariableEntry> _locals;
List<CodeBlockEntry> _blocks;
List<ScopeVariable> _scope_vars;
Stack<CodeBlockEntry> _block_stack;
readonly List<LineNumberEntry> method_lines;
readonly ICompileUnit _comp_unit;
readonly int ns_id;
readonly IMethodDef method;
public SourceMethodBuilder (ICompileUnit comp_unit)
{
this._comp_unit = comp_unit;
method_lines = new List<LineNumberEntry> ();
}
public SourceMethodBuilder (ICompileUnit comp_unit, int ns_id, IMethodDef method)
: this (comp_unit)
{
this.ns_id = ns_id;
this.method = method;
}
public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column, bool is_hidden)
{
MarkSequencePoint (offset, file, line, column, -1, -1, is_hidden);
}
public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column, int end_line, int end_column, bool is_hidden)
{
int file_idx = file != null ? file.Index : 0;
var lne = new LineNumberEntry (file_idx, line, column, end_line, end_column, offset, is_hidden);
if (method_lines.Count > 0) {
var prev = method_lines[method_lines.Count - 1];
//
// Same offset cannot be used for multiple lines
//
if (prev.Offset == offset) {
//
// Use the new location because debugger will adjust
// the breakpoint to next line with sequence point
//
if (LineNumberEntry.LocationComparer.Default.Compare (lne, prev) > 0)
method_lines[method_lines.Count - 1] = lne;
return;
}
}
method_lines.Add (lne);
}
public void StartBlock (CodeBlockEntry.Type type, int start_offset)
{
StartBlock (type, start_offset, _blocks == null ? 1 : _blocks.Count + 1);
}
public void StartBlock (CodeBlockEntry.Type type, int start_offset, int scopeIndex)
{
if (_block_stack == null) {
_block_stack = new Stack<CodeBlockEntry> ();
}
if (_blocks == null)
_blocks = new List<CodeBlockEntry> ();
int parent = CurrentBlock != null ? CurrentBlock.Index : -1;
CodeBlockEntry block = new CodeBlockEntry (
scopeIndex, parent, type, start_offset);
_block_stack.Push (block);
_blocks.Add (block);
}
public void EndBlock (int end_offset)
{
CodeBlockEntry block = (CodeBlockEntry) _block_stack.Pop ();
block.Close (end_offset);
}
public CodeBlockEntry[] Blocks {
get {
if (_blocks == null)
return new CodeBlockEntry [0];
CodeBlockEntry[] retval = new CodeBlockEntry [_blocks.Count];
_blocks.CopyTo (retval, 0);
return retval;
}
}
public CodeBlockEntry CurrentBlock {
get {
if ((_block_stack != null) && (_block_stack.Count > 0))
return (CodeBlockEntry) _block_stack.Peek ();
else
return null;
}
}
public LocalVariableEntry[] Locals {
get {
if (_locals == null)
return new LocalVariableEntry [0];
else {
return _locals.ToArray ();
}
}
}
public ICompileUnit SourceFile {
get {
return _comp_unit;
}
}
public void AddLocal (int index, string name)
{
if (_locals == null)
_locals = new List<LocalVariableEntry> ();
int block_idx = CurrentBlock != null ? CurrentBlock.Index : 0;
_locals.Add (new LocalVariableEntry (index, name, block_idx));
}
public ScopeVariable[] ScopeVariables {
get {
if (_scope_vars == null)
return new ScopeVariable [0];
return _scope_vars.ToArray ();
}
}
public void AddScopeVariable (int scope, int index)
{
if (_scope_vars == null)
_scope_vars = new List<ScopeVariable> ();
_scope_vars.Add (
new ScopeVariable (scope, index));
}
public void DefineMethod (MonoSymbolFile file)
{
DefineMethod (file, method.Token);
}
public void DefineMethod (MonoSymbolFile file, int token)
{
var blocks = Blocks;
if (blocks.Length > 0) {
//
// When index is provided by user it can be inserted in
// any order but mdb format does not store its value. It
// uses stored order as the index instead.
//
var sorted = new List<CodeBlockEntry> (blocks.Length);
int max_index = 0;
for (int i = 0; i < blocks.Length; ++i) {
max_index = System.Math.Max (max_index, blocks [i].Index);
}
for (int i = 0; i < max_index; ++i) {
var scope_index = i + 1;
//
// Common fast path
//
if (i < blocks.Length && blocks [i].Index == scope_index) {
sorted.Add (blocks [i]);
continue;
}
bool found = false;
for (int ii = 0; ii < blocks.Length; ++ii) {
if (blocks [ii].Index == scope_index) {
sorted.Add (blocks [ii]);
found = true;
break;
}
}
if (found)
continue;
//
// Ideally this should never happen but with current design we can
// generate scope index for unreachable code before reachable code
//
sorted.Add (new CodeBlockEntry (scope_index, -1, CodeBlockEntry.Type.CompilerGenerated, 0));
}
blocks = sorted.ToArray ();
//for (int i = 0; i < blocks.Length; ++i) {
// if (blocks [i].Index - 1 != i)
// throw new ArgumentException ("CodeBlocks cannot be converted to mdb format");
//}
}
var entry = new MethodEntry (
file, _comp_unit.Entry, token, ScopeVariables,
Locals, method_lines.ToArray (), blocks, null, MethodEntry.Flags.ColumnsInfoIncluded, ns_id);
file.AddMethod (entry);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Buffers
{
using System.Diagnostics.Contracts;
public class UnpooledHeapByteBuffer : AbstractReferenceCountedByteBuffer
{
readonly IByteBufferAllocator allocator;
byte[] array;
/// <summary>
/// Creates a new heap buffer with a newly allocated byte array.
///
/// @param initialCapacity the initial capacity of the underlying byte array
/// @param maxCapacity the max capacity of the underlying byte array
/// </summary>
public UnpooledHeapByteBuffer(IByteBufferAllocator allocator, int initialCapacity, int maxCapacity)
: this(allocator, new byte[initialCapacity], 0, 0, maxCapacity)
{
}
/// <summary>
/// Creates a new heap buffer with an existing byte array.
///
/// @param initialArray the initial underlying byte array
/// @param maxCapacity the max capacity of the underlying byte array
/// </summary>
public UnpooledHeapByteBuffer(IByteBufferAllocator allocator, byte[] initialArray, int maxCapacity)
: this(allocator, initialArray, 0, initialArray.Length, maxCapacity)
{
}
public UnpooledHeapByteBuffer(
IByteBufferAllocator allocator, byte[] initialArray, int readerIndex, int writerIndex, int maxCapacity)
: base(maxCapacity)
{
Contract.Requires(allocator != null);
Contract.Requires(initialArray != null);
Contract.Requires(initialArray.Length <= maxCapacity);
this.allocator = allocator;
this.SetArray(initialArray);
this.SetIndex(readerIndex, writerIndex);
}
protected void SetArray(byte[] initialArray)
{
this.array = initialArray;
}
public override IByteBufferAllocator Allocator
{
get { return this.allocator; }
}
public override ByteOrder Order
{
get { return ByteOrder.BigEndian; }
}
public override int Capacity
{
get
{
this.EnsureAccessible();
return this.array.Length;
}
}
public override IByteBuffer AdjustCapacity(int newCapacity)
{
this.EnsureAccessible();
Contract.Requires(newCapacity >= 0 && newCapacity <= this.MaxCapacity);
int oldCapacity = this.array.Length;
if (newCapacity > oldCapacity)
{
var newArray = new byte[newCapacity];
System.Array.Copy(this.array, 0, newArray, 0, this.array.Length);
this.SetArray(newArray);
}
else if (newCapacity < oldCapacity)
{
var newArray = new byte[newCapacity];
int readerIndex = this.ReaderIndex;
if (readerIndex < newCapacity)
{
int writerIndex = this.WriterIndex;
if (writerIndex > newCapacity)
{
this.SetWriterIndex(writerIndex = newCapacity);
}
System.Array.Copy(this.array, readerIndex, newArray, readerIndex, writerIndex - readerIndex);
}
else
{
this.SetIndex(newCapacity, newCapacity);
}
this.SetArray(newArray);
}
return this;
}
public override bool HasArray
{
get { return true; }
}
public override byte[] Array
{
get
{
this.EnsureAccessible();
return this.array;
}
}
public override int ArrayOffset
{
get { return 0; }
}
public override IByteBuffer GetBytes(int index, IByteBuffer dst, int dstIndex, int length)
{
this.CheckDstIndex(index, length, dstIndex, dst.Capacity);
if (dst.HasArray)
{
this.GetBytes(index, dst.Array, dst.ArrayOffset + dstIndex, length);
}
else
{
dst.SetBytes(dstIndex, this.array, index, length);
}
return this;
}
public override IByteBuffer GetBytes(int index, byte[] dst, int dstIndex, int length)
{
this.CheckDstIndex(index, length, dstIndex, dst.Length);
System.Array.Copy(this.array, index, dst, dstIndex, length);
return this;
}
public override IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length)
{
this.CheckSrcIndex(index, length, srcIndex, src.Capacity);
if (src.HasArray)
{
this.SetBytes(index, src.Array, src.ArrayOffset + srcIndex, length);
}
else
{
src.GetBytes(srcIndex, this.array, index, length);
}
return this;
}
public override IByteBuffer SetBytes(int index, byte[] src, int srcIndex, int length)
{
this.CheckSrcIndex(index, length, srcIndex, src.Length);
System.Array.Copy(src, srcIndex, this.array, index, length);
return this;
}
public override byte GetByte(int index)
{
this.EnsureAccessible();
return this._GetByte(index);
}
protected override byte _GetByte(int index)
{
return this.array[index];
}
public override short GetShort(int index)
{
this.EnsureAccessible();
return this._GetShort(index);
}
protected override short _GetShort(int index)
{
return unchecked((short)(this.array[index] << 8 | this.array[index + 1]));
}
public override int GetInt(int index)
{
this.EnsureAccessible();
return this._GetInt(index);
}
protected override int _GetInt(int index)
{
return unchecked(this.array[index] << 24 |
this.array[index + 1] << 16 |
this.array[index + 2] << 8 |
this.array[index + 3]);
}
public override long GetLong(int index)
{
this.EnsureAccessible();
return this._GetLong(index);
}
protected override long _GetLong(int index)
{
unchecked
{
int i1 = this.array[index] << 24 |
this.array[index + 1] << 16 |
this.array[index + 2] << 8 |
this.array[index + 3];
int i2 = this.array[index + 4] << 24 |
this.array[index + 5] << 16 |
this.array[index + 6] << 8 |
this.array[index + 7];
return (uint)i2 | ((long)i1 << 32);
}
}
public override IByteBuffer SetByte(int index, int value)
{
this.EnsureAccessible();
this._SetByte(index, value);
return this;
}
protected override void _SetByte(int index, int value)
{
this.array[index] = (byte)value;
}
public override IByteBuffer SetShort(int index, int value)
{
this.EnsureAccessible();
this._SetShort(index, value);
return this;
}
protected override void _SetShort(int index, int value)
{
unchecked
{
this.array[index] = (byte)((ushort)value >> 8);
this.array[index + 1] = (byte)value;
}
}
public override IByteBuffer SetInt(int index, int value)
{
this.EnsureAccessible();
this._SetInt(index, value);
return this;
}
protected override void _SetInt(int index, int value)
{
unchecked
{
uint unsignedValue = (uint)value;
this.array[index] = (byte)(unsignedValue >> 24);
this.array[index + 1] = (byte)(unsignedValue >> 16);
this.array[index + 2] = (byte)(unsignedValue >> 8);
this.array[index + 3] = (byte)value;
}
}
public override IByteBuffer SetLong(int index, long value)
{
this.EnsureAccessible();
this._SetLong(index, value);
return this;
}
protected override void _SetLong(int index, long value)
{
unchecked
{
ulong unsignedValue = (ulong)value;
this.array[index] = (byte)(unsignedValue >> 56);
this.array[index + 1] = (byte)(unsignedValue >> 48);
this.array[index + 2] = (byte)(unsignedValue >> 40);
this.array[index + 3] = (byte)(unsignedValue >> 32);
this.array[index + 4] = (byte)(unsignedValue >> 24);
this.array[index + 5] = (byte)(unsignedValue >> 16);
this.array[index + 6] = (byte)(unsignedValue >> 8);
this.array[index + 7] = (byte)value;
}
}
public override IByteBuffer Copy(int index, int length)
{
this.CheckIndex(index, length);
var copiedArray = new byte[length];
System.Array.Copy(this.array, index, copiedArray, 0, length);
return new UnpooledHeapByteBuffer(this.Allocator, copiedArray, this.MaxCapacity);
}
protected override void Deallocate()
{
this.array = null;
}
public override IByteBuffer Unwrap()
{
return null;
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Roslyn.Utilities;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.CodeAnalysis.CommandLine;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines all of the common stuff that is shared between the Vbc and Csc tasks.
/// This class is not instantiatable as a Task just by itself.
/// </summary>
public abstract class ManagedCompiler : ToolTask
{
private CancellationTokenSource _sharedCompileCts;
internal readonly PropertyDictionary _store = new PropertyDictionary();
public ManagedCompiler()
{
TaskResources = ErrorString.ResourceManager;
}
#region Properties
// Please keep these alphabetized.
public string[] AdditionalLibPaths
{
set { _store[nameof(AdditionalLibPaths)] = value; }
get { return (string[])_store[nameof(AdditionalLibPaths)]; }
}
public string[] AddModules
{
set { _store[nameof(AddModules)] = value; }
get { return (string[])_store[nameof(AddModules)]; }
}
public ITaskItem[] AdditionalFiles
{
set { _store[nameof(AdditionalFiles)] = value; }
get { return (ITaskItem[])_store[nameof(AdditionalFiles)]; }
}
public ITaskItem[] EmbeddedFiles
{
set { _store[nameof(EmbeddedFiles)] = value; }
get { return (ITaskItem[])_store[nameof(EmbeddedFiles)]; }
}
public ITaskItem[] Analyzers
{
set { _store[nameof(Analyzers)] = value; }
get { return (ITaskItem[])_store[nameof(Analyzers)]; }
}
// We do not support BugReport because it always requires user interaction,
// which will cause a hang.
public string ChecksumAlgorithm
{
set { _store[nameof(ChecksumAlgorithm)] = value; }
get { return (string)_store[nameof(ChecksumAlgorithm)]; }
}
/// <summary>
/// An instrument flag that specifies instrumentation settings.
/// </summary>
public string Instrument
{
set { _store[nameof(Instrument)] = value; }
get { return (string)_store[nameof(Instrument)]; }
}
public string CodeAnalysisRuleSet
{
set { _store[nameof(CodeAnalysisRuleSet)] = value; }
get { return (string)_store[nameof(CodeAnalysisRuleSet)]; }
}
public int CodePage
{
set { _store[nameof(CodePage)] = value; }
get { return _store.GetOrDefault(nameof(CodePage), 0); }
}
[Output]
public ITaskItem[] CommandLineArgs
{
set { _store[nameof(CommandLineArgs)] = value; }
get { return (ITaskItem[])_store[nameof(CommandLineArgs)]; }
}
public string DebugType
{
set { _store[nameof(DebugType)] = value; }
get { return (string)_store[nameof(DebugType)]; }
}
public string SourceLink
{
set { _store[nameof(SourceLink)] = value; }
get { return (string)_store[nameof(SourceLink)]; }
}
public string DefineConstants
{
set { _store[nameof(DefineConstants)] = value; }
get { return (string)_store[nameof(DefineConstants)]; }
}
public bool DelaySign
{
set { _store[nameof(DelaySign)] = value; }
get { return _store.GetOrDefault(nameof(DelaySign), false); }
}
public bool Deterministic
{
set { _store[nameof(Deterministic)] = value; }
get { return _store.GetOrDefault(nameof(Deterministic), false); }
}
public bool PublicSign
{
set { _store[nameof(PublicSign)] = value; }
get { return _store.GetOrDefault(nameof(PublicSign), false); }
}
public bool EmitDebugInformation
{
set { _store[nameof(EmitDebugInformation)] = value; }
get { return _store.GetOrDefault(nameof(EmitDebugInformation), false); }
}
public string ErrorLog
{
set { _store[nameof(ErrorLog)] = value; }
get { return (string)_store[nameof(ErrorLog)]; }
}
public string Features
{
set { _store[nameof(Features)] = value; }
get { return (string)_store[nameof(Features)]; }
}
public int FileAlignment
{
set { _store[nameof(FileAlignment)] = value; }
get { return _store.GetOrDefault(nameof(FileAlignment), 0); }
}
public bool HighEntropyVA
{
set { _store[nameof(HighEntropyVA)] = value; }
get { return _store.GetOrDefault(nameof(HighEntropyVA), false); }
}
public string KeyContainer
{
set { _store[nameof(KeyContainer)] = value; }
get { return (string)_store[nameof(KeyContainer)]; }
}
public string KeyFile
{
set { _store[nameof(KeyFile)] = value; }
get { return (string)_store[nameof(KeyFile)]; }
}
public ITaskItem[] LinkResources
{
set { _store[nameof(LinkResources)] = value; }
get { return (ITaskItem[])_store[nameof(LinkResources)]; }
}
public string MainEntryPoint
{
set { _store[nameof(MainEntryPoint)] = value; }
get { return (string)_store[nameof(MainEntryPoint)]; }
}
public bool NoConfig
{
set { _store[nameof(NoConfig)] = value; }
get { return _store.GetOrDefault(nameof(NoConfig), false); }
}
public bool NoLogo
{
set { _store[nameof(NoLogo)] = value; }
get { return _store.GetOrDefault(nameof(NoLogo), false); }
}
public bool NoWin32Manifest
{
set { _store[nameof(NoWin32Manifest)] = value; }
get { return _store.GetOrDefault(nameof(NoWin32Manifest), false); }
}
public bool Optimize
{
set { _store[nameof(Optimize)] = value; }
get { return _store.GetOrDefault(nameof(Optimize), false); }
}
[Output]
public ITaskItem OutputAssembly
{
set { _store[nameof(OutputAssembly)] = value; }
get { return (ITaskItem)_store[nameof(OutputAssembly)]; }
}
public string Platform
{
set { _store[nameof(Platform)] = value; }
get { return (string)_store[nameof(Platform)]; }
}
public bool Prefer32Bit
{
set { _store[nameof(Prefer32Bit)] = value; }
get { return _store.GetOrDefault(nameof(Prefer32Bit), false); }
}
public bool ProvideCommandLineArgs
{
set { _store[nameof(ProvideCommandLineArgs)] = value; }
get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); }
}
public ITaskItem[] References
{
set { _store[nameof(References)] = value; }
get { return (ITaskItem[])_store[nameof(References)]; }
}
public bool ReportAnalyzer
{
set { _store[nameof(ReportAnalyzer)] = value; }
get { return _store.GetOrDefault(nameof(ReportAnalyzer), false); }
}
public ITaskItem[] Resources
{
set { _store[nameof(Resources)] = value; }
get { return (ITaskItem[])_store[nameof(Resources)]; }
}
public string RuntimeMetadataVersion
{
set { _store[nameof(RuntimeMetadataVersion)] = value; }
get { return (string)_store[nameof(RuntimeMetadataVersion)]; }
}
public ITaskItem[] ResponseFiles
{
set { _store[nameof(ResponseFiles)] = value; }
get { return (ITaskItem[])_store[nameof(ResponseFiles)]; }
}
public bool SkipCompilerExecution
{
set { _store[nameof(SkipCompilerExecution)] = value; }
get { return _store.GetOrDefault(nameof(SkipCompilerExecution), false); }
}
public ITaskItem[] Sources
{
set
{
if (UsedCommandLineTool)
{
NormalizePaths(value);
}
_store[nameof(Sources)] = value;
}
get { return (ITaskItem[])_store[nameof(Sources)]; }
}
public string SubsystemVersion
{
set { _store[nameof(SubsystemVersion)] = value; }
get { return (string)_store[nameof(SubsystemVersion)]; }
}
public string TargetType
{
set { _store[nameof(TargetType)] = CultureInfo.InvariantCulture.TextInfo.ToLower(value); }
get { return (string)_store[nameof(TargetType)]; }
}
public bool TreatWarningsAsErrors
{
set { _store[nameof(TreatWarningsAsErrors)] = value; }
get { return _store.GetOrDefault(nameof(TreatWarningsAsErrors), false); }
}
public bool Utf8Output
{
set { _store[nameof(Utf8Output)] = value; }
get { return _store.GetOrDefault(nameof(Utf8Output), false); }
}
public string Win32Icon
{
set { _store[nameof(Win32Icon)] = value; }
get { return (string)_store[nameof(Win32Icon)]; }
}
public string Win32Manifest
{
set { _store[nameof(Win32Manifest)] = value; }
get { return (string)_store[nameof(Win32Manifest)]; }
}
public string Win32Resource
{
set { _store[nameof(Win32Resource)] = value; }
get { return (string)_store[nameof(Win32Resource)]; }
}
public string PathMap
{
set { _store[nameof(PathMap)] = value; }
get { return (string)_store[nameof(PathMap)]; }
}
/// <summary>
/// If this property is true then the task will take every C# or VB
/// compilation which is queued by MSBuild and send it to the
/// VBCSCompiler server instance, starting a new instance if necessary.
/// If false, we will use the values from ToolPath/Exe.
/// </summary>
public bool UseSharedCompilation
{
set { _store[nameof(UseSharedCompilation)] = value; }
get { return _store.GetOrDefault(nameof(UseSharedCompilation), false); }
}
// Map explicit platform of "AnyCPU" or the default platform (null or ""), since it is commonly understood in the
// managed build process to be equivalent to "AnyCPU", to platform "AnyCPU32BitPreferred" if the Prefer32Bit
// property is set.
internal string PlatformWith32BitPreference
{
get
{
string platform = Platform;
if ((string.IsNullOrEmpty(platform) || platform.Equals("anycpu", StringComparison.OrdinalIgnoreCase)) && Prefer32Bit)
{
platform = "anycpu32bitpreferred";
}
return platform;
}
}
/// <summary>
/// Overridable property specifying the encoding of the captured task standard output stream
/// </summary>
protected override Encoding StandardOutputEncoding
{
get
{
return (Utf8Output) ? Encoding.UTF8 : base.StandardOutputEncoding;
}
}
#endregion
internal abstract RequestLanguage Language { get; }
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
if (ProvideCommandLineArgs)
{
CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands)
.Select(arg => new TaskItem(arg)).ToArray();
}
if (SkipCompilerExecution)
{
return 0;
}
if (!UseSharedCompilation ||
!string.IsNullOrEmpty(ToolPath) ||
!Utilities.IsCompilerServerSupported)
{
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
using (_sharedCompileCts = new CancellationTokenSource())
{
try
{
CompilerServerLogger.Log($"CommandLine = '{commandLineCommands}'");
CompilerServerLogger.Log($"BuildResponseFile = '{responseFileCommands}'");
// Try to get the location of the user-provided build client and server,
// which should be located next to the build task. If not, fall back to
// "pathToTool", which is the compiler in the MSBuild default bin directory.
var clientDir = TryGetClientDir() ?? Path.GetDirectoryName(pathToTool);
pathToTool = Path.Combine(clientDir, ToolExe);
// Note: we can't change the "tool path" printed to the console when we run
// the Csc/Vbc task since MSBuild logs it for us before we get here. Instead,
// we'll just print our own message that contains the real client location
Log.LogMessage(ErrorString.UsingSharedCompilation, clientDir);
var buildPaths = new BuildPaths(
clientDir: clientDir,
// MSBuild doesn't need the .NET SDK directory
sdkDir: null,
workingDir: CurrentDirectoryToUse());
var responseTask = DesktopBuildClient.RunServerCompilation(
Language,
GetArguments(commandLineCommands, responseFileCommands).ToList(),
buildPaths,
keepAlive: null,
libEnvVariable: LibDirectoryToUse(),
cancellationToken: _sharedCompileCts.Token);
responseTask.Wait(_sharedCompileCts.Token);
var response = responseTask.Result;
if (response != null)
{
ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands);
}
else
{
Log.LogMessage(ErrorString.SharedCompilationFallback, pathToTool);
ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
}
catch (OperationCanceledException)
{
ExitCode = 0;
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("Compiler_UnexpectedException");
LogErrorOutput(e.ToString());
ExitCode = -1;
}
}
return ExitCode;
}
/// <summary>
/// Try to get the directory this assembly is in. Returns null if assembly
/// was in the GAC or DLL location can not be retrieved.
/// </summary>
private static string TryGetClientDir()
{
var buildTask = typeof(ManagedCompiler).GetTypeInfo().Assembly;
var inGac = (bool?)typeof(Assembly)
.GetTypeInfo()
.GetDeclaredProperty("GlobalAssemblyCache")
?.GetMethod.Invoke(buildTask, parameters: null);
if (inGac != false)
return null;
var codeBase = (string)typeof(Assembly)
.GetTypeInfo()
.GetDeclaredProperty("CodeBase")
?.GetMethod.Invoke(buildTask, parameters: null);
if (codeBase == null) return null;
var uri = new Uri(codeBase);
string assemblyPath;
if (uri.IsFile)
{
assemblyPath = uri.LocalPath;
}
else
{
var callingAssembly = (Assembly)typeof(Assembly)
.GetTypeInfo()
.GetDeclaredMethod("GetCallingAssembly")
?.Invoke(null, null);
var location = (string)typeof(Assembly)
.GetTypeInfo()
.GetDeclaredProperty("Location")
?.GetMethod.Invoke(callingAssembly, parameters: null);
if (location == null) return null;
assemblyPath = location;
}
return Path.GetDirectoryName(assemblyPath);
}
/// <summary>
/// Cancel the in-process build task.
/// </summary>
public override void Cancel()
{
base.Cancel();
_sharedCompileCts?.Cancel();
}
/// <summary>
/// Get the current directory that the compiler should run in.
/// </summary>
private string CurrentDirectoryToUse()
{
// ToolTask has a method for this. But it may return null. Use the process directory
// if ToolTask didn't override. MSBuild uses the process directory.
string workingDirectory = GetWorkingDirectory();
if (string.IsNullOrEmpty(workingDirectory))
workingDirectory = Directory.GetCurrentDirectory();
return workingDirectory;
}
/// <summary>
/// Get the "LIB" environment variable, or NULL if none.
/// </summary>
private string LibDirectoryToUse()
{
// First check the real environment.
string libDirectory = Environment.GetEnvironmentVariable("LIB");
// Now go through additional environment variables.
string[] additionalVariables = EnvironmentVariables;
if (additionalVariables != null)
{
foreach (string var in EnvironmentVariables)
{
if (var.StartsWith("LIB=", StringComparison.OrdinalIgnoreCase))
{
libDirectory = var.Substring(4);
}
}
}
return libDirectory;
}
/// <summary>
/// The return code of the compilation. Strangely, this isn't overridable from ToolTask, so we need
/// to create our own.
/// </summary>
[Output]
public new int ExitCode { get; private set; }
/// <summary>
/// Handle a response from the server, reporting messages and returning
/// the appropriate exit code.
/// </summary>
private int HandleResponse(BuildResponse response, string pathToTool, string responseFileCommands, string commandLineCommands)
{
switch (response.Type)
{
case BuildResponse.ResponseType.MismatchedVersion:
LogErrorOutput(CommandLineParser.MismatchedVersionErrorText);
return -1;
case BuildResponse.ResponseType.Completed:
var completedResponse = (CompletedBuildResponse)response;
LogMessages(completedResponse.Output, StandardOutputImportanceToUse);
if (LogStandardErrorAsError)
{
LogErrorOutput(completedResponse.ErrorOutput);
}
else
{
LogMessages(completedResponse.ErrorOutput, StandardErrorImportanceToUse);
}
return completedResponse.ReturnCode;
case BuildResponse.ResponseType.Rejected:
case BuildResponse.ResponseType.AnalyzerInconsistency:
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
default:
throw new InvalidOperationException("Encountered unknown response type");
}
}
private void LogErrorOutput(string output)
{
string[] lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string trimmedMessage = line.Trim();
if (trimmedMessage != "")
{
Log.LogError(trimmedMessage);
}
}
}
/// <summary>
/// Log each of the messages in the given output with the given importance.
/// We assume each line is a message to log.
/// </summary>
/// <remarks>
/// Should be "private protected" visibility once it is introduced into C#.
/// </remarks>
internal abstract void LogMessages(string output, MessageImportance messageImportance);
public string GenerateResponseFileContents()
{
return GenerateResponseFileCommands();
}
/// <summary>
/// Get the command line arguments to pass to the compiler.
/// </summary>
private string[] GetArguments(string commandLineCommands, string responseFileCommands)
{
var commandLineArguments =
CommandLineParser.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true);
var responseFileArguments =
CommandLineParser.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true);
return commandLineArguments.Concat(responseFileArguments).ToArray();
}
/// <summary>
/// Returns the command line switch used by the tool executable to specify the response file
/// Will only be called if the task returned a non empty string from GetResponseFileCommands
/// Called after ValidateParameters, SkipTaskExecution and GetResponseFileCommands
/// </summary>
protected override string GenerateResponseFileCommands()
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
AddResponseFileCommands(commandLineBuilder);
return commandLineBuilder.ToString();
}
protected override string GenerateCommandLineCommands()
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
AddCommandLineCommands(commandLineBuilder);
return commandLineBuilder.ToString();
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and
/// must go directly onto the command line.
/// </summary>
protected internal virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendWhenTrue("/noconfig", _store, nameof(NoConfig));
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
protected internal virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
// If outputAssembly is not specified, then an "/out: <name>" option won't be added to
// overwrite the one resulting from the OutputAssembly member of the CompilerParameters class.
// In that case, we should set the outputAssembly member based on the first source file.
if (
(OutputAssembly == null) &&
(Sources != null) &&
(Sources.Length > 0) &&
(ResponseFiles == null) // The response file may already have a /out: switch in it, so don't try to be smart here.
)
{
try
{
OutputAssembly = new TaskItem(Path.GetFileNameWithoutExtension(Sources[0].ItemSpec));
}
catch (ArgumentException e)
{
throw new ArgumentException(e.Message, "Sources");
}
if (string.Compare(TargetType, "library", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".dll";
}
else if (string.Compare(TargetType, "module", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".netmodule";
}
else
{
OutputAssembly.ItemSpec += ".exe";
}
}
commandLine.AppendSwitchIfNotNull("/addmodule:", AddModules, ",");
commandLine.AppendSwitchWithInteger("/codepage:", _store, nameof(CodePage));
ConfigureDebugProperties();
// The "DebugType" parameter should be processed after the "EmitDebugInformation" parameter
// because it's more specific. Order matters on the command-line, and the last one wins.
// /debug+ is just a shorthand for /debug:full. And /debug- is just a shorthand for /debug:none.
commandLine.AppendPlusOrMinusSwitch("/debug", _store, nameof(EmitDebugInformation));
commandLine.AppendSwitchIfNotNull("/debug:", DebugType);
commandLine.AppendPlusOrMinusSwitch("/delaysign", _store, nameof(DelaySign));
commandLine.AppendSwitchWithInteger("/filealign:", _store, nameof(FileAlignment));
commandLine.AppendSwitchIfNotNull("/keycontainer:", KeyContainer);
commandLine.AppendSwitchIfNotNull("/keyfile:", KeyFile);
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/linkresource:", LinkResources, new string[] { "LogicalName", "Access" });
commandLine.AppendWhenTrue("/nologo", _store, nameof(NoLogo));
commandLine.AppendWhenTrue("/nowin32manifest", _store, nameof(NoWin32Manifest));
commandLine.AppendPlusOrMinusSwitch("/optimize", _store, nameof(Optimize));
commandLine.AppendSwitchIfNotNull("/pathmap:", PathMap);
commandLine.AppendSwitchIfNotNull("/out:", OutputAssembly);
commandLine.AppendSwitchIfNotNull("/ruleset:", CodeAnalysisRuleSet);
commandLine.AppendSwitchIfNotNull("/errorlog:", ErrorLog);
commandLine.AppendSwitchIfNotNull("/subsystemversion:", SubsystemVersion);
commandLine.AppendWhenTrue("/reportanalyzer", _store, nameof(ReportAnalyzer));
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/resource:", Resources, new string[] { "LogicalName", "Access" });
commandLine.AppendSwitchIfNotNull("/target:", TargetType);
commandLine.AppendPlusOrMinusSwitch("/warnaserror", _store, nameof(TreatWarningsAsErrors));
commandLine.AppendWhenTrue("/utf8output", _store, nameof(Utf8Output));
commandLine.AppendSwitchIfNotNull("/win32icon:", Win32Icon);
commandLine.AppendSwitchIfNotNull("/win32manifest:", Win32Manifest);
AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLine);
AddAnalyzersToCommandLine(commandLine, Analyzers);
AddAdditionalFilesToCommandLine(commandLine);
// Append the sources.
commandLine.AppendFileNamesIfNotNull(Sources, " ");
}
internal void AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(CommandLineBuilderExtension commandLine)
{
commandLine.AppendPlusOrMinusSwitch("/deterministic", _store, nameof(Deterministic));
commandLine.AppendPlusOrMinusSwitch("/publicsign", _store, nameof(PublicSign));
commandLine.AppendSwitchIfNotNull("/runtimemetadataversion:", RuntimeMetadataVersion);
commandLine.AppendSwitchIfNotNull("/checksumalgorithm:", ChecksumAlgorithm);
commandLine.AppendSwitchIfNotNull("/instrument:", Instrument);
commandLine.AppendSwitchIfNotNull("/sourcelink:", SourceLink);
AddFeatures(commandLine, Features);
AddEmbeddedFilesToCommandLine(commandLine);
}
/// <summary>
/// Adds a "/features:" switch to the command line for each provided feature.
/// </summary>
internal static void AddFeatures(CommandLineBuilderExtension commandLine, string features)
{
if (string.IsNullOrEmpty(features))
{
return;
}
foreach (var feature in CompilerOptionParseUtilities.ParseFeatureFromMSBuild(features))
{
commandLine.AppendSwitchIfNotNull("/features:", feature.Trim());
}
}
/// <summary>
/// Adds a "/analyzer:" switch to the command line for each provided analyzer.
/// </summary>
internal static void AddAnalyzersToCommandLine(CommandLineBuilderExtension commandLine, ITaskItem[] analyzers)
{
// If there were no analyzers passed in, don't add any /analyzer: switches
// on the command-line.
if (analyzers == null)
{
return;
}
foreach (ITaskItem analyzer in analyzers)
{
commandLine.AppendSwitchIfNotNull("/analyzer:", analyzer.ItemSpec);
}
}
/// <summary>
/// Adds a "/additionalfile:" switch to the command line for each additional file.
/// </summary>
private void AddAdditionalFilesToCommandLine(CommandLineBuilderExtension commandLine)
{
if (AdditionalFiles != null)
{
foreach (ITaskItem additionalFile in AdditionalFiles)
{
commandLine.AppendSwitchIfNotNull("/additionalfile:", additionalFile.ItemSpec);
}
}
}
/// <summary>
/// Adds a "/embed:" switch to the command line for each pdb embedded file.
/// </summary>
private void AddEmbeddedFilesToCommandLine(CommandLineBuilderExtension commandLine)
{
if (EmbeddedFiles != null)
{
foreach (ITaskItem embeddedFile in EmbeddedFiles)
{
commandLine.AppendSwitchIfNotNull("/embed:", embeddedFile.ItemSpec);
}
}
}
/// <summary>
/// Configure the debug switches which will be placed on the compiler command-line.
/// The matrix of debug type and symbol inputs and the desired results is as follows:
///
/// Debug Symbols DebugType Desired Results
/// True Full /debug+ /debug:full
/// True PdbOnly /debug+ /debug:PdbOnly
/// True None /debug-
/// True Blank /debug+
/// False Full /debug- /debug:full
/// False PdbOnly /debug- /debug:PdbOnly
/// False None /debug-
/// False Blank /debug-
/// Blank Full /debug:full
/// Blank PdbOnly /debug:PdbOnly
/// Blank None /debug-
/// Debug: Blank Blank /debug+ //Microsoft.common.targets will set this
/// Release: Blank Blank "Nothing for either switch"
///
/// The logic is as follows:
/// If debugtype is none set debugtype to empty and debugSymbols to false
/// If debugType is blank use the debugsymbols "as is"
/// If debug type is set, use its value and the debugsymbols value "as is"
/// </summary>
private void ConfigureDebugProperties()
{
// If debug type is set we need to take some action depending on the value. If debugtype is not set
// We don't need to modify the EmitDebugInformation switch as its value will be used as is.
if (_store[nameof(DebugType)] != null)
{
// If debugtype is none then only show debug- else use the debug type and the debugsymbols as is.
if (string.Compare((string)_store[nameof(DebugType)], "none", StringComparison.OrdinalIgnoreCase) == 0)
{
_store[nameof(DebugType)] = null;
_store[nameof(EmitDebugInformation)] = false;
}
}
}
/// <summary>
/// Validate parameters, log errors and warnings and return true if
/// Execute should proceed.
/// </summary>
protected override bool ValidateParameters()
{
return ListHasNoDuplicateItems(Resources, nameof(Resources), "LogicalName", Log) && ListHasNoDuplicateItems(Sources, nameof(Sources), Log);
}
/// <summary>
/// Returns true if the provided item list contains duplicate items, false otherwise.
/// </summary>
internal static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, TaskLoggingHelper log)
{
return ListHasNoDuplicateItems(itemList, parameterName, null, log);
}
/// <summary>
/// Returns true if the provided item list contains duplicate items, false otherwise.
/// </summary>
/// <param name="itemList"></param>
/// <param name="disambiguatingMetadataName">Optional name of metadata that may legitimately disambiguate items. May be null.</param>
/// <param name="parameterName"></param>
/// <param name="log"></param>
private static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, string disambiguatingMetadataName, TaskLoggingHelper log)
{
if (itemList == null || itemList.Length == 0)
{
return true;
}
var alreadySeen = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (ITaskItem item in itemList)
{
string key;
string disambiguatingMetadataValue = null;
if (disambiguatingMetadataName != null)
{
disambiguatingMetadataValue = item.GetMetadata(disambiguatingMetadataName);
}
if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue))
{
key = item.ItemSpec;
}
else
{
key = item.ItemSpec + ":" + disambiguatingMetadataValue;
}
if (alreadySeen.ContainsKey(key))
{
if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue))
{
log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupported", item.ItemSpec, parameterName);
}
else
{
log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupportedWithMetadata", item.ItemSpec, parameterName, disambiguatingMetadataValue, disambiguatingMetadataName);
}
return false;
}
else
{
alreadySeen[key] = string.Empty;
}
}
return true;
}
/// <summary>
/// Allows tool to handle the return code.
/// This method will only be called with non-zero exitCode.
/// </summary>
protected override bool HandleTaskExecutionErrors()
{
// For managed compilers, the compiler should emit the appropriate
// error messages before returning a non-zero exit code, so we don't
// normally need to emit any additional messages now.
//
// If somehow the compiler DID return a non-zero exit code and didn't log an error, we'd like to log that exit code.
// We can only do this for the command line compiler: if the inproc compiler was used,
// we can't tell what if anything it logged as it logs directly to Visual Studio's output window.
//
if (!Log.HasLoggedErrors && UsedCommandLineTool)
{
// This will log a message "MSB3093: The command exited with code {0}."
base.HandleTaskExecutionErrors();
}
return false;
}
/// <summary>
/// Takes a list of files and returns the normalized locations of these files
/// </summary>
private void NormalizePaths(ITaskItem[] taskItems)
{
foreach (var item in taskItems)
{
item.ItemSpec = Utilities.GetFullPathNoThrow(item.ItemSpec);
}
}
/// <summary>
/// Whether the command line compiler was invoked, instead
/// of the host object compiler.
/// </summary>
protected bool UsedCommandLineTool
{
get;
set;
}
private bool _hostCompilerSupportsAllParameters;
protected bool HostCompilerSupportsAllParameters
{
get { return _hostCompilerSupportsAllParameters; }
set { _hostCompilerSupportsAllParameters = value; }
}
/// <summary>
/// Checks the bool result from calling one of the methods on the host compiler object to
/// set one of the parameters. If it returned false, that means the host object doesn't
/// support a particular parameter or variation on a parameter. So we log a comment,
/// and set our state so we know not to call the host object to do the actual compilation.
/// </summary>
/// <owner>RGoel</owner>
protected void CheckHostObjectSupport
(
string parameterName,
bool resultFromHostObjectSetOperation
)
{
if (!resultFromHostObjectSetOperation)
{
Log.LogMessageFromResources(MessageImportance.Normal, "General_ParameterUnsupportedOnHostCompiler", parameterName);
_hostCompilerSupportsAllParameters = false;
}
}
internal void InitializeHostObjectSupportForNewSwitches(ITaskHost hostObject, ref string param)
{
var compilerOptionsHostObject = hostObject as ICompilerOptionsHostObject;
if (compilerOptionsHostObject != null)
{
var commandLineBuilder = new CommandLineBuilderExtension();
AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLineBuilder);
param = "CompilerOptions";
CheckHostObjectSupport(param, compilerOptionsHostObject.SetCompilerOptions(commandLineBuilder.ToString()));
}
}
/// <summary>
/// Checks to see whether all of the passed-in references exist on disk before we launch the compiler.
/// </summary>
/// <owner>RGoel</owner>
protected bool CheckAllReferencesExistOnDisk()
{
if (null == References)
{
// No references
return true;
}
bool success = true;
foreach (ITaskItem reference in References)
{
if (!File.Exists(reference.ItemSpec))
{
success = false;
Log.LogErrorWithCodeFromResources("General_ReferenceDoesNotExist", reference.ItemSpec);
}
}
return success;
}
/// <summary>
/// The IDE and command line compilers unfortunately differ in how win32
/// manifests are specified. In particular, the command line compiler offers a
/// "/nowin32manifest" switch, while the IDE compiler does not offer analogous
/// functionality. If this switch is omitted from the command line and no win32
/// manifest is specified, the compiler will include a default win32 manifest
/// named "default.win32manifest" found in the same directory as the compiler
/// executable. Again, the IDE compiler does not offer analogous support.
///
/// We'd like to imitate the command line compiler's behavior in the IDE, but
/// it isn't aware of the default file, so we must compute the path to it if
/// noDefaultWin32Manifest is false and no win32Manifest was provided by the
/// project.
///
/// This method will only be called during the initialization of the host object,
/// which is only used during IDE builds.
/// </summary>
/// <returns>the path to the win32 manifest to provide to the host object</returns>
internal string GetWin32ManifestSwitch
(
bool noDefaultWin32Manifest,
string win32Manifest
)
{
if (!noDefaultWin32Manifest)
{
if (string.IsNullOrEmpty(win32Manifest) && string.IsNullOrEmpty(Win32Resource))
{
// We only want to consider the default.win32manifest if this is an executable
if (!string.Equals(TargetType, "library", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(TargetType, "module", StringComparison.OrdinalIgnoreCase))
{
// We need to compute the path to the default win32 manifest
string pathToDefaultManifest = ToolLocationHelper.GetPathToDotNetFrameworkFile
(
"default.win32manifest",
// We are choosing to pass Version46 instead of VersionLatest. TargetDotNetFrameworkVersion
// is an enum, and VersionLatest is not some sentinel value but rather a constant that is
// equal to the highest version defined in the enum. Enum values, being constants, are baked
// into consuming assembly, so specifying VersionLatest means not the latest version wherever
// this code is running, but rather the latest version of the framework according to the
// reference assembly with which this assembly was built. As of this writing, we are building
// our bits on machines with Visual Studio 2015 that know about 4.6.1, so specifying
// VersionLatest would bake in the enum value for 4.6.1. But we need to run on machines with
// MSBuild that only know about Version46 (and no higher), so VersionLatest will fail there.
// Explicitly passing Version46 prevents this problem.
TargetDotNetFrameworkVersion.Version46
);
if (null == pathToDefaultManifest)
{
// This is rather unlikely, and the inproc compiler seems to log an error anyway.
// So just a message is fine.
Log.LogMessageFromResources
(
"General_ExpectedFileMissing",
"default.win32manifest"
);
}
return pathToDefaultManifest;
}
}
}
return win32Manifest;
}
}
}
| |
// 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.Storage
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// The Azure Storage Management API.
/// </summary>
public partial class StorageManagementClient : ServiceClient<StorageManagementClient>, IStorageManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify the Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IStorageAccountsOperations.
/// </summary>
public virtual IStorageAccountsOperations StorageAccounts { get; private set; }
/// <summary>
/// Gets the IUsageOperations.
/// </summary>
public virtual IUsageOperations Usage { get; private set; }
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected StorageManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected StorageManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected StorageManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected StorageManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
StorageAccounts = new StorageAccountsOperations(this);
Usage = new UsageOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
ApiVersion = "2016-05-01";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.ObjectModel;
using System.Management.Automation.Internal;
using System.Text;
namespace System.Management.Automation
{
/// <summary>
/// The parameter binder for native commands.
/// </summary>
///
internal class NativeCommandParameterBinder : ParameterBinderBase
{
#region ctor
/// <summary>
/// Constructs a NativeCommandParameterBinder
/// </summary>
///
/// <param name="command">
/// The NativeCommand to bind to.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// <paramref name="command"/>.Context is null
/// </exception>
internal NativeCommandParameterBinder(
NativeCommand command) : base(command.MyInvocation, command.Context, command)
{
_nativeCommand = command;
}
#endregion ctor
#region internal members
#region Parameter binding
/// <summary>
/// Binds a parameter for a native command (application).
/// </summary>
/// <param name="name">
/// The name of the parameter to bind the value to. For applications
/// this just becomes another parameter...
/// </param>
/// <param name="value">
/// The value to bind to the parameter. It should be assumed by
/// derived classes that the proper type coercion has already taken
/// place and that any prerequisite metadata has been satisfied.
/// </param>
/// <param name="parameterMetadata"></param>
internal override void BindParameter(string name, object value, CompiledCommandParameter parameterMetadata)
{
Diagnostics.Assert(false, "Unreachable code");
throw new NotSupportedException();
} // BindParameter
internal override object GetDefaultParameterValue(string name)
{
return null;
}
internal void BindParameters(Collection<CommandParameterInternal> parameters)
{
bool sawVerbatimArgumentMarker = false;
bool first = true;
foreach (CommandParameterInternal parameter in parameters)
{
if (!first)
{
_arguments.Append(' ');
}
first = false;
if (parameter.ParameterNameSpecified)
{
Diagnostics.Assert(parameter.ParameterText.IndexOf(' ') == -1, "Parameters cannot have whitespace");
_arguments.Append(parameter.ParameterText);
if (parameter.SpaceAfterParameter)
{
_arguments.Append(' ');
}
}
if (parameter.ArgumentSpecified)
{
// If this is the verbatim argument marker, we don't pass it on to the native command.
// We do need to remember it though - we'll expand environment variables in subsequent args.
object argValue = parameter.ArgumentValue;
if (string.Equals("--%", argValue as string, StringComparison.OrdinalIgnoreCase))
{
sawVerbatimArgumentMarker = true;
continue;
}
if (argValue != AutomationNull.Value && argValue != UnboundParameter.Value)
{
// ArrayIsSingleArgumentForNativeCommand is true when a comma is used in the
// command line, e.g.
// windbg -k com:port=\\devbox\pipe\debug,pipe,resets=0,reconnect
// The parser produced an array of strings but marked the parameter so we
// can properly reconstruct the correct command line.
appendOneNativeArgument(Context, argValue,
parameter.ArrayIsSingleArgumentForNativeCommand ? ',' : ' ',
sawVerbatimArgumentMarker);
}
}
}
}
#endregion Parameter binding
/// <summary>
/// Gets the command arguments in string form
/// </summary>
///
internal String Arguments
{
get
{
return _arguments.ToString();
}
} // Arguments
private readonly StringBuilder _arguments = new StringBuilder();
#endregion internal members
#region private members
/// <summary>
/// Stringize a non-IEnum argument to a native command, adding quotes
/// and trailing spaces as appropriate. An array gets added as multiple arguments
/// each of which will be stringized.
/// </summary>
/// <param name="context">Execution context instance</param>
/// <param name="obj">The object to append</param>
/// <param name="separator">A space or comma used when obj is enumerable</param>
/// <param name="sawVerbatimArgumentMarker">true if the argument occurs after --%</param>
private void appendOneNativeArgument(ExecutionContext context, object obj, char separator, bool sawVerbatimArgumentMarker)
{
IEnumerator list = LanguagePrimitives.GetEnumerator(obj);
bool needSeparator = false;
do
{
string arg;
if (list == null)
{
arg = PSObject.ToStringParser(context, obj);
}
else
{
if (!ParserOps.MoveNext(context, null, list))
{
break;
}
arg = PSObject.ToStringParser(context, ParserOps.Current(null, list));
}
if (!String.IsNullOrEmpty(arg))
{
if (needSeparator)
{
_arguments.Append(separator);
}
else
{
needSeparator = true;
}
if (sawVerbatimArgumentMarker)
{
arg = Environment.ExpandEnvironmentVariables(arg);
_arguments.Append(arg);
}
else
{
// We need to add quotes if the argument has unquoted spaces. The
// quotes could appear anywhere inside the string, not just at the start,
// e.g.
// $a = 'a"b c"d'
// echoargs $a 'a"b c"d' a"b c"d
//
// The above should see 3 identical arguments in argv (the command line will
// actually have quotes in different places, but the Win32 command line=>argv parser
// erases those differences.
//
// We need to check quotes that the win32 argument parser checks which is currently
// just the normal double quotes, no other special quotes. Also note that mismatched
// quotes are supported.
bool needQuotes = false, followingBackslash = false;
int quoteCount = 0;
for (int i = 0; i < arg.Length; i++)
{
if (arg[i] == '"' && !followingBackslash)
{
quoteCount += 1;
}
else if (char.IsWhiteSpace(arg[i]) && (quoteCount % 2 == 0))
{
needQuotes = true;
}
followingBackslash = arg[i] == '\\';
}
if (needQuotes)
{
_arguments.Append('"');
_arguments.Append(arg);
_arguments.Append('"');
}
else
{
_arguments.Append(arg);
}
}
}
} while (list != null);
}
/// <summary>
/// The native command to bind to
/// </summary>
private NativeCommand _nativeCommand;
#endregion private members
}
} // namespace System.Management.Automation
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Encog.MathUtil.Matrices
{
[TestClass]
public class TestMatrixMath
{
[TestMethod]
public void Inverse()
{
double[][] matrixData1 = {
new[] {1.0, 2.0, 3.0, 4.0}
};
double[][] matrixData2 = {
new[] {1.0},
new[] {2.0},
new[] {3.0},
new[] {4.0}
};
var matrix1 = new Matrix(matrixData1);
var checkMatrix = new Matrix(matrixData2);
Matrix matrix2 = MatrixMath.Transpose(matrix1);
Assert.IsTrue(matrix2.Equals(checkMatrix));
}
[TestMethod]
public void DotProduct()
{
double[][] matrixData1 = {new[] {1.0, 2.0, 3.0, 4.0}};
double[][] matrixData2 = {
new[] {5.0},
new[] {6.0},
new[] {7.0},
new[] {8.0}
};
var matrix1 = new Matrix(matrixData1);
var matrix2 = new Matrix(matrixData2);
double dotProduct = MatrixMath.DotProduct(matrix1, matrix2);
Assert.AreEqual(dotProduct, 70.0);
// test dot product errors
double[][] nonVectorData = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
double[][] differentLengthData = {
new[] {1.0}
};
var nonVector = new Matrix(nonVectorData);
var differentLength = new Matrix(differentLengthData);
try
{
MatrixMath.DotProduct(matrix1, nonVector);
Assert.IsTrue(false);
}
catch (MatrixError)
{
}
try
{
MatrixMath.DotProduct(nonVector, matrix2);
Assert.IsTrue(false);
}
catch (MatrixError)
{
}
try
{
MatrixMath.DotProduct(matrix1, differentLength);
Assert.IsTrue(false);
}
catch (MatrixError)
{
}
}
[TestMethod]
public void Multiply()
{
double[][] matrixData1 = {
new[] {1.0, 4.0},
new[] {2.0, 5.0},
new[] {3.0, 6.0}
};
double[][] matrixData2 = {
new[] {7.0, 8.0, 9.0},
new[] {10.0, 11.0, 12.0}
};
double[][] matrixData3 = {
new[] {47.0, 52.0, 57.0},
new[] {64.0, 71.0, 78.0},
new[] {81.0, 90.0, 99.0}
};
var matrix1 = new Matrix(matrixData1);
var matrix2 = new Matrix(matrixData2);
var matrix3 = new Matrix(matrixData3);
Matrix result = MatrixMath.Multiply(matrix1, matrix2);
Assert.IsTrue(result.Equals(matrix3));
}
[TestMethod]
public void VerifySame()
{
double[][] dataBase = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
double[][] dataTooManyRows = {
new[] {1.0, 2.0},
new[] {3.0, 4.0},
new[] {5.0, 6.0}
};
double[][] dataTooManyCols = {
new[] {1.0, 2.0, 3.0},
new[] {4.0, 5.0, 6.0}
};
var baseMatrix = new Matrix(dataBase);
var tooManyRows = new Matrix(dataTooManyRows);
var tooManyCols = new Matrix(dataTooManyCols);
MatrixMath.Add(baseMatrix, baseMatrix);
try
{
MatrixMath.Add(baseMatrix, tooManyRows);
Assert.IsFalse(true);
}
catch (MatrixError)
{
}
try
{
MatrixMath.Add(baseMatrix, tooManyCols);
Assert.IsFalse(true);
}
catch (MatrixError)
{
}
}
[TestMethod]
public void Divide()
{
double[][] data = {
new[] {2.0, 4.0},
new[] {6.0, 8.0}
};
var matrix = new Matrix(data);
Matrix result = MatrixMath.Divide(matrix, 2.0);
Assert.AreEqual(1.0, result[0, 0]);
}
[TestMethod]
public void Identity()
{
try
{
MatrixMath.Identity(0);
Assert.IsTrue(false);
}
catch (MatrixError)
{
}
double[][] checkData = {
new[] {1.0, 0.0},
new[] {0.0, 1.0}
};
var check = new Matrix(checkData);
Matrix matrix = MatrixMath.Identity(2);
Assert.IsTrue(check.Equals(matrix));
}
[TestMethod]
public void MultiplyScalar()
{
double[][] data = {
new[] {2.0, 4.0},
new[] {6.0, 8.0}
};
var matrix = new Matrix(data);
Matrix result = MatrixMath.Multiply(matrix, 2.0);
Assert.AreEqual(4.0, result[0, 0]);
}
[TestMethod]
public void DeleteRow()
{
double[][] origData = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
double[][] checkData = {new[] {3.0, 4.0}};
var orig = new Matrix(origData);
Matrix matrix = MatrixMath.DeleteRow(orig, 0);
var check = new Matrix(checkData);
Assert.IsTrue(check.Equals(matrix));
try
{
MatrixMath.DeleteRow(orig, 10);
Assert.IsTrue(false);
}
catch (MatrixError)
{
}
}
[TestMethod]
public void DeleteCol()
{
double[][] origData = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
double[][] checkData = {
new[] {2.0},
new[] {4.0}
};
var orig = new Matrix(origData);
Matrix matrix = MatrixMath.DeleteCol(orig, 0);
var check = new Matrix(checkData);
Assert.IsTrue(check.Equals(matrix));
try
{
MatrixMath.DeleteCol(orig, 10);
Assert.IsTrue(false);
}
catch (MatrixError)
{
}
}
[TestMethod]
public void Copy()
{
double[][] data = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
var source = new Matrix(data);
var target = new Matrix(2, 2);
MatrixMath.Copy(source, target);
Assert.IsTrue(source.Equals(target));
}
}
}
| |
#define MCG_WINRT_SUPPORTED
using Mcg.System;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
// -----------------------------------------------------------------------------------------------------------
//
// WARNING: THIS SOURCE FILE IS FOR 32-BIT BUILDS ONLY!
//
// MCG GENERATED CODE
//
// This C# source file is generated by MCG and is added into the application at compile time to support interop features.
//
// It has three primary components:
//
// 1. Public type definitions with interop implementation used by this application including WinRT & COM data structures and P/Invokes.
//
// 2. The 'McgInterop' class containing marshaling code that acts as a bridge from managed code to native code.
//
// 3. The 'McgNative' class containing marshaling code and native type definitions that call into native code and are called by native code.
//
// -----------------------------------------------------------------------------------------------------------
//
// warning CS0067: The event 'event' is never used
#pragma warning disable 67
// warning CS0169: The field 'field' is never used
#pragma warning disable 169
// warning CS0649: Field 'field' is never assigned to, and will always have its default value 0
#pragma warning disable 414
// warning CS0414: The private field 'field' is assigned but its value is never used
#pragma warning disable 649
// warning CS1591: Missing XML comment for publicly visible type or member 'Type_or_Member'
#pragma warning disable 1591
// warning CS0108 'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.
#pragma warning disable 108
// warning CS0114 'member1' hides inherited member 'member2'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.
#pragma warning disable 114
// warning CS0659 'type' overrides Object.Equals but does not override GetHashCode.
#pragma warning disable 659
// warning CS0465 Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?
#pragma warning disable 465
// warning CS0028 'function declaration' has the wrong signature to be an entry point
#pragma warning disable 28
// warning CS0162 Unreachable code Detected
#pragma warning disable 162
// warning CS0628 new protected member declared in sealed class
#pragma warning disable 628
namespace McgInterop
{
/// <summary>
/// P/Invoke class for module '[MRT]'
/// </summary>
public unsafe static partial class _MRT_
{
// Signature, RhWaitForPendingFinalizers, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhWaitForPendingFinalizers")]
public static void RhWaitForPendingFinalizers(int allowReentrantWait)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.RhWaitForPendingFinalizers(allowReentrantWait);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, RhCompatibleReentrantWaitAny, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr___ptr__w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhCompatibleReentrantWaitAny")]
public static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop._MRT__PInvokes.RhCompatibleReentrantWaitAny(
alertable,
timeout,
count,
((global::System.IntPtr*)handles)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, _ecvt_s, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "_ecvt_s")]
public static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes._ecvt_s(
((byte*)buffer),
sizeInBytes,
value,
count,
((int*)dec),
((int*)sign)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, memmove, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "memmove")]
public static void memmove(
byte* dmem,
byte* smem,
uint size)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.memmove(
((byte*)dmem),
((byte*)smem),
size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module '*'
/// </summary>
public unsafe static partial class _
{
// Signature, CallingConventionConverter_GetStubs, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_GetStubs")]
public static void CallingConventionConverter_GetStubs(
out global::System.IntPtr returnVoidStub,
out global::System.IntPtr returnIntegerStub,
out global::System.IntPtr commonStub)
{
// Setup
global::System.IntPtr unsafe_returnVoidStub;
global::System.IntPtr unsafe_returnIntegerStub;
global::System.IntPtr unsafe_commonStub;
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_GetStubs(
&(unsafe_returnVoidStub),
&(unsafe_returnIntegerStub),
&(unsafe_commonStub)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
commonStub = unsafe_commonStub;
returnIntegerStub = unsafe_returnIntegerStub;
returnVoidStub = unsafe_returnVoidStub;
// Return
}
// Signature, CallingConventionConverter_SpecifyCommonStubData, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_SpecifyCommonStubData")]
public static void CallingConventionConverter_SpecifyCommonStubData(global::System.IntPtr commonStubData)
{
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_SpecifyCommonStubData(commonStubData);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-errorhandling-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll
{
// Signature, GetLastError, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.Extensions, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetLastError")]
public static int GetLastError()
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes.GetLastError();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll
{
// Signature, RoInitialize, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "RoInitialize")]
public static int RoInitialize(uint initType)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_l1_1_0_dll_PInvokes.RoInitialize(initType);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-handle-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_handle_l1_1_0_dll
{
// Signature, CloseHandle, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CloseHandle")]
public static bool CloseHandle(global::System.IntPtr handle)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_handle_l1_1_0_dll_PInvokes.CloseHandle(handle);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
// Return
return unsafe___value != 0;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-localization-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll
{
// Signature, IsValidLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "IsValidLocaleName")]
public static int IsValidLocaleName(char* lpLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.IsValidLocaleName(((ushort*)lpLocaleName));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ResolveLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "ResolveLocaleName")]
public static int ResolveLocaleName(
char* lpNameToResolve,
char* lpLocaleName,
int cchLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.ResolveLocaleName(
((ushort*)lpNameToResolve),
((ushort*)lpLocaleName),
cchLocaleName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, GetCPInfoExW, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages___ptr__Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Text.Encoding.CodePages, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetCPInfoExW")]
public static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.GetCPInfoExW(
CodePage,
dwFlags,
((global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages*)lpCPInfoEx)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-com-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll
{
// Signature, CoCreateInstance, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.StackTraceGenerator.StackTraceGenerator", "CoCreateInstance")]
public static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
out global::System.IntPtr ppv)
{
// Setup
global::System.IntPtr unsafe_ppv;
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_com_l1_1_0_dll_PInvokes.CoCreateInstance(
((byte*)rclsid),
pUnkOuter,
dwClsContext,
((byte*)riid),
&(unsafe_ppv)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
ppv = unsafe_ppv;
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'clrcompression.dll'
/// </summary>
public unsafe static partial class clrcompression_dll
{
// Signature, deflateInit2_, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflateInit2_")]
public static int deflateInit2_(
byte* stream,
int level,
int method,
int windowBits,
int memLevel,
int strategy,
byte* version,
int stream_size)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflateInit2_(
((byte*)stream),
level,
method,
windowBits,
memLevel,
strategy,
((byte*)version),
stream_size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, deflateEnd, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflateEnd")]
public static int deflateEnd(byte* strm)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflateEnd(((byte*)strm));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, inflateEnd, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "inflateEnd")]
public static int inflateEnd(byte* stream)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.inflateEnd(((byte*)stream));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, deflate, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflate")]
public static int deflate(
byte* stream,
int flush)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflate(
((byte*)stream),
flush
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'OleAut32'
/// </summary>
public unsafe static partial class OleAut32
{
// Signature, SysFreeString, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.LightweightInterop.MarshalExtensions", "SysFreeString")]
public static void SysFreeString(global::System.IntPtr bstr)
{
// Marshalling
// Call to native method
global::McgInterop.OleAut32_PInvokes.SysFreeString(bstr);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-robuffer-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll
{
// Signature, RoGetBufferMarshaler, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.ComInterfaceMarshaller] System_Runtime_InteropServices_IMarshal__System_Runtime_WindowsRuntime__System_Runtime_InteropServices__IMarshal__System_Runtime_WindowsRuntime *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop+mincore_PInvokes", "RoGetBufferMarshaler")]
public static int RoGetBufferMarshaler(out global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime bufferMarshalerPtr)
{
// Setup
global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl** unsafe_bufferMarshalerPtr = default(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl**);
int unsafe___value;
try
{
// Marshalling
unsafe_bufferMarshalerPtr = null;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes.RoGetBufferMarshaler(&(unsafe_bufferMarshalerPtr));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
bufferMarshalerPtr = (global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime)global::System.Runtime.InteropServices.McgModuleManager.ComInterfaceToObject(
((global::System.IntPtr)unsafe_bufferMarshalerPtr),
global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("System.Runtime.InteropServices.IMarshal,System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, Public" +
"KeyToken=b77a5c561934e089")
);
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(new global::System.IntPtr(((void*)unsafe_bufferMarshalerPtr)));
}
}
}
public unsafe static partial class _MRT__PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void RhWaitForPendingFinalizers(int allowReentrantWait);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void memmove(
byte* dmem,
byte* smem,
uint size);
}
public unsafe static partial class __PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_GetStubs(
global::System.IntPtr* returnVoidStub,
global::System.IntPtr* returnIntegerStub,
global::System.IntPtr* commonStub);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_SpecifyCommonStubData(global::System.IntPtr commonStubData);
}
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-errorhandling-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetLastError();
}
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RoInitialize(uint initType);
}
public unsafe static partial class api_ms_win_core_handle_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-handle-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CloseHandle(global::System.IntPtr handle);
}
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int IsValidLocaleName(ushort* lpLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ResolveLocaleName(
ushort* lpNameToResolve,
ushort* lpLocaleName,
int cchLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx);
}
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-com-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
global::System.IntPtr* ppv);
}
public unsafe static partial class clrcompression_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflateInit2_(
byte* stream,
int level,
int method,
int windowBits,
int memLevel,
int strategy,
byte* version,
int stream_size);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflateEnd(byte* strm);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int inflateEnd(byte* stream);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflate(
byte* stream,
int flush);
}
public unsafe static partial class OleAut32_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("oleaut32.dll", EntryPoint="#6", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void SysFreeString(global::System.IntPtr bstr);
}
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-robuffer-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.StdCall)]
public extern static int RoGetBufferMarshaler(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl*** bufferMarshalerPtr);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using Castle.Core;
using Castle.Core.Configuration;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
using Castle.Windsor;
using Rhino.ServiceBus.Actions;
using Rhino.ServiceBus.Config;
using Rhino.ServiceBus.Convertors;
using Rhino.ServiceBus.DataStructures;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.LoadBalancer;
using Rhino.ServiceBus.MessageModules;
using Rhino.ServiceBus.Msmq;
using Rhino.ServiceBus.Msmq.TransportActions;
using ErrorAction = Rhino.ServiceBus.Msmq.TransportActions.ErrorAction;
using IStartable = Rhino.ServiceBus.Internal.IStartable;
using LoadBalancerConfiguration = Rhino.ServiceBus.LoadBalancer.LoadBalancerConfiguration;
using System.Reflection;
namespace Rhino.ServiceBus.Castle
{
public class CastleBuilder : IBusContainerBuilder
{
private readonly IWindsorContainer container;
private readonly AbstractRhinoServiceBusConfiguration config;
public CastleBuilder(IWindsorContainer container, AbstractRhinoServiceBusConfiguration config)
{
this.container = container;
this.config = config;
this.config.BuildWith(this);
}
public void WithInterceptor(IConsumerInterceptor interceptor)
{
container.Kernel.ComponentModelCreated +=
model =>
{
if (typeof(IMessageConsumer).IsAssignableFrom(model.Implementation) == false)
return;
model.LifestyleType = LifestyleType.Transient;
interceptor.ItemCreated(model.Implementation, true);
};
}
public void RegisterDefaultServices(IEnumerable<Assembly> assemblies)
{
if (!container.Kernel.HasComponent(typeof(IWindsorContainer)))
container.Register(Component.For<IWindsorContainer>().Instance(container));
container.Register(Component.For<IServiceLocator>().ImplementedBy<CastleServiceLocator>());
foreach (var assembly in assemblies)
container.Register(
AllTypes.FromAssembly(assembly)
.BasedOn<IBusConfigurationAware>().WithService.FirstInterface()
);
var locator = container.Resolve<IServiceLocator>();
foreach (var configurationAware in container.ResolveAll<IBusConfigurationAware>())
configurationAware.Configure(config, this, locator);
container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));
foreach (var type in config.MessageModules)
if (!container.Kernel.HasComponent(type))
container.Register(Component.For(type).Named(type.FullName));
container.Register(
Component.For<IReflection>()
.LifeStyle.Is(LifestyleType.Singleton)
.ImplementedBy<CastleReflection>(),
Component.For<IMessageSerializer>()
.LifeStyle.Is(LifestyleType.Singleton)
.ImplementedBy(config.SerializerType),
Component.For<IEndpointRouter>()
.ImplementedBy<EndpointRouter>());
}
public void RegisterBus()
{
var busConfig = (RhinoServiceBusConfiguration)config;
container.Register(
Component.For<IDeploymentAction>()
.ImplementedBy<CreateLogQueueAction>(),
Component.For<IDeploymentAction>()
.ImplementedBy<CreateQueuesAction>(),
Component.For<IServiceBus, IStartableServiceBus, IStartable>()
.ImplementedBy<DefaultServiceBus>()
.LifeStyle.Is(LifestyleType.Singleton)
.DependsOn(new
{
messageOwners = busConfig.MessageOwners.ToArray(),
})
.DependsOn(Dependency.OnConfigValue("modules", CreateModuleConfigurationNode(busConfig.MessageModules))));
}
private static IConfiguration CreateModuleConfigurationNode(IEnumerable<Type> messageModules)
{
var config = new MutableConfiguration("array");
foreach (Type type in messageModules)
config.CreateChild("item", "${" + type.FullName + "}");
return config;
}
public void RegisterPrimaryLoadBalancer()
{
var loadBalancerConfig = (LoadBalancerConfiguration)config;
container.Register(Component.For<MsmqLoadBalancer, IStartable>()
.ImplementedBy(loadBalancerConfig.LoadBalancerType)
.LifeStyle.Is(LifestyleType.Singleton)
.DependsOn(new
{
endpoint = loadBalancerConfig.Endpoint,
threadCount = loadBalancerConfig.ThreadCount,
primaryLoadBalancer = loadBalancerConfig.PrimaryLoadBalancer,
transactional = loadBalancerConfig.Transactional
}));
container.Register(
Component.For<IDeploymentAction>()
.ImplementedBy<CreateLoadBalancerQueuesAction>());
}
public void RegisterSecondaryLoadBalancer()
{
var loadBalancerConfig = (LoadBalancerConfiguration)config;
container.Register(Component.For<MsmqLoadBalancer>()
.ImplementedBy(loadBalancerConfig.LoadBalancerType)
.LifeStyle.Is(LifestyleType.Singleton)
.DependsOn(new
{
endpoint = loadBalancerConfig.Endpoint,
threadCount = loadBalancerConfig.ThreadCount,
primaryLoadBalancer = loadBalancerConfig.PrimaryLoadBalancer,
transactional = loadBalancerConfig.Transactional,
secondaryLoadBalancer = loadBalancerConfig.SecondaryLoadBalancer,
}));
container.Register(
Component.For<IDeploymentAction>()
.ImplementedBy<CreateLoadBalancerQueuesAction>());
}
public void RegisterReadyForWork()
{
var loadBalancerConfig = (LoadBalancerConfiguration)config;
container.Register(Component.For<MsmqReadyForWorkListener>()
.LifeStyle.Is(LifestyleType.Singleton)
.DependsOn(new
{
endpoint = loadBalancerConfig.ReadyForWork,
threadCount = loadBalancerConfig.ThreadCount,
transactional = loadBalancerConfig.Transactional
}));
container.Register(
Component.For<IDeploymentAction>()
.ImplementedBy<CreateReadyForWorkQueuesAction>());
}
public void RegisterLoadBalancerEndpoint(Uri loadBalancerEndpoint)
{
container.Register(
Component.For<LoadBalancerMessageModule>()
.DependsOn(new { loadBalancerEndpoint }));
}
public void RegisterLoggingEndpoint(Uri logEndpoint)
{
container.Register(
Component.For<MessageLoggingModule>()
.DependsOn(new { logQueue = logEndpoint }));
}
public void RegisterSingleton<T>(Func<T> func)
where T : class
{
T singleton = null;
container.Register(
Component.For<T>()
.UsingFactoryMethod<T>(x => singleton == null ? singleton = func() : singleton));
}
public void RegisterSingleton<T>(string name, Func<T> func)
where T : class
{
T singleton = null;
container.Register(
Component.For<T>()
.UsingFactoryMethod<T>(x => singleton == null ? singleton = func() : singleton).Named(name));
}
public void RegisterAll<T>(params Type[] excludes)
where T : class { RegisterAll<T>((Predicate<Type>)(x => !excludes.Contains(x))); }
public void RegisterAll<T>(Predicate<Type> condition)
where T : class
{
container.Kernel.Register(
AllTypes.FromAssembly(typeof(T).Assembly)
.BasedOn<T>()
.Unless(x => !condition(x))
.WithService.FirstInterface()
.Configure(registration =>
registration.LifeStyle.Is(LifestyleType.Singleton)));
}
public void RegisterSecurity(byte[] key)
{
container.Register(
Component.For<IEncryptionService>()
.ImplementedBy<RijndaelEncryptionService>()
.DependsOn(new
{
key,
})
.Named("esb.security"));
container.Register(
Component.For<IValueConvertor<WireEncryptedString>>()
.ImplementedBy<WireEncryptedStringConvertor>()
.DependsOn(Dependency.OnComponent("encryptionService", "esb.security")));
container.Register(
Component.For<IElementSerializationBehavior>()
.ImplementedBy<WireEncryptedMessageConvertor>()
.DependsOn(Dependency.OnComponent("encryptionService", "esb.security")));
}
public void RegisterNoSecurity()
{
container.Register(
Component.For<IValueConvertor<WireEncryptedString>>()
.ImplementedBy<ThrowingWireEncryptedStringConvertor>());
container.Register(
Component.For<IElementSerializationBehavior>()
.ImplementedBy<ThrowingWireEncryptedMessageConvertor>());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ConvertToVector128Int64Int32()
{
var test = new SimpleUnaryOpTest__ConvertToVector128Int64Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ConvertToVector128Int64Int32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int RetElementCount = VectorSize / sizeof(Int64);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int32> _dataTable;
static SimpleUnaryOpTest__ConvertToVector128Int64Int32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ConvertToVector128Int64Int32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int32>(_data, new Int64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.ConvertToVector128Int64(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.ConvertToVector128Int64(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.ConvertToVector128Int64(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.ConvertToVector128Int64(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr);
var result = Sse41.ConvertToVector128Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.ConvertToVector128Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.ConvertToVector128Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ConvertToVector128Int64Int32();
var result = Sse41.ConvertToVector128Int64(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.ConvertToVector128Int64(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
if (result[0] != firstOp[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != firstOp[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.ConvertToVector128Int64)}<Int64>(Vector128<Int32>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
namespace TypedRest.Endpoints.Generic;
[Collection("Endpoint")]
public class ElementEndpointTest : EndpointTestBase
{
private readonly ElementEndpoint<MockEntity> _endpoint;
public ElementEndpointTest()
{
_endpoint = new(EntryEndpoint, "endpoint");
}
[Fact]
public async Task TestRead()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(JsonMime, "{\"id\":5,\"name\":\"test\"}");
var result = await _endpoint.ReadAsync();
result.Should().Be(new MockEntity(5, "test"));
}
[Fact]
public async Task TestReadCustomMimeWithJsonSuffix()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond("application/sample+json", "{\"id\":5,\"name\":\"test\"}");
var result = await _endpoint.ReadAsync();
result.Should().Be(new MockEntity(5, "test"));
}
[Fact]
public async Task TestReadCacheETag()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new()
{
Content = new StringContent("{\"id\":5,\"name\":\"test\"}", Encoding.UTF8, JsonMime),
Headers = {ETag = new("\"123abc\"")}
});
var result1 = await _endpoint.ReadAsync();
result1.Should().Be(new MockEntity(5, "test"));
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.WithHeaders("If-None-Match", "\"123abc\"")
.Respond(HttpStatusCode.NotModified);
var result2 = await _endpoint.ReadAsync();
result2.Should().Be(new MockEntity(5, "test"));
result2.Should().NotBeSameAs(result1,
because: "Cache responses, not deserialized objects");
}
[Fact]
public async Task TestReadCacheLastModified()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new()
{
Content = new StringContent("{\"id\":5,\"name\":\"test\"}", Encoding.UTF8, JsonMime)
{
Headers = {LastModified = new(new DateTime(2015, 10, 21), TimeSpan.Zero)}
}
});
var result1 = await _endpoint.ReadAsync();
result1.Should().Be(new MockEntity(5, "test"));
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.WithHeaders("If-Modified-Since", "Wed, 21 Oct 2015 00:00:00 GMT")
.Respond(HttpStatusCode.NotModified);
var result2 = await _endpoint.ReadAsync();
result2.Should().Be(new MockEntity(5, "test"));
result2.Should().NotBeSameAs(result1,
because: "Cache responses, not deserialized objects");
}
[Fact]
public async Task TestExistsTrue()
{
Mock.Expect(HttpMethod.Head, "http://localhost/endpoint")
.Respond(HttpStatusCode.OK);
bool result = await _endpoint.ExistsAsync();
result.Should().BeTrue();
}
[Fact]
public async Task TestExistsFalse()
{
Mock.Expect(HttpMethod.Head, "http://localhost/endpoint")
.Respond(HttpStatusCode.NotFound);
bool result = await _endpoint.ExistsAsync();
result.Should().BeFalse();
}
[Fact]
public async Task TestSetResult()
{
Mock.Expect(HttpMethod.Put, "http://localhost/endpoint")
.WithContent("{\"id\":5,\"name\":\"test\"}")
.Respond(JsonMime, "{\"id\":5,\"name\":\"testXXX\"}");
var result = await _endpoint.SetAsync(new MockEntity(5, "test"));
result.Should().Be(new MockEntity(5, "testXXX"));
}
[Fact]
public async Task TestSetNoResult()
{
Mock.Expect(HttpMethod.Put, "http://localhost/endpoint")
.WithContent("{\"id\":5,\"name\":\"test\"}")
.Respond(HttpStatusCode.NoContent);
var result = await _endpoint.SetAsync(new MockEntity(5, "test"));
result.Should().BeNull();
}
[Fact]
public async Task TestSetETag()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new()
{
Content = new StringContent("{\"id\":5,\"name\":\"test\"}", Encoding.UTF8, JsonMime),
Headers = {ETag = new("\"123abc\"")}
});
var result = await _endpoint.ReadAsync();
Mock.Expect(HttpMethod.Put, "http://localhost/endpoint")
.WithContent("{\"id\":5,\"name\":\"test\"}")
.WithHeaders("If-Match", "\"123abc\"")
.Respond(HttpStatusCode.NoContent);
await _endpoint.SetAsync(result);
}
[Fact]
public async Task TestSetLastModified()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new()
{
Content = new StringContent("{\"id\":5,\"name\":\"test\"}", Encoding.UTF8, JsonMime)
{
Headers = {LastModified = new(new DateTime(2015, 10, 21), TimeSpan.Zero)}
}
});
var result = await _endpoint.ReadAsync();
Mock.Expect(HttpMethod.Put, "http://localhost/endpoint")
.WithContent("{\"id\":5,\"name\":\"test\"}")
.WithHeaders("If-Unmodified-Since", "Wed, 21 Oct 2015 00:00:00 GMT")
.Respond(HttpStatusCode.NoContent);
await _endpoint.SetAsync(result);
}
[Fact]
public async Task TestUpdateRetry()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new()
{
Content = new StringContent("{\"id\":5,\"name\":\"test1\"}", Encoding.UTF8, JsonMime),
Headers = {ETag = new("\"1\"")}
});
Mock.Expect(HttpMethod.Put, "http://localhost/endpoint")
.WithContent("{\"id\":5,\"name\":\"testX\"}")
.WithHeaders("If-Match", "\"1\"")
.Respond(HttpStatusCode.PreconditionFailed);
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new()
{
Content = new StringContent("{\"id\":5,\"name\":\"test2\"}", Encoding.UTF8, JsonMime),
Headers = {ETag = new("\"2\"")}
});
Mock.Expect(HttpMethod.Put, "http://localhost/endpoint")
.WithContent("{\"id\":5,\"name\":\"testX\"}")
.WithHeaders("If-Match", "\"2\"")
.Respond(HttpStatusCode.NoContent);
await _endpoint.UpdateAsync(x => x.Name = "testX");
}
[Fact]
public async Task TestUpdateFail()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new()
{
Content = new StringContent("{\"id\":5,\"name\":\"test1\"}", Encoding.UTF8, JsonMime),
Headers = {ETag = new("\"1\"")}
});
Mock.Expect(HttpMethod.Put, "http://localhost/endpoint")
.WithContent("{\"id\":5,\"name\":\"testX\"}")
.WithHeaders("If-Match", "\"1\"")
.Respond(HttpStatusCode.PreconditionFailed);
await Assert.ThrowsAsync<InvalidOperationException>(async () => await _endpoint.UpdateAsync(x => x.Name = "testX", maxRetries: 0));
}
[Fact]
public async Task TestJsonPatch()
{
Mock.Expect(HttpMethods.Patch, "http://localhost/endpoint")
.WithContent("[{\"value\":\"testX\",\"path\":\"/name\",\"op\":\"replace\"}]")
.Respond(JsonMime, "{\"id\":5,\"name\":\"testX\"}");
var result = await _endpoint.UpdateAsync(patch => patch.Replace(x => x.Name, "testX"));
result.Should().Be(new MockEntity(5, "testX"));
}
[Fact]
public async Task TestJsonPatchFallback()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new()
{
Content = new StringContent("{\"id\":5,\"name\":\"test1\"}", Encoding.UTF8, JsonMime)
});
Mock.Expect(HttpMethod.Put, "http://localhost/endpoint")
.WithContent("{\"id\":5,\"name\":\"testX\"}")
.Respond(JsonMime, "{\"id\":5,\"name\":\"testX\"}");
var result = await _endpoint.UpdateAsync(patch => patch.Replace(x => x.Name, "testX"));
result.Should().Be(new MockEntity(5, "testX"));
}
[Fact]
public async Task TestMergeResult()
{
Mock.Expect(HttpMethods.Patch, "http://localhost/endpoint")
.WithContent("{\"id\":5,\"name\":\"test\"}")
.Respond(JsonMime, "{\"id\":5,\"name\":\"testXXX\"}");
var result = await _endpoint.MergeAsync(new MockEntity(5, "test"));
result.Should().Be(new MockEntity(5, "testXXX"));
}
[Fact]
public async Task TestMergeNoResult()
{
Mock.Expect(HttpMethods.Patch, "http://localhost/endpoint")
.WithContent("{\"id\":5,\"name\":\"test\"}")
.Respond(HttpStatusCode.NoContent);
var result = await _endpoint.MergeAsync(new MockEntity(5, "test"));
result.Should().BeNull();
}
[Fact]
public async Task TestDelete()
{
Mock.Expect(HttpMethod.Delete, "http://localhost/endpoint")
.Respond(HttpStatusCode.NoContent);
await _endpoint.DeleteAsync();
}
[Fact]
public async Task TestDeleteETag()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new()
{
Content = new StringContent("{\"id\":5,\"name\":\"test\"}", Encoding.UTF8, JsonMime),
Headers = {ETag = new("\"123abc\"")}
});
await _endpoint.ReadAsync();
Mock.Expect(HttpMethod.Delete, "http://localhost/endpoint")
.WithHeaders("If-Match", "\"123abc\"")
.Respond(HttpStatusCode.NoContent);
await _endpoint.DeleteAsync();
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSLF.Model;
using NPOI.ddf.EscherArrayProperty;
using NPOI.ddf.EscherContainerRecord;
using NPOI.ddf.EscherOptRecord;
using NPOI.ddf.EscherProperties;
using NPOI.ddf.EscherSimpleProperty;
using NPOI.util.LittleEndian;
using NPOI.util.POILogger;
/**
* A "Freeform" shape.
*
* <p>
* Shapes Drawn with the "Freeform" tool have cubic bezier curve segments in the smooth sections
* and straight-line segments in the straight sections. This object closely corresponds to <code>java.awt.geom.GeneralPath</code>.
* </p>
* @author Yegor Kozlov
*/
public class Freeform : AutoShape {
public static byte[] SEGMENTINFO_MOVETO = new byte[]{0x00, 0x40};
public static byte[] SEGMENTINFO_LINETO = new byte[]{0x00, (byte)0xAC};
public static byte[] SEGMENTINFO_ESCAPE = new byte[]{0x01, 0x00};
public static byte[] SEGMENTINFO_ESCAPE2 = new byte[]{0x01, 0x20};
public static byte[] SEGMENTINFO_CUBICTO = new byte[]{0x00, (byte)0xAD};
public static byte[] SEGMENTINFO_CUBICTO2 = new byte[]{0x00, (byte)0xB3}; //OpenOffice inserts 0xB3 instead of 0xAD.
public static byte[] SEGMENTINFO_CLOSE = new byte[]{0x01, (byte)0x60};
public static byte[] SEGMENTINFO_END = new byte[]{0x00, (byte)0x80};
/**
* Create a Freeform object and Initialize it from the supplied Record Container.
*
* @param escherRecord <code>EscherSpContainer</code> Container which holds information about this shape
* @param parent the parent of the shape
*/
protected Freeform(EscherContainerRecord escherRecord, Shape parent){
base(escherRecord, parent);
}
/**
* Create a new Freeform. This constructor is used when a new shape is Created.
*
* @param parent the parent of this Shape. For example, if this text box is a cell
* in a table then the parent is Table.
*/
public Freeform(Shape parent){
base(null, parent);
_escherContainer = CreateSpContainer(ShapeTypes.NotPrimitive, parent is ShapeGroup);
}
/**
* Create a new Freeform. This constructor is used when a new shape is Created.
*
*/
public Freeform(){
this(null);
}
/**
* Set the shape path
*
* @param path
*/
public void SetPath(GeneralPath path)
{
Rectangle2D bounds = path.GetBounds2D();
PathIterator it = path.GetPathIterator(new AffineTransform());
List<byte[]> segInfo = new List<byte[]>();
List<Point2D.Double> pntInfo = new List<Point2D.Double>();
bool IsClosed = false;
while (!it.IsDone()) {
double[] vals = new double[6];
int type = it.currentSegment(vals);
switch (type) {
case PathIterator.SEG_MOVETO:
pntInfo.Add(new Point2D.Double(vals[0], vals[1]));
segInfo.Add(SEGMENTINFO_MOVETO);
break;
case PathIterator.SEG_LINETO:
pntInfo.Add(new Point2D.Double(vals[0], vals[1]));
segInfo.Add(SEGMENTINFO_LINETO);
segInfo.Add(SEGMENTINFO_ESCAPE);
break;
case PathIterator.SEG_CUBICTO:
pntInfo.Add(new Point2D.Double(vals[0], vals[1]));
pntInfo.Add(new Point2D.Double(vals[2], vals[3]));
pntInfo.Add(new Point2D.Double(vals[4], vals[5]));
segInfo.Add(SEGMENTINFO_CUBICTO);
segInfo.Add(SEGMENTINFO_ESCAPE2);
break;
case PathIterator.SEG_QUADTO:
//TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO
logger.log(POILogger.WARN, "SEG_QUADTO is not supported");
break;
case PathIterator.SEG_CLOSE:
pntInfo.Add(pntInfo.Get(0));
segInfo.Add(SEGMENTINFO_LINETO);
segInfo.Add(SEGMENTINFO_ESCAPE);
segInfo.Add(SEGMENTINFO_LINETO);
segInfo.Add(SEGMENTINFO_CLOSE);
isClosed = true;
break;
}
it.next();
}
if(!isClosed) segInfo.Add(SEGMENTINFO_LINETO);
segInfo.Add(new byte[]{0x00, (byte)0x80});
EscherOptRecord opt = (EscherOptRecord)getEscherChild(_escherContainer, EscherOptRecord.RECORD_ID);
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4));
EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null);
verticesProp.SetNumberOfElementsInArray(pntInfo.Count);
verticesProp.SetNumberOfElementsInMemory(pntInfo.Count);
verticesProp.SetSizeOfElements(0xFFF0);
for (int i = 0; i < pntInfo.Count; i++) {
Point2D.Double pnt = pntInfo.Get(i);
byte[] data = new byte[4];
LittleEndian.Putshort(data, 0, (short)((pnt.GetX() - bounds.GetX())*MASTER_DPI/POINT_DPI));
LittleEndian.Putshort(data, 2, (short)((pnt.GetY() - bounds.GetY())*MASTER_DPI/POINT_DPI));
verticesProp.SetElement(i, data);
}
opt.AddEscherProperty(verticesProp);
EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null);
segmentsProp.SetNumberOfElementsInArray(segInfo.Count);
segmentsProp.SetNumberOfElementsInMemory(segInfo.Count);
segmentsProp.SetSizeOfElements(0x2);
for (int i = 0; i < segInfo.Count; i++) {
byte[] seg = segInfo.Get(i);
segmentsProp.SetElement(i, seg);
}
opt.AddEscherProperty(segmentsProp);
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, (int)(bounds.Width*MASTER_DPI/POINT_DPI)));
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, (int)(bounds.Height*MASTER_DPI/POINT_DPI)));
opt.sortProperties();
SetAnchor(bounds);
}
/**
* Gets the freeform path
*
* @return the freeform path
*/
public GeneralPath GetPath(){
EscherOptRecord opt = (EscherOptRecord)getEscherChild(_escherContainer, EscherOptRecord.RECORD_ID);
opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4));
EscherArrayProperty verticesProp = (EscherArrayProperty)getEscherProperty(opt, (short)(EscherProperties.GEOMETRY__VERTICES + 0x4000));
if(verticesProp == null) verticesProp = (EscherArrayProperty)getEscherProperty(opt, EscherProperties.GEOMETRY__VERTICES);
EscherArrayProperty segmentsProp = (EscherArrayProperty)getEscherProperty(opt, (short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000));
if(segmentsProp == null) segmentsProp = (EscherArrayProperty)getEscherProperty(opt, EscherProperties.GEOMETRY__SEGMENTINFO);
//sanity check
if(verticesProp == null) {
logger.log(POILogger.WARN, "Freeform is missing GEOMETRY__VERTICES ");
return null;
}
if(segmentsProp == null) {
logger.log(POILogger.WARN, "Freeform is missing GEOMETRY__SEGMENTINFO ");
return null;
}
GeneralPath path = new GeneralPath();
int numPoints = verticesProp.GetNumberOfElementsInArray();
int numSegments = segmentsProp.GetNumberOfElementsInArray();
for (int i = 0, j = 0; i < numSegments && j < numPoints; i++) {
byte[] elem = segmentsProp.GetElement(i);
if(Arrays.Equals(elem, SEGMENTINFO_MOVETO)){
byte[] p = verticesProp.GetElement(j++);
short x = LittleEndian.Getshort(p, 0);
short y = LittleEndian.Getshort(p, 2);
path.moveTo(
((float)x*POINT_DPI/MASTER_DPI),
((float)y*POINT_DPI/MASTER_DPI));
} else if (Arrays.Equals(elem, SEGMENTINFO_CUBICTO) || Arrays.Equals(elem, SEGMENTINFO_CUBICTO2)){
i++;
byte[] p1 = verticesProp.GetElement(j++);
short x1 = LittleEndian.Getshort(p1, 0);
short y1 = LittleEndian.Getshort(p1, 2);
byte[] p2 = verticesProp.GetElement(j++);
short x2 = LittleEndian.Getshort(p2, 0);
short y2 = LittleEndian.Getshort(p2, 2);
byte[] p3 = verticesProp.GetElement(j++);
short x3 = LittleEndian.Getshort(p3, 0);
short y3 = LittleEndian.Getshort(p3, 2);
path.curveTo(
((float)x1*POINT_DPI/MASTER_DPI), ((float)y1*POINT_DPI/MASTER_DPI),
((float)x2*POINT_DPI/MASTER_DPI), ((float)y2*POINT_DPI/MASTER_DPI),
((float)x3*POINT_DPI/MASTER_DPI), ((float)y3*POINT_DPI/MASTER_DPI));
} else if (Arrays.Equals(elem, SEGMENTINFO_LINETO)){
i++;
byte[] pnext = segmentsProp.GetElement(i);
if(Arrays.Equals(pnext, SEGMENTINFO_ESCAPE)){
if(j + 1 < numPoints){
byte[] p = verticesProp.GetElement(j++);
short x = LittleEndian.Getshort(p, 0);
short y = LittleEndian.Getshort(p, 2);
path.lineTo(
((float)x*POINT_DPI/MASTER_DPI), ((float)y*POINT_DPI/MASTER_DPI));
}
} else if (Arrays.Equals(pnext, SEGMENTINFO_CLOSE)){
path.ClosePath();
}
}
}
return path;
}
public java.awt.Shape GetOutline(){
GeneralPath path = GetPath();
Rectangle2D anchor = GetAnchor2D();
Rectangle2D bounds = path.GetBounds2D();
AffineTransform at = new AffineTransform();
at.translate(anchor.GetX(), anchor.GetY());
at.scale(
anchor.Width/bounds.Width,
anchor.Height/bounds.Height
);
return at.CreateTransformedShape(path);
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>DistanceView</c> resource.</summary>
public sealed partial class DistanceViewName : gax::IResourceName, sys::IEquatable<DistanceViewName>
{
/// <summary>The possible contents of <see cref="DistanceViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>.
/// </summary>
CustomerPlaceholderChainDistanceBucket = 1,
}
private static gax::PathTemplate s_customerPlaceholderChainDistanceBucket = new gax::PathTemplate("customers/{customer_id}/distanceViews/{placeholder_chain_id_distance_bucket}");
/// <summary>Creates a <see cref="DistanceViewName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="DistanceViewName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static DistanceViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new DistanceViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="DistanceViewName"/> with the pattern
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="placeholderChainId">The <c>PlaceholderChain</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="distanceBucketId">The <c>DistanceBucket</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="DistanceViewName"/> constructed from the provided ids.</returns>
public static DistanceViewName FromCustomerPlaceholderChainDistanceBucket(string customerId, string placeholderChainId, string distanceBucketId) =>
new DistanceViewName(ResourceNameType.CustomerPlaceholderChainDistanceBucket, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), placeholderChainId: gax::GaxPreconditions.CheckNotNullOrEmpty(placeholderChainId, nameof(placeholderChainId)), distanceBucketId: gax::GaxPreconditions.CheckNotNullOrEmpty(distanceBucketId, nameof(distanceBucketId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DistanceViewName"/> with pattern
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="placeholderChainId">The <c>PlaceholderChain</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="distanceBucketId">The <c>DistanceBucket</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="DistanceViewName"/> with pattern
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>.
/// </returns>
public static string Format(string customerId, string placeholderChainId, string distanceBucketId) =>
FormatCustomerPlaceholderChainDistanceBucket(customerId, placeholderChainId, distanceBucketId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DistanceViewName"/> with pattern
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="placeholderChainId">The <c>PlaceholderChain</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="distanceBucketId">The <c>DistanceBucket</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="DistanceViewName"/> with pattern
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>.
/// </returns>
public static string FormatCustomerPlaceholderChainDistanceBucket(string customerId, string placeholderChainId, string distanceBucketId) =>
s_customerPlaceholderChainDistanceBucket.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(placeholderChainId, nameof(placeholderChainId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(distanceBucketId, nameof(distanceBucketId)))}");
/// <summary>Parses the given resource name string into a new <see cref="DistanceViewName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="distanceViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="DistanceViewName"/> if successful.</returns>
public static DistanceViewName Parse(string distanceViewName) => Parse(distanceViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="DistanceViewName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="distanceViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="DistanceViewName"/> if successful.</returns>
public static DistanceViewName Parse(string distanceViewName, bool allowUnparsed) =>
TryParse(distanceViewName, allowUnparsed, out DistanceViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DistanceViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="distanceViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DistanceViewName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string distanceViewName, out DistanceViewName result) =>
TryParse(distanceViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DistanceViewName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="distanceViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DistanceViewName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string distanceViewName, bool allowUnparsed, out DistanceViewName result)
{
gax::GaxPreconditions.CheckNotNull(distanceViewName, nameof(distanceViewName));
gax::TemplatedResourceName resourceName;
if (s_customerPlaceholderChainDistanceBucket.TryParseName(distanceViewName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerPlaceholderChainDistanceBucket(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(distanceViewName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private DistanceViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string distanceBucketId = null, string placeholderChainId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
DistanceBucketId = distanceBucketId;
PlaceholderChainId = placeholderChainId;
}
/// <summary>
/// Constructs a new instance of a <see cref="DistanceViewName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="placeholderChainId">The <c>PlaceholderChain</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="distanceBucketId">The <c>DistanceBucket</c> ID. Must not be <c>null</c> or empty.</param>
public DistanceViewName(string customerId, string placeholderChainId, string distanceBucketId) : this(ResourceNameType.CustomerPlaceholderChainDistanceBucket, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), placeholderChainId: gax::GaxPreconditions.CheckNotNullOrEmpty(placeholderChainId, nameof(placeholderChainId)), distanceBucketId: gax::GaxPreconditions.CheckNotNullOrEmpty(distanceBucketId, nameof(distanceBucketId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>DistanceBucket</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string DistanceBucketId { get; }
/// <summary>
/// The <c>PlaceholderChain</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string PlaceholderChainId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerPlaceholderChainDistanceBucket: return s_customerPlaceholderChainDistanceBucket.Expand(CustomerId, $"{PlaceholderChainId}~{DistanceBucketId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as DistanceViewName);
/// <inheritdoc/>
public bool Equals(DistanceViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(DistanceViewName a, DistanceViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(DistanceViewName a, DistanceViewName b) => !(a == b);
}
public partial class DistanceView
{
/// <summary>
/// <see cref="DistanceViewName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal DistanceViewName ResourceNameAsDistanceViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : DistanceViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using ServiceStack.Text;
using ServiceStack.Text.Common;
namespace ServiceStack.Common.Tests.Perf
{
[Ignore("Bencharks for serializing basic .NET types")]
[TestFixture]
public class ToStringPerf
: PerfTestBase
{
public ToStringPerf()
{
this.MultipleIterations = new List<int> { 10000 };
}
[Test]
public void Compare_string()
{
CompareMultipleRuns(
"'test'.ToCsvField()", () => "test".ToCsvField(),
"SCU.ToString('test')", () => TypeSerializer.SerializeToString("test")
);
}
[Test]
public void Compare_escaped_string()
{
CompareMultipleRuns(
"'t,e:st'.ToCsvField()", () => "t,e:st".ToCsvField(),
"SCU.ToString('t,e:st')", () => TypeSerializer.SerializeToString("t,e:st")
);
}
[Test]
public void Compare_ints()
{
CompareMultipleRuns(
"1.ToString()", () => 1.ToString(),
"SCU.ToString(1)", () => TypeSerializer.SerializeToString(1)
);
}
[Test]
public void Compare_longs()
{
CompareMultipleRuns(
"1L.ToString()", () => 1L.ToString(),
"SCU.ToString(1L)", () => TypeSerializer.SerializeToString(1L)
);
}
[Test]
public void Compare_Guids()
{
var guid = new Guid("AC800C9C-B8BE-4829-868A-B43CFF7B2AFD");
CompareMultipleRuns(
"guid.ToString()", () => guid.ToString(),
"SCU.ToString(guid)", () => TypeSerializer.SerializeToString(guid)
);
}
[Test]
public void Compare_DateTime()
{
var now = DateTime.Now;
CompareMultipleRuns(
"now.ToString()", () => now.ToString(),
"SCU.ToString(now)", () => TypeSerializer.SerializeToString(now)
);
}
[Test]
public void Compare_IntList()
{
var intList = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
CompareMultipleRuns(
"intList.ForEach(x => sb.Append(x.ToString()))", () => {
var sb = new StringBuilder();
intList.ForEach(x => { if (sb.Length > 0) sb.Append(","); sb.Append(x.ToString()); });
sb.ToString();
},
"SCU.ToString(intList)", () => TypeSerializer.SerializeToString(intList)
);
}
[Test]
public void Compare_LongList()
{
var longList = new List<long> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
CompareMultipleRuns(
"longList.ForEach(x => sb.Append(x.ToString()))", () => {
var sb = new StringBuilder();
longList.ForEach(x => { if (sb.Length > 0) sb.Append(","); sb.Append(x.ToString()); });
sb.ToString();
},
"SCU.ToString(longList)", () => TypeSerializer.SerializeToString(longList)
);
}
[Test]
public void Compare_StringArray()
{
var stringArray = new[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
CompareMultipleRuns(
"sb.Append(s.ToCsvField());", () => {
var sb = new StringBuilder();
foreach (var s in stringArray)
{
if (sb.Length > 0) sb.Append(",");
sb.Append(s.ToCsvField());
}
sb.ToString();
},
"SCU.ToString(stringArray)", () => TypeSerializer.SerializeToString(stringArray)
);
}
[Test]
public void Compare_StringList()
{
var stringList = new List<string> { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
CompareMultipleRuns(
"sb.Append(s.ToCsvField());", () => {
var sb = new StringBuilder();
stringList.ForEach(x => { if (sb.Length > 0) sb.Append(","); sb.Append(x.ToString()); });
sb.ToString();
},
"SCU.ToString(stringList)", () => TypeSerializer.SerializeToString(stringList)
);
}
[Test]
public void Compare_DoubleList()
{
var doubleList = new List<double> { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 0.1 };
CompareMultipleRuns(
"doubleList.ForEach(x => sb.Append(x.ToString()))", () => {
var sb = new StringBuilder();
doubleList.ForEach(x => { if (sb.Length > 0) sb.Append(","); sb.Append(x.ToString()); });
sb.ToString();
},
"SCU.ToString(doubleList)", () => TypeSerializer.SerializeToString(doubleList)
);
}
[Test]
public void Compare_GuidList()
{
var guidList = new List<Guid>
{
new Guid("8F403A5E-CDFC-4C6F-B0EB-C055C1C8BA60"),
new Guid("5673BAC7-BAC5-4B3F-9B69-4180E6227508"),
new Guid("B0CA730F-14C9-4D00-AC7F-07E7DE8D566E"),
new Guid("4E26AF94-6B13-4F89-B192-36C6ABE73DAE"),
new Guid("08491B16-2270-4DF9-8AEE-A8861A791C50"),
};
CompareMultipleRuns(
"guidList.ForEach(x => sb.Append(x.ToString()))", () => {
var sb = new StringBuilder();
guidList.ForEach(x => { if (sb.Length > 0) sb.Append(","); sb.Append(x.ToString()); });
sb.ToString();
},
"SCU.ToString(guidList)", () => TypeSerializer.SerializeToString(guidList)
);
}
[Test]
public void Compare_StringHashSet()
{
var stringHashSet = new HashSet<string> { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
CompareMultipleRuns(
"sb.Append(s.ToCsvField());", () => {
var sb = new StringBuilder();
foreach (var s in stringHashSet)
{
if (sb.Length > 0) sb.Append(",");
sb.Append(s.ToCsvField());
}
sb.ToString();
},
"SCU.ToString(stringHashSet)", () => TypeSerializer.SerializeToString(stringHashSet)
);
}
[Test]
public void Compare_IntHashSet()
{
var intHashSet = new HashSet<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
CompareMultipleRuns(
"intList.ForEach(x => sb.Append(x.ToString()))", () => {
var sb = new StringBuilder();
foreach (var s in intHashSet)
{
if (sb.Length > 0) sb.Append(",");
sb.Append(s.ToString());
}
sb.ToString();
},
"SCU.ToString(intHashSet)", () => TypeSerializer.SerializeToString(intHashSet)
);
}
[Test]
public void Compare_DoubleHashSet()
{
var doubleHashSet = new HashSet<double> { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 0.1 };
CompareMultipleRuns(
"doubleList.ForEach(x => sb.Append(x.ToString()))", () => {
var sb = new StringBuilder();
foreach (var s in doubleHashSet)
{
if (sb.Length > 0) sb.Append(",");
sb.Append(s.ToString());
}
sb.ToString();
},
"SCU.ToString(doubleHashSet)", () => TypeSerializer.SerializeToString(doubleHashSet)
);
}
[Test]
public void Compare_StringStringMap()
{
var map = new Dictionary<string, string> {
{"A", "1"},{"B", "2"},{"C", "3"},{"D", "4"},{"E", "5"},
{"F", "6"},{"G", "7"},{"H", "8"},{"I", "9"},{"j", "10"},
};
CompareMultipleRuns(
"sb.Append(kv.Key.ToCsvField()).Append(ParseStringMethods.KeyValueSeperator).", () => {
var sb = new StringBuilder();
foreach (var kv in map)
{
if (sb.Length > 0) sb.Append(",");
sb.Append(kv.Key.ToCsvField())
.Append(JsWriter.MapKeySeperator)
.Append(kv.Value.ToCsvField());
}
sb.ToString();
},
"SCU.ToString(map)", () => TypeSerializer.SerializeToString(map)
);
}
[Test]
public void Compare_StringIntMap()
{
var map = new Dictionary<string, int> {
{"A", 1},{"B", 2},{"C", 3},{"D", 4},{"E", 5},
{"F", 6},{"G", 7},{"H", 8},{"I", 9},{"j", 10},
};
CompareMultipleRuns(
".Append(ParseStringMethods.KeyValueSeperator).Append(kv.Value.ToString())", () => {
var sb = new StringBuilder();
foreach (var kv in map)
{
if (sb.Length > 0) sb.Append(",");
sb.Append(kv.Key.ToCsvField())
.Append(JsWriter.MapKeySeperator)
.Append(kv.Value.ToString());
}
sb.ToString();
},
"SCU.ToString(map)", () => TypeSerializer.SerializeToString(map)
);
}
[Test]
public void Compare_StringInt_SortedDictionary()
{
var map = new SortedDictionary<string, int>{
{"A", 1},{"B", 2},{"C", 3},{"D", 4},{"E", 5},
{"F", 6},{"G", 7},{"H", 8},{"I", 9},{"j", 10},
};
CompareMultipleRuns(
".Append(ParseStringMethods.KeyValueSeperator).Append(kv.Value.ToString())", () => {
var sb = new StringBuilder();
foreach (var kv in map)
{
if (sb.Length > 0) sb.Append(",");
sb.Append(kv.Key.ToCsvField())
.Append(JsWriter.MapKeySeperator)
.Append(kv.Value.ToString());
}
sb.ToString();
},
"SCU.ToString(map)", () => TypeSerializer.SerializeToString(map)
);
}
[Test]
public void Compare_ByteArray()
{
var byteArrayValue = new byte[] { 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, 0, 65, 97, 255, };
CompareMultipleRuns(
"Encoding.Default.GetString(byteArrayValue)", () => Encoding.Default.GetString(byteArrayValue),
"SCU.ToString(byteArrayValue)", () => TypeSerializer.SerializeToString(byteArrayValue)
);
}
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Testing.TimeZones;
using NodaTime.Text;
using NodaTime.TimeZones;
using NUnit.Framework;
namespace NodaTime.Test
{
/// <summary>
/// Tests for aspects of DateTimeZone to do with converting from LocalDateTime and
/// LocalDate to ZonedDateTime.
/// </summary>
// TODO: Fix all tests to use SingleTransitionZone.
public partial class DateTimeZoneTest
{
// Sample time zones for DateTimeZone.AtStartOfDay etc. I didn't want to only test midnight transitions.
private static readonly DateTimeZone LosAngeles = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
private static readonly DateTimeZone NewZealand = DateTimeZoneProviders.Tzdb["Pacific/Auckland"];
private static readonly DateTimeZone Paris = DateTimeZoneProviders.Tzdb["Europe/Paris"];
private static readonly DateTimeZone NewYork = DateTimeZoneProviders.Tzdb["America/New_York"];
private static readonly DateTimeZone Pacific = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
/// <summary>
/// Local midnight at the start of the transition (June 1st) becomes 1am.
/// </summary>
private static readonly DateTimeZone TransitionForwardAtMidnightZone =
new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 6, 1, 2, 0), Offset.FromHours(-2), Offset.FromHours(-1));
/// <summary>
/// Local 1am at the start of the transition (June 1st) becomes midnight.
/// </summary>
private static readonly DateTimeZone TransitionBackwardToMidnightZone =
new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 6, 1, 3, 0), Offset.FromHours(-2), Offset.FromHours(-3));
/// <summary>
/// Local 11.20pm at the start of the transition (May 30th) becomes 12.20am of June 1st.
/// </summary>
private static readonly DateTimeZone TransitionForwardBeforeMidnightZone =
new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 6, 1, 1, 20), Offset.FromHours(-2), Offset.FromHours(-1));
/// <summary>
/// Local 12.20am at the start of the transition (June 1st) becomes 11.20pm of the previous day.
/// </summary>
private static readonly DateTimeZone TransitionBackwardAfterMidnightZone =
new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 6, 1, 2, 20), Offset.FromHours(-2), Offset.FromHours(-3));
private static readonly LocalDate TransitionDate = new LocalDate(2000, 6, 1);
[Test]
public void AmbiguousStartOfDay_TransitionAtMidnight()
{
// Occurrence before transition
var expected = new ZonedDateTime(new LocalDateTime(2000, 6, 1, 0, 0).WithOffset(Offset.FromHours(-2)),
TransitionBackwardToMidnightZone);
var actual = TransitionBackwardToMidnightZone.AtStartOfDay(TransitionDate);
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, TransitionDate.AtStartOfDayInZone(TransitionBackwardToMidnightZone));
}
[Test]
public void AmbiguousStartOfDay_TransitionAfterMidnight()
{
// Occurrence before transition
var expected = new ZonedDateTime(new LocalDateTime(2000, 6, 1, 0, 0).WithOffset(Offset.FromHours(-2)),
TransitionBackwardAfterMidnightZone);
var actual = TransitionBackwardAfterMidnightZone.AtStartOfDay(TransitionDate);
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, TransitionDate.AtStartOfDayInZone(TransitionBackwardAfterMidnightZone));
}
[Test]
public void SkippedStartOfDay_TransitionAtMidnight()
{
// 1am because of the skip
var expected = new ZonedDateTime(new LocalDateTime(2000, 6, 1, 1, 0).WithOffset(Offset.FromHours(-1)),
TransitionForwardAtMidnightZone);
var actual = TransitionForwardAtMidnightZone.AtStartOfDay(TransitionDate);
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, TransitionDate.AtStartOfDayInZone(TransitionForwardAtMidnightZone));
}
[Test]
public void SkippedStartOfDay_TransitionBeforeMidnight()
{
// 12.20am because of the skip
var expected = new ZonedDateTime(new LocalDateTime(2000, 6, 1, 0, 20).WithOffset(Offset.FromHours(-1)),
TransitionForwardBeforeMidnightZone);
var actual = TransitionForwardBeforeMidnightZone.AtStartOfDay(TransitionDate);
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, TransitionDate.AtStartOfDayInZone(TransitionForwardBeforeMidnightZone));
}
[Test]
public void UnambiguousStartOfDay()
{
// Just a simple midnight in March.
var expected = new ZonedDateTime(new LocalDateTime(2000, 3, 1, 0, 0).WithOffset(Offset.FromHours(-2)),
TransitionForwardAtMidnightZone);
var actual = TransitionForwardAtMidnightZone.AtStartOfDay(new LocalDate(2000, 3, 1));
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, new LocalDate(2000, 3, 1).AtStartOfDayInZone(TransitionForwardAtMidnightZone));
}
private static void AssertImpossible(LocalDateTime localTime, DateTimeZone zone)
{
try
{
zone.MapLocal(localTime).Single();
Assert.Fail("Expected exception");
}
catch (SkippedTimeException e)
{
Assert.AreEqual(localTime, e.LocalDateTime);
Assert.AreEqual(zone, e.Zone);
}
}
private static void AssertAmbiguous(LocalDateTime localTime, DateTimeZone zone)
{
ZonedDateTime earlier = zone.MapLocal(localTime).First();
ZonedDateTime later = zone.MapLocal(localTime).Last();
Assert.AreEqual(localTime, earlier.LocalDateTime);
Assert.AreEqual(localTime, later.LocalDateTime);
Assert.That(earlier.ToInstant(), Is.LessThan(later.ToInstant()));
try
{
zone.MapLocal(localTime).Single();
Assert.Fail("Expected exception");
}
catch (AmbiguousTimeException e)
{
Assert.AreEqual(localTime, e.LocalDateTime);
Assert.AreEqual(zone, e.Zone);
Assert.AreEqual(earlier, e.EarlierMapping);
Assert.AreEqual(later, e.LaterMapping);
}
}
private static void AssertOffset(int expectedHours, LocalDateTime localTime, DateTimeZone zone)
{
var zoned = zone.MapLocal(localTime).Single();
int actualHours = zoned.Offset.Milliseconds / NodaConstants.MillisecondsPerHour;
Assert.AreEqual(expectedHours, actualHours);
}
// Los Angeles goes from -7 to -8 on November 7th 2010 at 2am wall time
[Test]
public void GetOffsetFromLocal_LosAngelesFallTransition()
{
var before = new LocalDateTime(2010, 11, 7, 0, 30);
var atTransition = new LocalDateTime(2010, 11, 7, 1, 0);
var ambiguous = new LocalDateTime(2010, 11, 7, 1, 30);
var after = new LocalDateTime(2010, 11, 7, 2, 30);
AssertOffset(-7, before, LosAngeles);
AssertAmbiguous(atTransition, LosAngeles);
AssertAmbiguous(ambiguous, LosAngeles);
AssertOffset(-8, after, LosAngeles);
}
[Test]
public void GetOffsetFromLocal_LosAngelesSpringTransition()
{
var before = new LocalDateTime(2010, 3, 14, 1, 30);
var impossible = new LocalDateTime(2010, 3, 14, 2, 30);
var atTransition = new LocalDateTime(2010, 3, 14, 3, 0);
var after = new LocalDateTime(2010, 3, 14, 3, 30);
AssertOffset(-8, before, LosAngeles);
AssertImpossible(impossible, LosAngeles);
AssertOffset(-7, atTransition, LosAngeles);
AssertOffset(-7, after, LosAngeles);
}
// New Zealand goes from +13 to +12 on April 4th 2010 at 3am wall time
[Test]
public void GetOffsetFromLocal_NewZealandFallTransition()
{
var before = new LocalDateTime(2010, 4, 4, 1, 30);
var atTransition = new LocalDateTime(2010, 4, 4, 2, 0);
var ambiguous = new LocalDateTime(2010, 4, 4, 2, 30);
var after = new LocalDateTime(2010, 4, 4, 3, 30);
AssertOffset(+13, before, NewZealand);
AssertAmbiguous(atTransition, NewZealand);
AssertAmbiguous(ambiguous, NewZealand);
AssertOffset(+12, after, NewZealand);
}
// New Zealand goes from +12 to +13 on September 26th 2010 at 2am wall time
[Test]
public void GetOffsetFromLocal_NewZealandSpringTransition()
{
var before = new LocalDateTime(2010, 9, 26, 1, 30);
var impossible = new LocalDateTime(2010, 9, 26, 2, 30);
var atTransition = new LocalDateTime(2010, 9, 26, 3, 0);
var after = new LocalDateTime(2010, 9, 26, 3, 30);
AssertOffset(+12, before, NewZealand);
AssertImpossible(impossible, NewZealand);
AssertOffset(+13, atTransition, NewZealand);
AssertOffset(+13, after, NewZealand);
}
// Paris goes from +1 to +2 on March 28th 2010 at 2am wall time
[Test]
public void GetOffsetFromLocal_ParisFallTransition()
{
var before = new LocalDateTime(2010, 10, 31, 1, 30);
var atTransition = new LocalDateTime(2010, 10, 31, 2, 0);
var ambiguous = new LocalDateTime(2010, 10, 31, 2, 30);
var after = new LocalDateTime(2010, 10, 31, 3, 30);
AssertOffset(2, before, Paris);
AssertAmbiguous(ambiguous, Paris);
AssertAmbiguous(atTransition, Paris);
AssertOffset(1, after, Paris);
}
[Test]
public void GetOffsetFromLocal_ParisSpringTransition()
{
var before = new LocalDateTime(2010, 3, 28, 1, 30);
var impossible = new LocalDateTime(2010, 3, 28, 2, 30);
var atTransition = new LocalDateTime(2010, 3, 28, 3, 0);
var after = new LocalDateTime(2010, 3, 28, 3, 30);
AssertOffset(1, before, Paris);
AssertImpossible(impossible, Paris);
AssertOffset(2, atTransition, Paris);
AssertOffset(2, after, Paris);
}
[Test]
public void MapLocalDateTime_UnambiguousDateReturnsUnambiguousMapping()
{
//2011-11-09 01:30:00 - not ambiguous in America/New York timezone
var unambigiousTime = new LocalDateTime(2011, 11, 9, 1, 30);
var mapping = NewYork.MapLocal(unambigiousTime);
Assert.AreEqual(1, mapping.Count);
}
[Test]
public void MapLocalDateTime_AmbiguousDateReturnsAmbigousMapping()
{
//2011-11-06 01:30:00 - falls during DST - EST conversion in America/New York timezone
var ambiguousTime = new LocalDateTime(2011, 11, 6, 1, 30);
var mapping = NewYork.MapLocal(ambiguousTime);
Assert.AreEqual(2, mapping.Count);
}
[Test]
public void MapLocalDateTime_SkippedDateReturnsSkippedMapping()
{
//2011-03-13 02:30:00 - falls during EST - DST conversion in America/New York timezone
var skippedTime = new LocalDateTime(2011, 3, 13, 2, 30);
var mapping = NewYork.MapLocal(skippedTime);
Assert.AreEqual(0, mapping.Count);
}
// Some zones skipped dates by changing from UTC-lots to UTC+lots. For example, Samoa (Pacific/Apia)
// skipped December 30th 2011, going from 23:59:59 December 29th local time UTC-10
// to 00:00:00 December 31st local time UTC+14
[Test]
[TestCase("Pacific/Apia", "2011-12-30")]
[TestCase("Pacific/Enderbury", "1995-01-01")]
[TestCase("Pacific/Kiritimati", "1995-01-01")]
[TestCase("Pacific/Kwajalein", "1993-08-20")]
public void AtStartOfDay_DayDoesntExist(string zoneId, string localDate)
{
LocalDate badDate = LocalDatePattern.IsoPattern.Parse(localDate).Value;
DateTimeZone zone = DateTimeZoneProviders.Tzdb[zoneId];
var exception = Assert.Throws<SkippedTimeException>(() => zone.AtStartOfDay(badDate));
Assert.AreEqual(badDate + LocalTime.Midnight, exception.LocalDateTime);
}
[Test]
public void AtStrictly_InWinter()
{
var when = Pacific.AtStrictly(new LocalDateTime(2009, 12, 22, 21, 39, 30));
Assert.AreEqual(2009, when.Year);
Assert.AreEqual(12, when.Month);
Assert.AreEqual(22, when.Day);
Assert.AreEqual(2, when.DayOfWeek);
Assert.AreEqual(21, when.Hour);
Assert.AreEqual(39, when.Minute);
Assert.AreEqual(30, when.Second);
Assert.AreEqual(Offset.FromHours(-8), when.Offset);
}
[Test]
public void AtStrictly_InSummer()
{
var when = Pacific.AtStrictly(new LocalDateTime(2009, 6, 22, 21, 39, 30));
Assert.AreEqual(2009, when.Year);
Assert.AreEqual(6, when.Month);
Assert.AreEqual(22, when.Day);
Assert.AreEqual(21, when.Hour);
Assert.AreEqual(39, when.Minute);
Assert.AreEqual(30, when.Second);
Assert.AreEqual(Offset.FromHours(-7), when.Offset);
}
/// <summary>
/// Pacific time changed from -7 to -8 at 2am wall time on November 2nd 2009,
/// so 2am became 1am.
/// </summary>
[Test]
public void AtStrictly_ThrowsWhenAmbiguous()
{
Assert.Throws<AmbiguousTimeException>(() => Pacific.AtStrictly(new LocalDateTime(2009, 11, 1, 1, 30, 0)));
}
/// <summary>
/// Pacific time changed from -8 to -7 at 2am wall time on March 8th 2009,
/// so 2am became 3am. This means that 2.30am doesn't exist on that day.
/// </summary>
[Test]
public void AtStrictly_ThrowsWhenSkipped()
{
Assert.Throws<SkippedTimeException>(() => Pacific.AtStrictly(new LocalDateTime(2009, 3, 8, 2, 30, 0)));
}
/// <summary>
/// Pacific time changed from -7 to -8 at 2am wall time on November 2nd 2009,
/// so 2am became 1am. We'll return the earlier result, i.e. with the offset of -7
/// </summary>
[Test]
public void AtLeniently_AmbiguousTime_ReturnsEarlierMapping()
{
var local = new LocalDateTime(2009, 11, 1, 1, 30, 0);
var zoned = Pacific.AtLeniently(local);
Assert.AreEqual(local, zoned.LocalDateTime);
Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
}
/// <summary>
/// Pacific time changed from -8 to -7 at 2am wall time on March 8th 2009,
/// so 2am became 3am. This means that 2:30am doesn't exist on that day.
/// We'll return 3:30am, the forward-shifted value.
/// </summary>
[Test]
public void AtLeniently_ReturnsForwardShiftedValue()
{
var local = new LocalDateTime(2009, 3, 8, 2, 30, 0);
var zoned = Pacific.AtLeniently(local);
Assert.AreEqual(new LocalDateTime(2009, 3, 8, 3, 30, 0), zoned.LocalDateTime);
Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
}
[Test]
public void ResolveLocal()
{
// Don't need much for this - it only delegates.
var ambiguous = new LocalDateTime(2009, 11, 1, 1, 30, 0);
var skipped = new LocalDateTime(2009, 3, 8, 2, 30, 0);
Assert.AreEqual(Pacific.AtLeniently(ambiguous), Pacific.ResolveLocal(ambiguous, Resolvers.LenientResolver));
Assert.AreEqual(Pacific.AtLeniently(skipped), Pacific.ResolveLocal(skipped, Resolvers.LenientResolver));
}
}
}
| |
using System;
using System.Data;
using System.Diagnostics;
using System.Xml;
namespace FileHelpers.Dynamic
{
/// <summary>Used to create classes that maps to Delimited records.</summary>
public class DelimitedClassBuilder : ClassBuilder
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string mDelimiter = string.Empty;
/// <summary>The Delimiter that marks the end of each field.</summary>
public string Delimiter
{
get { return mDelimiter; }
set { mDelimiter = value; }
}
/// <summary>Return the field at the specified index.</summary>
/// <param name="index">The index of the field.</param>
/// <returns>The field at the specified index.</returns>
public new DelimitedFieldBuilder FieldByIndex(int index)
{
return (DelimitedFieldBuilder) base.FieldByIndex(index);
}
/// <summary>Returns the current fields of the class.</summary>
public new DelimitedFieldBuilder[] Fields
{
get { return (DelimitedFieldBuilder[]) mFields.ToArray(typeof (DelimitedFieldBuilder)); }
}
/// <summary>Creates a new DelimitedClassBuilder.</summary>
/// <param name="className">The valid class name.</param>
/// <param name="delimiter">The delimiter for that class.</param>
public DelimitedClassBuilder(string className, string delimiter)
: base(className)
{
mDelimiter = delimiter;
}
/// <summary>Creates a new DelimitedClassBuilder.</summary>
/// <param name="className">The valid class name.</param>
public DelimitedClassBuilder(string className)
: this(className, string.Empty) {}
/// <summary>Creates a new DelimitedClassBuilder with the same structure than a DataTable.</summary>
/// <param name="className">The valid class name.</param>
/// <param name="delimiter">The delimiter for that class.</param>
/// <param name="dt">The DataTable from where to get the field names and types</param>
public DelimitedClassBuilder(string className, string delimiter, DataTable dt)
: this(className, delimiter)
{
foreach (DataColumn dc in dt.Columns)
AddField(StringHelper.ToValidIdentifier(dc.ColumnName), dc.DataType);
}
/// <summary>Add a new Delimited field to the current class.</summary>
/// <param name="fieldName">The Name of the field.</param>
/// <param name="fieldType">The Type of the field.</param>
/// <returns>The just created field.</returns>
public virtual DelimitedFieldBuilder AddField(string fieldName, string fieldType)
{
var fb = new DelimitedFieldBuilder(fieldName, fieldType);
AddFieldInternal(fb);
return fb;
}
/// <summary>Add a new Delimited field to the current class.</summary>
/// <param name="fieldName">The Name of the field.</param>
/// <param name="fieldType">The Type of the field. (For generic of nullable types use the string overload, like "int?")</param>
/// <returns>The just created field.</returns>
public DelimitedFieldBuilder AddField(string fieldName, Type fieldType)
{
return AddField(fieldName, TypeToString(fieldType));
}
/// <summary>Add a new Delimited string field to the current class.</summary>
/// <param name="fieldName">The Name of the string field.</param>
/// <returns>The just created field.</returns>
public virtual DelimitedFieldBuilder AddField(string fieldName)
{
return AddField(fieldName, "System.String");
}
/// <summary>Add a new Delimited field to the current class.</summary>
/// <param name="field">The field definition.</param>
/// <returns>The just added field.</returns>
public DelimitedFieldBuilder AddField(DelimitedFieldBuilder field)
{
AddFieldInternal(field);
return field;
}
/// <summary>Return the last added field. (use it reduce casts and code)</summary>
public DelimitedFieldBuilder LastField
{
get
{
if (mFields.Count == 0)
return null;
else
return (DelimitedFieldBuilder) mFields[mFields.Count - 1];
}
}
/// <summary>
/// Add any attributes to source (currently only the delimiter attribute)
/// </summary>
/// <param name="attbs">Attributes storage area to add to class</param>
/// <param name="lang"></param>
internal override void AddAttributesCode(AttributesBuilder attbs, NetLanguage lang)
{
if (mDelimiter == string.Empty)
throw new BadUsageException("The Delimiter of the DelimiterClassBuilder can't be null or empty.");
else
attbs.AddAttribute("DelimitedRecord(" + GetDelimiter(mDelimiter, lang) + ")");
}
private static string GetDelimiter(string delimiter, NetLanguage lang)
{
switch (lang) {
case NetLanguage.CSharp:
if (delimiter == "\t")
return "\"\\t\"";
else
return "\"" + delimiter + "\"";
case NetLanguage.VbNet:
if (delimiter == "\t")
return "VbTab";
else
return "\"" + delimiter + "\"";
default:
throw new ArgumentOutOfRangeException("lang");
}
}
/// <summary>
/// Serialise the XML header
/// </summary>
/// <param name="writer">Writer to serialise to</param>
internal override void WriteHeaderElement(XmlHelper writer)
{
writer.Writer.WriteStartElement("DelimitedClass");
writer.Writer.WriteStartAttribute("Delimiter", "");
writer.Writer.WriteString(this.Delimiter);
writer.Writer.WriteEndAttribute();
}
/// <summary>
/// Write any extra elements (not used)
/// </summary>
/// <param name="writer"></param>
internal override void WriteExtraElements(XmlHelper writer) {}
/// <summary>
/// extract delimited class details from xml
/// </summary>
/// <param name="document">XML document to check</param>
/// <returns>delimited class information</returns>
internal static DelimitedClassBuilder LoadXmlInternal(XmlDocument document)
{
DelimitedClassBuilder res;
string del = document.SelectNodes("/DelimitedClass")[0].Attributes["Delimiter"].Value;
string className = document.SelectNodes("/DelimitedClass/ClassName")[0].InnerText;
res = new DelimitedClassBuilder(className, del);
return res;
}
/// <summary>
/// Extract the class element from the XML document
/// </summary>
/// <param name="document">XML to extract extra info from</param>
internal override void ReadClassElements(XmlDocument document) {}
/// <summary>
/// Get the attributes off the XML element
/// </summary>
/// <param name="node">Node to read</param>
internal override void ReadField(XmlNode node)
{
AddField(node.Attributes.Item(0).InnerText, node.Attributes.Item(1).InnerText).ReadField(node);
}
/// <summary>
/// Adds n fields of type string, with the names "Field1", Field2", etc
/// </summary>
/// <param name="numberOfFields">The number of fields to add</param>
public virtual void AddFields(int numberOfFields)
{
for (int i = 0; i < numberOfFields; i++)
AddField("Field" + (i + 1).ToString().PadLeft(4, '0'));
}
}
}
| |
using System;
using System.Collections.Generic;
using Activation;
using Common;
using Fairweather.Service;
namespace DTA
{
public class General_Helper : Write_Able_Helper
{
public IEnumerable<string> Company_Strings {
get {
foreach (var company in Companies) {
string item = Get_Company_String(company);
yield return item;
}
}
}
public string
Get_Company_String(Company_Number company) {
var company_helper = new Company_Helper(ini, company);
var as_string = company.As_String;
var company_name = company_helper.Company_Name;
var item = "{0} - {1}".spf(as_string, company_name);
return item;
}
public General_Helper(Ini_File ini)
: base(ini) {
}
public bool IsRegistered {
get {
string key, pin;
bool has_key = ini.Try_Get_Data(DTA_Fields.ACTIVATION_KEY, out key);
bool has_pin = ini.Try_Get_Data(DTA_Fields.PIN, out pin);
if (key.IsNullOrEmpty())
return false;
if (pin.IsNullOrEmpty())
return false;
if (!Activation_Data.ValidateKey(key))
return false;
if (!Activation_Data.ValidatePIN(key, pin))
return false;
return true;
}
}
public string Activation_Key {
get {
return String(DTA_Fields.ACTIVATION_KEY);
}
}
public string PIN {
get {
return String(DTA_Fields.PIN);
}
}
public Ini_File Ini_File {
get { return ini; }
}
public List<Company_Number> Companies {
get {
int cnt = Number_Of_Companies;
var ret = new List<Company_Number>(cnt);
for (int ii = 1; ii <= cnt; ++ii) {
ret.Add(new Company_Number(ii));
}
return ret;
}
}
public Company_Number Default_Company {
get {
return new Company_Number(Int(DTA_Fields.DEFAULT_COMPANY));
}
set {
Set(DTA_Fields.DEFAULT_COMPANY, value.As_Number);
}
}
public Set<Sub_App> Licensed_Modules {
get {
var lst = new List<Sub_App>();
if (Data.Is_Entry_Screens) {
if (Module_Enabled(1)) {
lst.Add(Sub_App.Entry_Customers);
lst.Add(Sub_App.Entry_Suppliers);
}
if (Module_Enabled(2)) {
lst.Add(Sub_App.Products);
}
if (Module_Enabled(3)) {
lst.Add(Sub_App.Documents_Transfer);
lst.Add(Sub_App.Transactions_Entry);
}
}
if (Data.Is_Ses_Cfg) {
lst.Add(Sub_App.Ses_Cfg);
}
if (Data.Is_Interface_Tools) {
// not needed
throw new NotImplementedException();
}
var ret = new Set<Sub_App>(lst);
return ret;
}
}
public bool Module_Enabled(int module_number) {
(module_number <= 3 && module_number > 0).tiff();
var strings = new Dictionary<int, Ini_Field>
{
{1, DTA_Fields.MODULE_1},
{2, DTA_Fields.MODULE_2},
{3, DTA_Fields.MODULE_3},
};
return True(strings[module_number]);
}
public bool Allow_Other_Companies {
get {
return False(DTA_Fields.ONLY_DEFAULT_COMPANY);
}
set {
Set(DTA_Fields.ONLY_DEFAULT_COMPANY, !value);
}
}
public bool Allow_Reset_Of_Active_Users {
get {
return True(DTA_Fields.ALLOW_REMOVING_USERS);
}
set {
Set(DTA_Fields.ALLOW_REMOVING_USERS, value);
}
}
public bool InternalCredentials {
get {
return String(DTA_Fields.CREDENTIALS_SOURCE) == FROM_DTA;
}
set {
if (value)
Set(DTA_Fields.CREDENTIALS_SOURCE, FROM_DTA);
else
CommandLineCredentials = true;
}
}
public bool CommandLineCredentials {
get {
return String(DTA_Fields.CREDENTIALS_SOURCE) == PROMPT;
}
set {
if (value)
Set(DTA_Fields.CREDENTIALS_SOURCE, PROMPT);
else
InternalCredentials = true;
}
}
public bool Debug {
get {
return True(DTA_Fields.DEBUG);
}
set {
Set(DTA_Fields.DEBUG, value);
}
}
public int Max_Companies {
get {
return Safe_Int(DTA_Fields.MAX_COMPANIES);
}
}
public bool Any_Registered_Companies {
get {
var num = Number_Of_Companies;
(num >= 0).tiff();
bool ret = (num > 0);
return ret;
}
}
protected override int Safe_Int(Ini_Field field) {
string str;
if (!ini.Try_Get_Data(field, out str))
return 0;
return base.Safe_Int(field);
}
public int Number_Of_Companies {
get {
return Safe_Int(DTA_Fields.NUMBER_OF_COMPANIES);
}
set {
ini[DTA_Fields.NUMBER_OF_COMPANIES] = value.ToString();
}
}
public int Version {
get {
return Int(DTA_Fields.VERSION);
}
}
public Company_Helper Get_Company_Helper(Company_Number number) {
(Number_Of_Companies < number.As_Number).tift();
var ret = new Company_Helper(ini, number);
return ret;
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion LGPL License
#region Using Directives
using System;
using System.Collections;
using System.Diagnostics;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Collections;
using Axiom.Media;
using Axiom.Graphics;
using Axiom.SceneManagers.PagingLandscape;
using Axiom.SceneManagers.PagingLandscape.Tile;
using Axiom.SceneManagers.PagingLandscape.Page;
using Axiom.SceneManagers.PagingLandscape.Collections;
using Axiom.SceneManagers.PagingLandscape.Data2D;
using Axiom.SceneManagers.PagingLandscape.Renderable;
using Axiom.SceneManagers.PagingLandscape.Texture;
#endregion Using Directives
namespace Axiom.SceneManagers.PagingLandscape.Tile
{
/// <summary>
/// Summary description for Tile.
/// </summary>
public class Tile : MovableObject
{
#region Fields
protected static string type = "PagingLandscapeTile";
//movable object variables
protected AxisAlignedBox bounds;
protected AxisAlignedBox boundsExt;
// if the tile is initialized
protected bool init;
// if the renderable is loaded
protected bool loaded;
protected Renderable.Renderable renderable;
protected SceneNode tileSceneNode;
protected Tile[] neighbors;
protected TileInfo info;
#endregion Fields
#region Constructor
public Tile()
{
info = new TileInfo();
tileSceneNode = null;
renderable = null;
init = false;
loaded = false;
bounds = new AxisAlignedBox();
boundsExt = new AxisAlignedBox();
//worldBounds = new AxisAlignedBox();
neighbors = new Tile[4];
}
#endregion Constructor
#region IDisposable Members
public void Dispose()
{
}
#endregion
public TileInfo Info
{
get
{
return info;
}
}
/** Sets the appropriate neighbor for this TerrainRenderable. Neighbors are necessary
to know when to bridge between LODs.
*/
public void SetNeighbor( Neighbor n, Tile t )
{
neighbors[(int) n ] = t;
}
/** Returns the neighbor TerrainRenderable.
*/
public Tile GetNeighbor( Neighbor n )
{
return neighbors[ (int)n ];
}
/// <summary>
/// Intersects Mainly with Landscape
/// </summary>
/// <param name="start">begining of the segment</param>
/// <param name="dir">direction of the secment</param>
/// <param name="result">where the segment intersects with the terrain</param>
/// <returns></returns>
public bool IntersectSegment( Vector3 start, Vector3 dir, Vector3 result )
{
Vector3 ray = start;
Vector3[] corners = worldAABB.Corners;
// Addd the direction to the segment
ray += dir;
Data2D.Data2D data = Data2DManager.Instance.GetData2D(info.PageX, info.PageZ);
if (data == null)
{
// just go until next tile.
while ( ! ( ( ray.x < corners[ 0 ].x ) ||
( ray.x > corners[ 4 ].x ) ||
( ray.z < corners[ 0 ].z ) ||
( ray.z > corners[ 4 ].z ) ) )
{
ray += dir;
}
}
else
{
float pageMax = 0f;
if (renderable != null)
{
if (renderable.IsLoaded )
{
pageMax = renderable.MaxHeight ;
}
}
else
{
pageMax = data.MaxHeight;
}
while ( ! ( ( ray.x < corners[ 0 ].x ) ||
( ray.x > corners[ 4 ].x ) ||
( ray.z < corners[ 0 ].z ) ||
( ray.z > corners[ 4 ].z ) ) )
{
if ( ray.y <= pageMax && // until under the max possible for this page/tile
ray.y <= data.GetHeightAbsolute( ray.x, ray.z, info )// until under the max
)
{
// Found intersection range
// zone (ray - dir < intersection < ray.y + dir )
// now do a precise check using a normalised Direction
// vector. (that is < 0.1f)
// ray -= dir;
// Vector3 s = PagingLandScapeOptions::getSingleton().scale;
// Vector3 PrecisionDir (dir.x / s.x,
// dir.y / s.y,
// dir.z / s.z);
// while( ray.y >= pageMax &&
// ray.y >= tileMax)
// {
// ray += PrecisionDir;
// }
// // until under the interpolated upon current LOD max
// while( ray.y > PagingLandScapeData2DManager::getSingleton().getRealWorldHeight( ray.x, ray.z ))
// {
// ray += PrecisionDir;
// }
result = ray;
return true;
}
ray += dir;
}
}
if ( ray.x < corners[ 0 ].x && neighbors[ (int)Neighbor.West ] != null )
return neighbors[ (int)Neighbor.West ].IntersectSegment( ray, dir, result );
else if ( ray.z < corners[ 0 ].z && neighbors[ (int)Neighbor.North ] != null )
return neighbors[ (int)Neighbor.North ].IntersectSegment( ray, dir, result );
else if ( ray.x > corners[ 4 ].x && neighbors[ (int)Neighbor.East ] != null )
return neighbors[ (int)Neighbor.East ].IntersectSegment( ray, dir, result );
else if ( ray.z > corners[ 4 ].z && neighbors[ (int)Neighbor.South ] != null )
return neighbors[ (int)Neighbor.South ].IntersectSegment( ray, dir, result );
else
{
if ( result != Vector3.Zero )
result = new Vector3( -1, -1, -1 );
return false;
}
}
/// <summary>
/// Make the Tile reload its vertices and normals (upon a modification of the height data)
/// </summary>
public void UpdateTerrain ()
{
Debug.Assert (renderable != null);
renderable.NeedUpdate();
}
public Renderable.Renderable Renderable
{
get
{
return renderable;
}
}
public void LinkRenderableNeighbor()
{
// South
if (neighbors[(int)Neighbor.South] != null)
{
if (neighbors[(int)Neighbor.South].IsLoaded)
{
Renderable.Renderable n = neighbors[(int)Neighbor.South].Renderable;
Debug.Assert(n != null);
renderable.SetNeighbor (Neighbor.South, n);
n.SetNeighbor (Neighbor.North, renderable);
}
}
//North
if (neighbors[(int)Neighbor.North] != null)
{
if (neighbors[(int)Neighbor.North].IsLoaded)
{
Renderable.Renderable n = neighbors[(int)Neighbor.North].Renderable;
Debug.Assert(n != null);
renderable.SetNeighbor (Neighbor.North, n);
n.SetNeighbor (Neighbor.South, renderable);
}
}
//East
if (neighbors[(int)Neighbor.East] != null)
{
if (neighbors[(int)Neighbor.East].IsLoaded)
{
Renderable.Renderable n = neighbors[(int)Neighbor.East].Renderable;
Debug.Assert(n != null);
renderable.SetNeighbor (Neighbor.East, n);
n.SetNeighbor (Neighbor.West, renderable);
}
}
//West
if (neighbors[(int)Neighbor.West] != null)
{
if (neighbors[(int)Neighbor.West].IsLoaded)
{
Renderable.Renderable n = neighbors[(int)Neighbor.West].Renderable;
Debug.Assert(n != null);
renderable.SetNeighbor (Neighbor.West, n);
n.SetNeighbor (Neighbor.East, renderable);
}
}
}
public void Init( ref SceneNode ParentSceneNode, int tableX, int tableZ, int tileX, int tileZ )
{
init = true;
Vector3 ParentPos = ParentSceneNode.DerivedPosition;
info.PageX = tableX;
info.PageZ = tableZ;
info.TileX = tileX;
info.TileZ = tileZ;
// Calculate the offset from the parent for this tile
Vector3 scale = Options.Instance.Scale;
float endx = Options.Instance.TileSize * scale.x;
float endz = Options.Instance.TileSize * scale.z;
info.PosX = info.TileX * endx;
info.PosZ = info.TileZ * endz;
name = String.Format("tile[{0},{1}][{2},{3}]",info.PageX, info.PageZ, info.TileX, info.TileZ);
tileSceneNode = (SceneNode)ParentSceneNode.CreateChild( name );
// figure out scene node position within parent
tileSceneNode.Position = new Vector3( info.PosX, 0, info.PosZ );
tileSceneNode.AttachObject( this );
float MaxHeight = Data2DManager.Instance.GetMaxHeight(info.PageX, info.PageZ);
bounds.SetExtents( new Vector3(0,0,0) , new Vector3((float)( endx ), MaxHeight, (float)( endz )) );
//Change Zone of this page
boundsExt.SetExtents( new Vector3( - endx * 0.5f, - MaxHeight * 0.5f, - endz * 0.5f) , new Vector3(endx * 1.5f, MaxHeight * 1.5f , endz * 1.5f));
//Change Zone of this page
this.worldAABB.SetExtents( new Vector3(info.PosX + ParentPos.x ,0, info.PosZ + ParentPos.z), new Vector3((float)( info.PosX + ParentPos.x + endx), MaxHeight, (float)( info.PosZ + ParentPos.z + endz) ));
//this.worldBounds.SetExtents( new Vector3(info.PosX + ParentPos.x ,0, info.PosZ + ParentPos.z), new Vector3((float)( info.PosX + ParentPos.x + endx), MaxHeight, (float)( info.PosZ + ParentPos.z + endz) ));
for ( long i = 0; i < 4; i++ )
{
neighbors[ i ] = null;
}
//force update in scene node
//tileSceneNode.update( true, true );
tileSceneNode.NeedUpdate();
loaded = false;
}
public void Release()
{
if (init)
{
init = false;
if ( loaded && renderable != null )
{
renderable.Release();
renderable = null;
loaded = false;
}
if (neighbors[(int)Neighbor.North] != null)
neighbors[(int)Neighbor.North].SetNeighbor(Neighbor.South, null);
if (neighbors[(int)Neighbor.South] != null)
neighbors[(int)Neighbor.South].SetNeighbor(Neighbor.North, null);
if (neighbors[(int)Neighbor.East] != null)
neighbors[(int)Neighbor.East].SetNeighbor(Neighbor.West, null);
if (neighbors[(int)Neighbor.West] != null)
neighbors[(int)Neighbor.West].SetNeighbor(Neighbor.East, null);
for ( long i = 0; i < 4; i++ )
{
neighbors[ i ] = null;
}
if ( tileSceneNode != null )
{
//mTileNode->getParent()->removeChild( mTileNode->getName() );
//delete mTileNode;
//assert (mTileSceneNode->getParent());
// jsw - we need to call both of these to delete the scene node. The first
// one removes it from the SceneManager's list of all nodes, and the 2nd one
// removes it from the tree of scene nodes.
tileSceneNode.Creator.DestroySceneNode(tileSceneNode.Name);
tileSceneNode.Parent.RemoveChild( tileSceneNode );
tileSceneNode = null;
}
TileManager.Instance.FreeTile( this );
}
}
/** Returns the bounding box of this LandScapeRenderable
*/
public override AxisAlignedBox BoundingBox
{
get
{
return bounds;
}
}
/** Updates the level of detail to be used for rendering this PagingLandScapeRenderable based on the passed in Camera
*/
public override void NotifyCurrentCamera( Axiom.Core.Camera cam )
{
PagingLandscape.Camera plsmcam = (PagingLandscape.Camera) (cam);
this.isVisible = (init && loaded && plsmcam.GetVisibility(tileSceneNode.WorldAABB));
// this.isVisible = (init && loaded );
}
public virtual void NotifyAttached(Node parent)
{
this.parentNode = parent;
if ( parent != null )
{
tileSceneNode = (SceneNode)( parent.CreateChild( name ) );
//mTileNode.setPosition( (Real)mTableX , 0.0, (Real)mTableZ );
if ( renderable != null)
if (renderable.IsLoaded)
{
tileSceneNode.AttachObject( (MovableObject) renderable );
}
tileSceneNode.NeedUpdate();
}
}
public override void UpdateRenderQueue( RenderQueue queue ){/* not needed */}
/** Overridden from SceneObject */
public override float BoundingRadius { get { return 0F; /* not needed */ } }
public void GetWorldTransforms( Matrix4[] xform )
{
parentNode.GetWorldTransforms(xform);
}
public Quaternion WorldOrientation
{
get
{
return parentNode.DerivedOrientation;
}
}
public Vector3 WorldPosition
{
get
{
return parentNode.DerivedPosition;
}
}
public void Notify( Vector3 pos, PagingLandscape.Camera Cam)
{
if ((( pos - tileSceneNode.DerivedPosition).LengthSquared <=
Options.Instance.Renderable_Factor))
{
if ( loaded == false
//&& Cam.getVisibility (mBoundsExt))
// && Cam.GetVisibility (tileSceneNode.WorldAABB ))
&& Cam.GetVisibility (this.worldAABB ))
{
// Request a renderable
renderable = RenderableManager.Instance.GetRenderable();
if ( renderable != null )
{
//TODO: We may remove the PosX and PosZ since it is not necessary
renderable.Init( info );
// Set the material
renderable.Material = Texture.TextureManager.Instance.GetMaterial( info.PageX, info.PageZ ) ;
if ( tileSceneNode != null)
{
tileSceneNode.Clear();
}
//Queue it for loading
RenderableManager.Instance.QueueRenderableLoading( renderable, this );
loaded = true;
PageManager.Instance.GetPage(info.PageX,info.PageZ).LinkTileNeighbors();
}
}
}
else
{
if ( renderable != null )
{
loaded = false;
if ( tileSceneNode != null && renderable.IsLoaded )
{
tileSceneNode.DetachObject( renderable );
}
renderable.Release();
renderable = null;
}
}
}
/// Gets all the patches within an AABB in world coordinates as GeometryData structs
public virtual void GetRenderOpsInBox( AxisAlignedBox box, ArrayList opList)
{
if ( MathUtil.Intersects(box, bounds ) != Intersection.None )
{
RenderOperation rend = new RenderOperation();
renderable.GetRenderOperation( rend );
opList.Add( rend );
}
}
public SceneNode TileNode
{
get
{
return tileSceneNode;
}
}
public bool IsLoaded
{
get
{
return loaded;
}
}
}
}
| |
// 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.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.X509Certificates.Asn1;
using System.Text;
namespace Internal.Cryptography.Pal
{
internal enum GeneralNameType
{
OtherName = 0,
Rfc822Name = 1,
// RFC 822: Standard for the format of ARPA Internet Text Messages.
// That means "email", and an RFC 822 Name: "Email address"
Email = Rfc822Name,
DnsName = 2,
X400Address = 3,
DirectoryName = 4,
EdiPartyName = 5,
UniformResourceIdentifier = 6,
IPAddress = 7,
RegisteredId = 8,
}
internal struct CertificateData
{
internal struct AlgorithmIdentifier
{
public AlgorithmIdentifier(AlgorithmIdentifierAsn algorithmIdentifier)
{
AlgorithmId = algorithmIdentifier.Algorithm.Value;
Parameters = algorithmIdentifier.Parameters?.ToArray() ?? Array.Empty<byte>();
}
internal string AlgorithmId;
internal byte[] Parameters;
}
private CertificateAsn certificate;
internal byte[] RawData;
internal byte[] SubjectPublicKeyInfo;
internal X500DistinguishedName Issuer;
internal X500DistinguishedName Subject;
internal List<X509Extension> Extensions;
internal int Version => certificate.TbsCertificate.Version;
internal byte[] SerialNumber => certificate.TbsCertificate.SerialNumber.ToArray();
internal DateTime NotBefore => certificate.TbsCertificate.Validity.NotBefore.GetValue().UtcDateTime;
internal DateTime NotAfter => certificate.TbsCertificate.Validity.NotAfter.GetValue().UtcDateTime;
internal AlgorithmIdentifier PublicKeyAlgorithm => new AlgorithmIdentifier(certificate.TbsCertificate.SubjectPublicKeyInfo.Algorithm);
internal byte[] PublicKey => certificate.TbsCertificate.SubjectPublicKeyInfo.SubjectPublicKey.ToArray();
internal byte[] IssuerUniqueId => certificate.TbsCertificate.IssuerUniqueId?.ToArray();
internal byte[] SubjectUniqueId => certificate.TbsCertificate.SubjectUniqueId?.ToArray();
internal AlgorithmIdentifier SignatureAlgorithm => new AlgorithmIdentifier(certificate.SignatureAlgorithm);
internal byte[] SignatureValue => certificate.SignatureValue.ToArray();
internal CertificateData(byte[] rawData)
{
#if DEBUG
try
{
#endif
RawData = rawData;
certificate = CertificateAsn.Decode(rawData, AsnEncodingRules.DER);
certificate.TbsCertificate.ValidateVersion();
Issuer = new X500DistinguishedName(certificate.TbsCertificate.Issuer.ToArray());
Subject = new X500DistinguishedName(certificate.TbsCertificate.Subject.ToArray());
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
certificate.TbsCertificate.SubjectPublicKeyInfo.Encode(writer);
SubjectPublicKeyInfo = writer.Encode();
}
Extensions = new List<X509Extension>();
if (certificate.TbsCertificate.Extensions != null)
{
foreach (X509ExtensionAsn rawExtension in certificate.TbsCertificate.Extensions)
{
X509Extension extension = new X509Extension(
rawExtension.ExtnId,
rawExtension.ExtnValue.ToArray(),
rawExtension.Critical);
Extensions.Add(extension);
}
}
#if DEBUG
}
catch (Exception e)
{
throw new CryptographicException(
$"Error in reading certificate:{Environment.NewLine}{PemPrintCert(rawData)}",
e);
}
#endif
}
public string GetNameInfo(X509NameType nameType, bool forIssuer)
{
// Algorithm behaviors (pseudocode). When forIssuer is true, replace "Subject" with "Issuer" and
// SAN (Subject Alternative Names) with IAN (Issuer Alternative Names).
//
// SimpleName: Subject[CN] ?? Subject[OU] ?? Subject[O] ?? Subject[E] ?? Subject.Rdns.FirstOrDefault() ??
// SAN.Entries.FirstOrDefault(type == GEN_EMAIL);
// EmailName: SAN.Entries.FirstOrDefault(type == GEN_EMAIL) ?? Subject[E];
// UpnName: SAN.Entries.FirsOrDefaultt(type == GEN_OTHER && entry.AsOther().OID == szOidUpn).AsOther().Value;
// DnsName: SAN.Entries.FirstOrDefault(type == GEN_DNS) ?? Subject[CN];
// DnsFromAlternativeName: SAN.Entries.FirstOrDefault(type == GEN_DNS);
// UrlName: SAN.Entries.FirstOrDefault(type == GEN_URI);
if (nameType == X509NameType.SimpleName)
{
X500DistinguishedName name = forIssuer ? Issuer : Subject;
string candidate = GetSimpleNameInfo(name);
if (candidate != null)
{
return candidate;
}
}
// Check the Subject Alternative Name (or Issuer Alternative Name) for the right value;
{
string extensionId = forIssuer ? Oids.IssuerAltName : Oids.SubjectAltName;
GeneralNameType? matchType = null;
string otherOid = null;
// Currently all X509NameType types have a path where they look at the SAN/IAN,
// but we need to figure out which kind they want.
switch (nameType)
{
case X509NameType.DnsName:
case X509NameType.DnsFromAlternativeName:
matchType = GeneralNameType.DnsName;
break;
case X509NameType.SimpleName:
case X509NameType.EmailName:
matchType = GeneralNameType.Email;
break;
case X509NameType.UpnName:
matchType = GeneralNameType.OtherName;
otherOid = Oids.UserPrincipalName;
break;
case X509NameType.UrlName:
matchType = GeneralNameType.UniformResourceIdentifier;
break;
}
if (matchType.HasValue)
{
foreach (X509Extension extension in Extensions)
{
if (extension.Oid.Value == extensionId)
{
string candidate = FindAltNameMatch(extension.RawData, matchType.Value, otherOid);
if (candidate != null)
{
return candidate;
}
}
}
}
else
{
Debug.Fail($"Unresolved matchType for X509NameType.{nameType}");
}
}
// Subject-based fallback
{
string expectedKey = null;
switch (nameType)
{
case X509NameType.EmailName:
expectedKey = Oids.EmailAddress;
break;
case X509NameType.DnsName:
// Note: This does not include DnsFromAlternativeName, since
// the subject (or issuer) is not the Alternative Name.
expectedKey = Oids.CommonName;
break;
}
if (expectedKey != null)
{
X500DistinguishedName name = forIssuer ? Issuer : Subject;
foreach (var kvp in ReadReverseRdns(name))
{
if (kvp.Key == expectedKey)
{
return kvp.Value;
}
}
}
}
return "";
}
private static string GetSimpleNameInfo(X500DistinguishedName name)
{
string ou = null;
string o = null;
string e = null;
string firstRdn = null;
foreach (var kvp in ReadReverseRdns(name))
{
string oid = kvp.Key;
string value = kvp.Value;
// TODO: Check this (and the OpenSSL-using version) if OU/etc are specified more than once.
// (Compare against Windows)
switch (oid)
{
case Oids.CommonName:
return value;
case Oids.OrganizationalUnit:
ou = value;
break;
case Oids.Organization:
o = value;
break;
case Oids.EmailAddress:
e = value;
break;
default:
if (firstRdn == null)
{
firstRdn = value;
}
break;
}
}
return ou ?? o ?? e ?? firstRdn;
}
private static string FindAltNameMatch(byte[] extensionBytes, GeneralNameType matchType, string otherOid)
{
// If Other, have OID, else, no OID.
Debug.Assert(
(otherOid == null) == (matchType != GeneralNameType.OtherName),
$"otherOid has incorrect nullarity for matchType {matchType}");
Debug.Assert(
matchType == GeneralNameType.UniformResourceIdentifier ||
matchType == GeneralNameType.DnsName ||
matchType == GeneralNameType.Email ||
matchType == GeneralNameType.OtherName,
$"matchType ({matchType}) is not currently supported");
Debug.Assert(
otherOid == null || otherOid == Oids.UserPrincipalName,
$"otherOid ({otherOid}) is not supported");
AsnReader reader = new AsnReader(extensionBytes, AsnEncodingRules.DER);
AsnReader sequenceReader = reader.ReadSequence();
reader.ThrowIfNotEmpty();
while (sequenceReader.HasData)
{
GeneralNameAsn.Decode(sequenceReader, out GeneralNameAsn generalName);
switch (matchType)
{
case GeneralNameType.OtherName:
// If the OtherName OID didn't match, move to the next entry.
if (generalName.OtherName.HasValue && generalName.OtherName.Value.TypeId == otherOid)
{
// Currently only UPN is supported, which is a UTF8 string per
// https://msdn.microsoft.com/en-us/library/ff842518.aspx
AsnReader nameReader = new AsnReader(generalName.OtherName.Value.Value, AsnEncodingRules.DER);
string udnName = nameReader.GetCharacterString(UniversalTagNumber.UTF8String);
nameReader.ThrowIfNotEmpty();
return udnName;
}
break;
case GeneralNameType.Rfc822Name:
if (generalName.Rfc822Name != null)
{
return generalName.Rfc822Name;
}
break;
case GeneralNameType.DnsName:
if (generalName.DnsName != null)
{
return generalName.DnsName;
}
break;
case GeneralNameType.UniformResourceIdentifier:
if (generalName.Uri != null)
{
return generalName.Uri;
}
break;
}
}
return null;
}
private static IEnumerable<KeyValuePair<string, string>> ReadReverseRdns(X500DistinguishedName name)
{
AsnReader x500NameReader = new AsnReader(name.RawData, AsnEncodingRules.DER);
AsnReader sequenceReader = x500NameReader.ReadSequence();
var rdnReaders = new Stack<AsnReader>();
x500NameReader.ThrowIfNotEmpty();
while (sequenceReader.HasData)
{
rdnReaders.Push(sequenceReader.ReadSetOf());
}
while (rdnReaders.Count > 0)
{
AsnReader rdnReader = rdnReaders.Pop();
while (rdnReader.HasData)
{
AsnReader tavReader = rdnReader.ReadSequence();
string oid = tavReader.ReadObjectIdentifierAsString();
string value = tavReader.ReadDirectoryOrIA5String();
tavReader.ThrowIfNotEmpty();
yield return new KeyValuePair<string, string>(oid, value);
}
}
}
#if DEBUG
private static string PemPrintCert(byte[] rawData)
{
const string PemHeader = "-----BEGIN CERTIFICATE-----";
const string PemFooter = "-----END CERTIFICATE-----";
StringBuilder builder = new StringBuilder(PemHeader.Length + PemFooter.Length + rawData.Length * 2);
builder.Append(PemHeader);
builder.AppendLine();
builder.Append(Convert.ToBase64String(rawData, Base64FormattingOptions.InsertLineBreaks));
builder.AppendLine();
builder.Append(PemFooter);
builder.AppendLine();
return builder.ToString();
}
#endif
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using log4net;
using MindTouch.IO;
namespace MindTouch.Collections {
/// <summary>
/// A specialized queue that uses a two-phase dequeue to retrieve items
/// </summary>
/// <remarks>
/// Items dequeued are invisible to other users of the queue, but are not permanently removed until the dequeue is either committed,
/// or rolled back, the latter action making the item availabe for dequeuing again
/// </remarks>
/// <typeparam name="T">Type of entries in the queue</typeparam>
public class TransactionalQueue<T> : ITransactionalQueue<T> {
//--- Types ---
private class Item : ITransactionalQueueEntry<T> {
//--- Fields ---
public readonly IQueueStreamHandle Handle;
private readonly T _data;
//--- Constructors ---
public Item(T data, IQueueStreamHandle handle) {
_data = data;
Handle = handle;
}
//--- Properties ---
public T Value { get { return _data; } }
public long Id { get; set; }
public DateTime Expiration { get; set; }
//--- Methods ---
public Item Clone() {
return new Item(_data, Handle);
}
}
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
//--- Fields ---
private readonly IQueueStream _stream;
private readonly IQueueItemSerializer<T> _serializer;
private readonly Dictionary<long, Item> _pending = new Dictionary<long, Item>();
private readonly Queue<Item> _available = new Queue<Item>();
private bool _isDisposed;
private long _currentId = new Random().Next(int.MaxValue);
private DateTime _nextCollect = DateTime.MinValue;
//--- Constructors ---
/// <summary>
/// Create a new Queue given an <see cref="IQueueStream"/> storage provider and an <see cref="IQueueItemSerializer{T}"/> serializer for type T.
/// </summary>
/// <remarks>
/// This class assumes ownership of the provided <see cref="IQueueStream"/> resource and will dispose it upon instance disposal
/// </remarks>
/// <param name="stream">An implementation of <see cref="IQueueStream"/> <seealso cref="SingleFileQueueStream"/><seealso cref="MultiFileQueueStream"/></param>
/// <param name="serializer">A serializer implementation of <see cref="IQueueItemSerializer{T}"/> for type T</param>
public TransactionalQueue(IQueueStream stream, IQueueItemSerializer<T> serializer) {
_stream = stream;
_serializer = serializer;
DefaultCommitTimeout = TimeSpan.FromSeconds(30);
}
//--- Properties ---
/// <summary>
/// The default timeout used for a dequeued item before the item is considered abandoned and automatically rolled back
/// </summary>
public TimeSpan DefaultCommitTimeout { get; set; }
/// <summary>
/// The current count of items available for <see cref="Dequeue()"/>
/// </summary>
/// <remarks>
/// Count only reflects items available for dequeue, not items pending commit or rollback
/// </remarks>
public int Count {
get {
EnsureInstanceNotDisposed();
ProcessExpiredItems();
return _stream.UnreadCount + _available.Count;
}
}
//--- Methods ---
/// <summary>
/// Clear out the queue and drop all items, including pending commits.
/// </summary>
public void Clear() {
EnsureInstanceNotDisposed();
_log.DebugFormat("Clearing queue");
lock(_available) {
_stream.Truncate();
_available.Clear();
_pending.Clear();
}
}
/// <summary>
/// Put an item into the queue
/// </summary>
/// <param name="item">An instance of type T</param>
public void Enqueue(T item) {
EnsureInstanceNotDisposed();
var data = _serializer.ToStream(item);
lock(_available) {
_stream.AppendRecord(data, data.Length);
}
}
/// <summary>
/// Get the next available item from the queue. Must call <see cref="CommitDequeue"/> to fully take possession or the item. Uses <see cref="DefaultCommitTimeout"/>.
/// </summary>
/// <remarks>
/// Phase 1 of the two-phase dequeue. <see cref="CommitDequeue"/> within <see cref="DefaultCommitTimeout"/> completes the dequeue, while waiting for the timeout to
/// expire or calling <see cref="RollbackDequeue"/> aborts the dequeue.
/// </remarks>
/// <returns>
/// An instance of <see cref="ITransactionalQueueEntry{T}"/> wrapping the dequeued value and item id for use
/// with <see cref="CommitDequeue"/> or <see cref="RollbackDequeue"/>. <see langword="null"/> if the queue is empty.
/// </returns>
public ITransactionalQueueEntry<T> Dequeue() {
return Dequeue(DefaultCommitTimeout);
}
/// <summary>
/// Get the next available item from the queue. Must call <see cref="CommitDequeue"/> to fully take possession or the item.
/// </summary>
/// <remarks>
/// Phase 1 of the two-phase dequeue. <see cref="CommitDequeue"/> within <b>commitTimeout</b> completes the dequeue, while waiting for the timeout to
/// expire or calling <see cref="RollbackDequeue"/> aborts the dequeue.
/// </remarks>
/// <param name="commitTimeout">Time before an uncommitted dequeue is considered abandoned and automatically rolled back</param>
/// <returns>
/// An instance of <see cref="ITransactionalQueueEntry{T}"/> wrapping the dequeued value and item id for use
/// with <see cref="CommitDequeue"/> or <see cref="RollbackDequeue"/>. <see langword="null"/> if the queue is empty.
/// </returns>
public ITransactionalQueueEntry<T> Dequeue(TimeSpan commitTimeout) {
EnsureInstanceNotDisposed();
lock(_available) {
Item pending = null;
ProcessExpiredItems();
if(_available.Count > 0) {
pending = _available.Dequeue().Clone();
} else {
while(pending == null) {
var data = _stream.ReadNextRecord();
if(data == QueueStreamRecord.Empty) {
return null;
}
try {
pending = new Item(_serializer.FromStream(data.Stream), data.Handle);
} catch(Exception e) {
_log.Warn("message failed to deserialize", e);
}
}
}
pending.Id = _currentId++;
if( commitTimeout == TimeSpan.MinValue) {
pending.Expiration = DateTime.MinValue;
} else if(commitTimeout == TimeSpan.MaxValue) {
pending.Expiration = DateTime.MaxValue;
} else {
pending.Expiration = DateTime.UtcNow.Add(commitTimeout);
}
if(_nextCollect > pending.Expiration) {
_nextCollect = pending.Expiration;
}
_pending.Add(pending.Id, pending);
return pending;
}
}
/// <summary>
/// Completes the two-phase <see cref="Dequeue()"/>.
/// </summary>
/// <param name="id"><see cref="ITransactionalQueueEntry{T}.Id"/> identifier of the dequeued item</param>
/// <returns><see langword="true"/> if the commit succeeded, <see langword="false"/> if the item was already dequeued or has been rolled back</returns>
public bool CommitDequeue(long id) {
EnsureInstanceNotDisposed();
Item item;
lock(_available) {
ProcessExpiredItems();
if(!_pending.TryGetValue(id, out item)) {
return false;
}
_pending.Remove(id);
_stream.DeleteRecord(item.Handle);
}
return true;
}
/// <summary>
/// Undo <see cref="Dequeue()"/> and return item back to the queue.
/// </summary>
/// <param name="id"><see cref="ITransactionalQueueEntry{T}.Id"/> identifier of the dequeued item</param>
public void RollbackDequeue(long id) {
EnsureInstanceNotDisposed();
lock(_available) {
ProcessExpiredItems();
Item item;
if(!_pending.TryGetValue(id, out item)) {
return;
}
_pending.Remove(id);
_available.Enqueue(item);
}
}
/// <summary>
/// Clean up the resources used by the Queue per the <see cref="IDisposable"/> pattern
/// </summary>
public void Dispose() {
if(!_isDisposed) {
lock(_available) {
_isDisposed = true;
_stream.Dispose();
}
}
}
private void ProcessExpiredItems() {
lock(_available) {
var now = DateTime.UtcNow;
if(_pending.Count == 0 || now < _nextCollect) {
return;
}
var nextCollect = DateTime.MaxValue;
var released = new List<long>();
foreach(var item in _pending.Values) {
if(item.Expiration <= now) {
released.Add(item.Id);
_available.Enqueue(item);
} else if(item.Expiration < nextCollect) {
nextCollect = item.Expiration;
}
}
_nextCollect = nextCollect;
foreach(var id in released) {
_pending.Remove(id);
}
}
}
private void EnsureInstanceNotDisposed() {
if(_isDisposed) {
throw new ObjectDisposedException("the queue has been disposed");
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet
{
protected object CreateVirtualMachineScaleSetReimageDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pVMScaleSetName = new RuntimeDefinedParameter();
pVMScaleSetName.Name = "VMScaleSetName";
pVMScaleSetName.ParameterType = typeof(string);
pVMScaleSetName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true
});
pVMScaleSetName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("VMScaleSetName", pVMScaleSetName);
var pInstanceIds = new RuntimeDefinedParameter();
pInstanceIds.Name = "InstanceId";
pInstanceIds.ParameterType = typeof(string[]);
pInstanceIds.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 3,
Mandatory = false
});
pInstanceIds.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("InstanceId", pInstanceIds);
var pArgumentList = new RuntimeDefinedParameter();
pArgumentList.Name = "ArgumentList";
pArgumentList.ParameterType = typeof(object[]);
pArgumentList.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByStaticParameters",
Position = 4,
Mandatory = true
});
pArgumentList.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ArgumentList", pArgumentList);
return dynamicParameters;
}
protected void ExecuteVirtualMachineScaleSetReimageMethod(object[] invokeMethodInputParameters)
{
string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]);
System.Collections.Generic.IList<string> instanceIds = null;
if (invokeMethodInputParameters[2] != null)
{
var inputArray2 = Array.ConvertAll((object[]) ParseParameter(invokeMethodInputParameters[2]), e => e.ToString());
instanceIds = inputArray2.ToList();
}
var result = VirtualMachineScaleSetsClient.Reimage(resourceGroupName, vmScaleSetName, instanceIds);
WriteObject(result);
}
}
public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
{
protected PSArgument[] CreateVirtualMachineScaleSetReimageParameters()
{
string resourceGroupName = string.Empty;
string vmScaleSetName = string.Empty;
var instanceIds = new string[0];
return ConvertFromObjectsToArguments(
new string[] { "ResourceGroupName", "VMScaleSetName", "InstanceIds" },
new object[] { resourceGroupName, vmScaleSetName, instanceIds });
}
}
[Cmdlet(VerbsCommon.Set, "AzureRmVmss", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)]
[OutputType(typeof(PSOperationStatusResponse))]
public partial class SetAzureRmVmss : ComputeAutomationBaseCmdlet
{
protected override void ProcessRecord()
{
ExecuteClientAction(() =>
{
if (ShouldProcess(this.VMScaleSetName, VerbsCommon.Set))
{
string resourceGroupName = this.ResourceGroupName;
string vmScaleSetName = this.VMScaleSetName;
System.Collections.Generic.IList<string> instanceIds = this.InstanceId;
if (this.ParameterSetName.Equals("FriendMethod"))
{
var result = VirtualMachineScaleSetsClient.ReimageAll(resourceGroupName, vmScaleSetName, instanceIds);
var psObject = new PSOperationStatusResponse();
ComputeAutomationAutoMapperProfile.Mapper.Map<Azure.Management.Compute.Models.OperationStatusResponse, PSOperationStatusResponse>(result, psObject);
WriteObject(psObject);
}
else
{
var result = VirtualMachineScaleSetsClient.Reimage(resourceGroupName, vmScaleSetName, instanceIds);
var psObject = new PSOperationStatusResponse();
ComputeAutomationAutoMapperProfile.Mapper.Map<Azure.Management.Compute.Models.OperationStatusResponse, PSOperationStatusResponse>(result, psObject);
WriteObject(psObject);
}
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Parameter(
ParameterSetName = "FriendMethod",
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[AllowNull]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Parameter(
ParameterSetName = "FriendMethod",
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Alias("Name")]
[AllowNull]
public string VMScaleSetName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 3,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Parameter(
ParameterSetName = "FriendMethod",
Position = 3,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[AllowNull]
public string [] InstanceId { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Mandatory = true)]
[AllowNull]
public SwitchParameter Reimage { get; set; }
[Parameter(
ParameterSetName = "FriendMethod",
Mandatory = true)]
[AllowNull]
public SwitchParameter ReimageAll { get; set; }
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 638539 $
* $LastChangedDate: 2008-03-18 20:53:02 +0100 (mar., 18 mars 2008) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using IBatisNet.Common.Exceptions;
using IBatisNet.Common.Utilities.Objects;
using IBatisNet.DataMapper.Configuration.Serializers;
using IBatisNet.DataMapper.DataExchange;
using IBatisNet.DataMapper.Exceptions;
using IBatisNet.DataMapper.Scope;
using IBatisNet.Common.Utilities;
namespace IBatisNet.DataMapper.Configuration.ResultMapping
{
/// <summary>
/// Main implementation of ResultMap interface
/// </summary>
[Serializable]
[XmlRoot("resultMap", Namespace = "http://ibatis.apache.org/mapping")]
public class ResultMap : IResultMap
{
/// <summary>
/// Token for xml path to argument constructor elements.
/// </summary>
public static BindingFlags ANY_VISIBILITY_INSTANCE = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
/// <summary>
/// Token for xml path to result elements.
/// </summary>
private const string XML_RESULT = "result";
/// <summary>
/// Token for xml path to result elements.
/// </summary>
private const string XML_CONSTRUCTOR_ARGUMENT = "constructor/argument";
/// <summary>
/// Token for xml path to discriminator elements.
/// </summary>
private const string XML_DISCRIMNATOR = "discriminator";
/// <summary>
/// Token for xml path to subMap elements.
/// </summary>
private const string XML_SUBMAP = "subMap";
private static IResultMap _nullResultMap = null;
#region Fields
[NonSerialized]
private bool _isInitalized = true;
[NonSerialized]
private string _id = string.Empty;
[NonSerialized]
private string _className = string.Empty;
[NonSerialized]
private string _extendMap = string.Empty;
[NonSerialized]
private Type _class = null;
[NonSerialized]
private StringCollection _groupByPropertyNames = new StringCollection();
[NonSerialized]
private ResultPropertyCollection _properties = new ResultPropertyCollection();
[NonSerialized]
private ResultPropertyCollection _groupByProperties = new ResultPropertyCollection();
[NonSerialized]
private ResultPropertyCollection _parameters = new ResultPropertyCollection();
[NonSerialized]
private Discriminator _discriminator = null;
[NonSerialized]
private string _sqlMapNameSpace = string.Empty;
[NonSerialized]
private IFactory _objectFactory = null;
[NonSerialized]
private DataExchangeFactory _dataExchangeFactory = null;
[NonSerialized]
private IDataExchange _dataExchange = null;
#endregion
#region Properties
/// <summary>
/// The GroupBy Properties.
/// </summary>
[XmlIgnore]
public StringCollection GroupByPropertyNames
{
get { return _groupByPropertyNames; }
}
/// <summary>
/// Gets or sets a value indicating whether this instance is initalized.
/// </summary>
/// <value>
/// <c>true</c> if this instance is initalized; otherwise, <c>false</c>.
/// </value>
public bool IsInitalized
{
get { return true; }
set { _isInitalized = value; }
}
/// <summary>
/// The discriminator used to choose the good SubMap
/// </summary>
[XmlIgnore]
public Discriminator Discriminator
{
get { return _discriminator; }
set { _discriminator = value; }
}
/// <summary>
/// The collection of ResultProperty.
/// </summary>
[XmlIgnore]
public ResultPropertyCollection Properties
{
get { return _properties; }
}
/// <summary>
/// The GroupBy Properties.
/// </summary>
[XmlIgnore]
public ResultPropertyCollection GroupByProperties
{
get { return _groupByProperties; }
}
/// <summary>
/// The collection of constructor parameters.
/// </summary>
[XmlIgnore]
public ResultPropertyCollection Parameters
{
get { return _parameters; }
}
/// <summary>
/// Identifier used to identify the resultMap amongst the others.
/// </summary>
/// <example>GetProduct</example>
[XmlAttribute("id")]
public string Id
{
get { return _id; }
}
/// <summary>
/// Extend ResultMap attribute
/// </summary>
[XmlAttribute("extends")]
public string ExtendMap
{
get { return _extendMap; }
set { _extendMap = value; }
}
/// <summary>
/// The output type class of the resultMap.
/// </summary>
[XmlIgnore]
public Type Class
{
get { return _class; }
}
/// <summary>
/// Sets the IDataExchange
/// </summary>
[XmlIgnore]
public IDataExchange DataExchange
{
set { _dataExchange = value; }
}
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Initializes a new instance of the <see cref="ResultMap"/> class.
/// </summary>
/// <param name="configScope">The config scope.</param>
/// <param name="className">The output class name of the resultMap.</param>
/// <param name="extendMap">The extend result map bame.</param>
/// <param name="id">Identifier used to identify the resultMap amongst the others.</param>
/// <param name="groupBy">The groupBy properties</param>
public ResultMap(ConfigurationScope configScope, string id, string className, string extendMap, string groupBy)
{
_nullResultMap = new NullResultMap();
_dataExchangeFactory = configScope.DataExchangeFactory;
_sqlMapNameSpace = configScope.SqlMapNamespace;
if ((id == null) || (id.Length < 1))
{
throw new ArgumentNullException("The id attribute is mandatory in a ResultMap tag.");
}
_id = configScope.ApplyNamespace(id);
if ((className == null) || (className.Length < 1))
{
throw new ArgumentNullException("The class attribute is mandatory in the ResultMap tag id:" + _id);
}
_className = className;
_extendMap = extendMap;
if (groupBy != null && groupBy.Length > 0)
{
string[] groupByProperties = groupBy.Split(',');
for (int i = 0; i < groupByProperties.Length; i++)
{
string memberName = groupByProperties[i].Trim();
_groupByPropertyNames.Add(memberName);
}
}
}
#endregion
#region Methods
#region Configuration
/// <summary>
/// Initialize the resultMap from an xmlNode..
/// </summary>
/// <param name="configScope"></param>
public void Initialize(ConfigurationScope configScope)
{
try
{
_class = configScope.SqlMapper.TypeHandlerFactory.GetType(_className);
_dataExchange = _dataExchangeFactory.GetDataExchangeForClass(_class);
// Load the child node
GetChildNode(configScope);
// Verify that that each groupBy element correspond to a class member
// of one of result property
for (int i = 0; i < _groupByProperties.Count; i++)
{
string memberName = GroupByPropertyNames[i];
if (!_properties.Contains(memberName))
{
throw new ConfigurationException(
string.Format(
"Could not configure ResultMap named \"{0}\". Check the groupBy attribute. Cause: there's no result property named \"{1}\".",
_id, memberName));
}
}
}
catch (Exception e)
{
throw new ConfigurationException(
string.Format("Could not configure ResultMap named \"{0}\", Cause: {1}", _id, e.Message)
, e);
}
}
/// <summary>
/// Initializes the groupBy properties.
/// </summary>
public void InitializeGroupByProperties()
{
for (int i = 0; i < GroupByPropertyNames.Count; i++)
{
ResultProperty resultProperty = Properties.FindByPropertyName(this.GroupByPropertyNames[i]);
this.GroupByProperties.Add(resultProperty);
}
}
/// <summary>
/// Get the result properties and the subMap properties.
/// </summary>
/// <param name="configScope"></param>
private void GetChildNode(ConfigurationScope configScope)
{
ResultProperty mapping = null;
SubMap subMap = null;
#region Load the parameters constructor
XmlNodeList nodeList = configScope.NodeContext.SelectNodes(DomSqlMapBuilder.ApplyMappingNamespacePrefix(XML_CONSTRUCTOR_ARGUMENT), configScope.XmlNamespaceManager);
if (nodeList.Count > 0)
{
Type[] parametersType = new Type[nodeList.Count];
string[] parametersName = new string[nodeList.Count];
for (int i = 0; i < nodeList.Count; i++)
{
ArgumentProperty argumentMapping = ArgumentPropertyDeSerializer.Deserialize(nodeList[i], configScope);
_parameters.Add(argumentMapping);
parametersName[i] = argumentMapping.ArgumentName;
}
ConstructorInfo constructorInfo = this.GetConstructor(_class, parametersName);
for (int i = 0; i < _parameters.Count; i++)
{
ArgumentProperty argumentMapping = (ArgumentProperty)_parameters[i];
configScope.ErrorContext.MoreInfo = "initialize argument property : " + argumentMapping.ArgumentName;
argumentMapping.Initialize(configScope, constructorInfo);
parametersType[i] = argumentMapping.MemberType;
}
// Init the object factory
_objectFactory = configScope.SqlMapper.ObjectFactory.CreateFactory(_class, parametersType);
}
else
{
if (Type.GetTypeCode(_class) == TypeCode.Object)
{
_objectFactory = configScope.SqlMapper.ObjectFactory.CreateFactory(_class, Type.EmptyTypes);
}
}
#endregion
#region Load the Result Properties
foreach (XmlNode resultNode in configScope.NodeContext.SelectNodes(DomSqlMapBuilder.ApplyMappingNamespacePrefix(XML_RESULT), configScope.XmlNamespaceManager))
{
mapping = ResultPropertyDeSerializer.Deserialize(resultNode, configScope);
configScope.ErrorContext.MoreInfo = "initialize result property: " + mapping.PropertyName;
mapping.Initialize(configScope, _class);
_properties.Add(mapping);
}
#endregion
#region Load the Discriminator Property
XmlNode discriminatorNode = configScope.NodeContext.SelectSingleNode(DomSqlMapBuilder.ApplyMappingNamespacePrefix(XML_DISCRIMNATOR), configScope.XmlNamespaceManager);
if (discriminatorNode != null)
{
configScope.ErrorContext.MoreInfo = "initialize discriminator";
this.Discriminator = DiscriminatorDeSerializer.Deserialize(discriminatorNode, configScope);
this.Discriminator.SetMapping(configScope, _class);
}
#endregion
#region Load the SubMap Properties
if (configScope.NodeContext.SelectNodes(DomSqlMapBuilder.ApplyMappingNamespacePrefix(XML_SUBMAP), configScope.XmlNamespaceManager).Count > 0 && this.Discriminator == null)
{
throw new ConfigurationException("The discriminator is null, but somehow a subMap was reached. This is a bug.");
}
foreach (XmlNode resultNode in configScope.NodeContext.SelectNodes(DomSqlMapBuilder.ApplyMappingNamespacePrefix(XML_SUBMAP), configScope.XmlNamespaceManager))
{
configScope.ErrorContext.MoreInfo = "initialize subMap";
subMap = SubMapDeSerializer.Deserialize(resultNode, configScope);
this.Discriminator.Add(subMap);
}
#endregion
}
/// <summary>
/// Sets the object factory.
/// </summary>
public void SetObjectFactory(ConfigurationScope configScope)
{
Type[] parametersType = new Type[_parameters.Count];
for (int i = 0; i < _parameters.Count; i++)
{
ArgumentProperty argumentMapping = (ArgumentProperty)_parameters[i];
parametersType[i] = argumentMapping.MemberType;
}
// Init the object factory
_objectFactory = configScope.SqlMapper.ObjectFactory.CreateFactory(_class, parametersType);
}
/// <summary>
/// Finds the constructor that takes the parameters.
/// </summary>
/// <param name="type">The <see cref="System.Type"/> to find the constructor in.</param>
/// <param name="parametersName">The parameters name to use to find the appropriate constructor.</param>
/// <returns>
/// An <see cref="ConstructorInfo"/> that can be used to create the type with
/// the specified parameters.
/// </returns>
/// <exception cref="DataMapperException">
/// Thrown when no constructor with the correct signature can be found.
/// </exception>
private ConstructorInfo GetConstructor(Type type, string[] parametersName)
{
ConstructorInfo[] candidates = type.GetConstructors(ANY_VISIBILITY_INSTANCE);
foreach (ConstructorInfo constructor in candidates)
{
ParameterInfo[] parameters = constructor.GetParameters();
if (parameters.Length == parametersName.Length)
{
bool found = true;
for (int j = 0; j < parameters.Length; j++)
{
bool ok = (parameters[j].Name == parametersName[j]);
if (!ok)
{
found = false;
break;
}
}
if (found)
{
return constructor;
}
}
}
throw new DataMapperException("Cannot find an appropriate constructor which map parameters in class: " + type.Name);
}
#endregion
/// <summary>
/// Create an instance Of result.
/// </summary>
/// <param name="parameters">
/// An array of values that matches the number, order and type
/// of the parameters for this constructor.
/// </param>
/// <returns>An object.</returns>
public object CreateInstanceOfResult(object[] parameters)
{
TypeCode typeCode = Type.GetTypeCode(_class);
if (typeCode == TypeCode.Object)
{
return _objectFactory.CreateInstance(parameters);
}
else
{
return TypeUtils.InstantiatePrimitiveType(typeCode);
}
}
/// <summary>
/// Set the value of an object property.
/// </summary>
/// <param name="target">The object to set the property.</param>
/// <param name="property">The result property to use.</param>
/// <param name="dataBaseValue">The database value to set.</param>
public void SetValueOfProperty(ref object target, ResultProperty property, object dataBaseValue)
{
_dataExchange.SetData(ref target, property, dataBaseValue);
}
/// <summary>
///
/// </summary>
/// <param name="dataReader"></param>
/// <returns></returns>
public IResultMap ResolveSubMap(IDataReader dataReader)
{
IResultMap subMap = this;
if (_discriminator != null)
{
ResultProperty mapping = _discriminator.ResultProperty;
object dataBaseValue = mapping.GetDataBaseValue(dataReader);
if (dataBaseValue != null)
{
subMap = _discriminator.GetSubMap(dataBaseValue.ToString());
if (subMap == null)
{
subMap = this;
}
else if (subMap != this)
{
subMap = subMap.ResolveSubMap(dataReader);
}
}
else
{
subMap = _nullResultMap;
}
}
return subMap;
}
#endregion
}
}
| |
using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Test.Sections.Printing
{
[Section("Printing", "Print Dialog")]
public class PrintDialogSection : Panel
{
PrintSettings settings = new PrintSettings();
NumericUpDown selectedEnd;
NumericUpDown maximumEnd;
CheckBox allowPageRange;
CheckBox allowSelection;
public PrintDialogSection()
{
this.DataContext = settings;
var layout = new DynamicLayout { DefaultSpacing = new Size(5, 5), Padding = new Padding(10) };
layout.BeginVertical();
layout.BeginHorizontal();
layout.Add(null);
layout.BeginVertical(Padding.Empty);
layout.AddSeparateRow(null, ShowPrintDialog(), null);
layout.AddSeparateRow(null, PrintFromGraphicsWithDialog(), null);
layout.AddSeparateRow(null, PrintFromGraphics(), null);
layout.EndBeginVertical();
layout.Add(PrintDialogOptions());
layout.Add(null);
layout.EndVertical();
layout.Add(null);
layout.EndHorizontal();
layout.EndVertical();
layout.AddSeparateRow(null, PageRange(), Settings(), null);
layout.Add(null);
Content = layout;
}
Control PrintDialogOptions()
{
var layout = new DynamicLayout { DefaultSpacing = new Size(5, 5), Padding = new Padding(10) };
layout.AddRow(null, AllowPageRange());
layout.AddRow(null, AllowSelection());
return new GroupBox { Text = "Print Dialog Options", Content = layout };
}
Control AllowPageRange()
{
return allowPageRange = new CheckBox { Text = "Allow Page Range", Checked = new PrintDialog().AllowPageRange };
}
Control AllowSelection()
{
return allowSelection = new CheckBox { Text = "Allow Selection", Checked = new PrintDialog().AllowSelection };
}
PrintDialog CreatePrintDialog()
{
return new PrintDialog
{
PrintSettings = settings,
AllowSelection = allowSelection.Checked ?? false,
AllowPageRange = allowPageRange.Checked ?? false
};
}
Control ShowPrintDialog()
{
var control = new Button { Text = "Show Print Dialog" };
control.Click += delegate
{
var print = CreatePrintDialog();
var ret = print.ShowDialog(ParentWindow);
if (ret == DialogResult.Ok)
{
DataContext = settings = print.PrintSettings;
}
};
return control;
}
PrintDocument GetPrintDocument()
{
var document = new PrintDocument();
document.PrintSettings = settings;
var font = Fonts.Serif(16);
var printTime = DateTime.Now;
document.PrintPage += (sender, e) =>
{
Size pageSize = Size.Round(e.PageSize);
// draw a border around the printable area
var rect = new Rectangle(pageSize);
rect.Inflate(-1, -1);
e.Graphics.DrawRectangle(Pens.Silver, rect);
// draw title
e.Graphics.DrawText(font, Colors.Black, new Point(50, 20), document.Name);
// draw page number
var text = string.Format("page {0} of {1}", e.CurrentPage + 1, document.PageCount);
var textSize = Size.Round(e.Graphics.MeasureString(font, text));
e.Graphics.DrawText(font, Colors.Black, new Point(pageSize.Width - textSize.Width - 50, 20), text);
// draw date
text = string.Format("Printed on {0:f}", printTime);
textSize = Size.Round(e.Graphics.MeasureString(font, text));
e.Graphics.DrawText(font, Colors.Black, new Point(pageSize.Width - textSize.Width - 50, pageSize.Height - textSize.Height - 20), text);
// draw some rectangles
switch (e.CurrentPage)
{
case 0:
e.Graphics.DrawRectangle(Pens.Blue, new Rectangle(50, 50, 100, 100));
e.Graphics.DrawRectangle(Pens.Green, new Rectangle(new Point(pageSize) - new Size(150, 150), new Size(100, 100)));
break;
case 1:
e.Graphics.DrawRectangle(Pens.Blue, new Rectangle(pageSize.Width - 150, 50, 100, 100));
e.Graphics.DrawRectangle(Pens.Green, new Rectangle(50, pageSize.Height - 150, 100, 100));
break;
}
};
document.Name = "Name Of Document";
document.PageCount = 2;
return document;
}
Control PrintFromGraphics()
{
var control = new Button { Text = "Print From Graphics" };
control.Click += delegate
{
var document = GetPrintDocument();
document.Print();
};
return control;
}
Control PrintFromGraphicsWithDialog()
{
var control = new Button { Text = "Print From Graphics With Dialog" };
control.Click += delegate
{
var document = GetPrintDocument();
var dialog = CreatePrintDialog();
dialog.ShowDialog(this, document);
DataContext = settings = document.PrintSettings;
};
return control;
}
Control Settings()
{
var layout = new DynamicLayout { DefaultSpacing = new Size(5, 5), Padding = new Padding(10) };
layout.AddRow(new Label { Text = "Orientation" }, TableLayout.AutoSized(PageOrientation()));
layout.BeginHorizontal();
layout.Add(new Label { Text = "Copies" });
layout.AddSeparateRow().Add(TableLayout.AutoSized(Copies()), TableLayout.AutoSized(Collate()));
layout.EndHorizontal();
layout.BeginHorizontal();
layout.Add(new Label { Text = "Maximum Pages" });
layout.AddSeparateRow().Add(MaximumStart(), new Label { Text = "to" }, MaximumEnd());
layout.EndHorizontal();
layout.AddRow(null, Reverse());
return new GroupBox { Text = "Settings", Content = layout };
}
Control PageRange()
{
var layout = new DynamicLayout { DefaultSpacing = new Size(5, 5), Padding = new Padding(10) };
layout.AddRow(new Label { Text = "Print Selection" }, TableLayout.AutoSized(PrintSelection()));
layout.BeginHorizontal();
layout.Add(new Label { Text = "Selected Start" });
layout.AddSeparateRow().Add(SelectedStart(), new Label { Text = "to" }, SelectedEnd());
layout.EndHorizontal();
layout.Add(null);
return new GroupBox { Text = "Page Range", Content = layout };
}
static Control PageOrientation()
{
var control = new EnumDropDown<PageOrientation>();
control.SelectedValueBinding.BindDataContext<PrintSettings>(r => r.Orientation, (r, v) => r.Orientation = v);
return control;
}
static Control Copies()
{
var control = new NumericUpDown { MinValue = 1 };
control.ValueBinding.BindDataContext<PrintSettings>(r => r.Copies, (r, v) => r.Copies = (int)v, defaultGetValue: 1);
return control;
}
static Control Collate()
{
var control = new CheckBox { Text = "Collate" };
control.CheckedBinding.BindDataContext<PrintSettings>(r => r.Collate, (r, v) => r.Collate = v ?? false);
return control;
}
static Control Reverse()
{
var control = new CheckBox { Text = "Reverse" };
control.CheckedBinding.BindDataContext<PrintSettings>(r => r.Reverse, (r, v) => r.Reverse = v ?? false);
return control;
}
Control MaximumStart()
{
var control = new NumericUpDown { MinValue = 1 };
control.DataContextChanged += delegate
{
control.Value = settings.MaximumPageRange.Start;
};
control.ValueChanged += delegate
{
var range = settings.MaximumPageRange;
var end = range.End;
range = new Range<int>((int)control.Value, Math.Max(end, range.Start));
maximumEnd.MinValue = control.Value;
maximumEnd.Value = range.End;
settings.MaximumPageRange = range;
};
return control;
}
Control MaximumEnd()
{
var control = maximumEnd = new NumericUpDown { MinValue = 1 };
control.DataContextChanged += delegate
{
control.Value = settings.MaximumPageRange.End;
};
control.ValueChanged += delegate
{
var range = settings.MaximumPageRange;
settings.MaximumPageRange = new Range<int>(range.Start, (int)control.Value);
};
return control;
}
Control SelectedStart()
{
var control = new NumericUpDown { MinValue = 1 };
control.DataContextChanged += delegate
{
control.Value = settings.SelectedPageRange.Start;
};
control.ValueChanged += delegate
{
var range = settings.SelectedPageRange;
var end = range.End;
range = new Range<int>((int)control.Value, Math.Max(range.Start, end));
selectedEnd.MinValue = control.Value;
selectedEnd.Value = range.End;
settings.SelectedPageRange = range;
};
return control;
}
Control SelectedEnd()
{
var control = selectedEnd = new NumericUpDown { MinValue = 1 };
control.DataContextChanged += delegate
{
control.Value = settings.SelectedPageRange.End;
};
control.ValueChanged += delegate
{
var range = settings.SelectedPageRange;
settings.SelectedPageRange = new Range<int>(range.Start, (int)control.Value);
};
return control;
}
static Control PrintSelection()
{
var control = new EnumDropDown<PrintSelection>();
control.SelectedValueBinding.BindDataContext<PrintSettings>(r => r.PrintSelection, (r, v) => r.PrintSelection = v);
return control;
}
}
}
| |
// 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.Collections;
using System.Diagnostics;
using System.Globalization;
using Microsoft.Win32;
namespace OpenLiveWriter.CoreServices
{
//usage:
//Instrumentor.IncrementCounter(Instrumentor.COUNTERNAME);
//handles creating the registry keys and opt in stuff, so you don't have to
/// <summary>
/// Summary description for Intrumentor.
/// </summary>
public class Instrumentor
{
public const string WRITER_OPENED = "wr";
public const string LINKS = "lk";
public const string IMAGES = "im";
public const string MAPS = "ma";
public const string PLUG_INS_COUNT = "pc";
public const string PLUG_INS_LIST = "pl";
public const string SOURCE_CODE_VIEW = "sv";
public const string NO_STYLE_EDIT = "ns";
public const string EDIT_OLD_POST = "ep";
public const string DEFAULT_BLOG_PROVIDER = "db";
private const string ALWAYS_SEND = "n";
private const string OPT_IN_ONLY = "o";
private readonly static string instrumentationReportKey;
private static bool SearchLoggerWorks = false;
static Instrumentor()
{
try
{
using (RegistryKey slVersionKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSN Apps\\SL", false))
{
if (slVersionKey != null)
{
string version = (string)slVersionKey.GetValue("Version");
int minorVersionNum = Int32.Parse(version.Substring(version.LastIndexOf('.') + 1), CultureInfo.InvariantCulture);
int majorVersionNum = Int32.Parse(version.Substring(0,version.IndexOf('.')), CultureInfo.InvariantCulture);
if (majorVersionNum >= 3 && minorVersionNum >= 1458)
{
SearchLoggerWorks = true;
}
}
}
if (SearchLoggerWorks)
{
string hkcu = string.Empty;
if (Environment.OSVersion.Version.Major >= 6)
{
// Under Vista Protected Mode, this is the low-integrity root
hkcu = @"Software\AppDataLow\";
}
instrumentationReportKey = hkcu + @"Software\Microsoft\MSN Apps\Open Live Writer\SL";
}
else
{
instrumentationReportKey = null;
}
}
catch (Exception ex)
{
Trace.Fail("Exception while writing instrumentation values to registry: " + ex.ToString());
}
}
public static void IncrementCounter(string keyName)
{
string regKey = GetKeyName(keyName);
//check that AL key exists--if not, add it
//check that specific key exists--if not, add it
//increment specific key
try
{
if (SearchLoggerWorks)
{
using ( RegistryKey reportingKey = Registry.CurrentUser.CreateSubKey(instrumentationReportKey) )
{
if ( reportingKey != null )
{
int currentVal = (int)reportingKey.GetValue(regKey, 0);
currentVal++;
reportingKey.SetValue(regKey, currentVal);
}
else
{
Debug.Fail("Unable to open Onfolio instrumentation reporting registry key") ;
}
}
}
}
catch (Exception ex)
{
Trace.Fail("Exception while writing instrumentation values to registry: " + ex.ToString());
}
}
public static void SetKeyValue(string keyName, object keyValue)
{
string regKey = GetKeyName(keyName);
//check that AL key exists--if not, add it
//check that specific key exists--if not, add it
try
{
if (SearchLoggerWorks)
{
using ( RegistryKey reportingKey = Registry.CurrentUser.CreateSubKey(instrumentationReportKey) )
{
if ( reportingKey != null )
{
reportingKey.SetValue(regKey, keyValue);
}
else
{
Debug.Fail("Unable to open Onfolio instrumentation reporting registry key") ;
}
}
}
}
catch (Exception ex)
{
Trace.Fail("Exception while writing instrumentation values to registry: " + ex.ToString());
}
}
public static void AddItemToList(string keyName, string item)
{
string regKey = GetKeyName(keyName);
//check that AL key exists--if not, add it
//check that specific key exists--if not, add it
try
{
if (SearchLoggerWorks)
{
using ( RegistryKey reportingKey = Registry.CurrentUser.CreateSubKey(instrumentationReportKey) )
{
if ( reportingKey != null )
{
string newVal = EscapeString(item);
String currentVal = (String)reportingKey.GetValue(regKey, "");
if (currentVal != "")
{
//add this item if it isn't in the list
if (currentVal.IndexOf(newVal) < 0)
{
currentVal += "," + newVal;
}
}
else
{
//new list, set to item
currentVal = newVal;
}
reportingKey.SetValue(regKey, currentVal);
}
else
{
Debug.Fail("Unable to open Writer instrumentation reporting registry key") ;
}
}
}
}
catch (Exception ex)
{
Trace.Fail("Exception while writing instrumentation values to registry: " + ex.ToString());
}
}
private static string GetKeyName(string keyName)
{
string regKey = keyName;
//the final letter of the key name determines whether it is opt-in only or not
//right now everything is opt in only
regKey += OPT_IN_ONLY;
return regKey;
}
private static string EscapeString(string val)
{
if (val == null)
return "";
// optimize for common case
if (val.IndexOf('\t') == -1 && val.IndexOf('\n') == -1 && val.IndexOf('\"') == -1)
return "\"" + val + "\"";
return "\"" + val.Replace("\"", "\"\"") + "\"";
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// EvaluationResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Numbers.V2.RegulatoryCompliance.Bundle
{
public class EvaluationResource : Resource
{
public sealed class StatusEnum : StringEnum
{
private StatusEnum(string value) : base(value) {}
public StatusEnum() {}
public static implicit operator StatusEnum(string value)
{
return new StatusEnum(value);
}
public static readonly StatusEnum Compliant = new StatusEnum("compliant");
public static readonly StatusEnum Noncompliant = new StatusEnum("noncompliant");
}
private static Request BuildCreateRequest(CreateEvaluationOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Numbers,
"/v2/RegulatoryCompliance/Bundles/" + options.PathBundleSid + "/Evaluations",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Creates an evaluation for a bundle
/// </summary>
/// <param name="options"> Create Evaluation parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Evaluation </returns>
public static EvaluationResource Create(CreateEvaluationOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Creates an evaluation for a bundle
/// </summary>
/// <param name="options"> Create Evaluation parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Evaluation </returns>
public static async System.Threading.Tasks.Task<EvaluationResource> CreateAsync(CreateEvaluationOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Creates an evaluation for a bundle
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Evaluation </returns>
public static EvaluationResource Create(string pathBundleSid, ITwilioRestClient client = null)
{
var options = new CreateEvaluationOptions(pathBundleSid);
return Create(options, client);
}
#if !NET35
/// <summary>
/// Creates an evaluation for a bundle
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Evaluation </returns>
public static async System.Threading.Tasks.Task<EvaluationResource> CreateAsync(string pathBundleSid,
ITwilioRestClient client = null)
{
var options = new CreateEvaluationOptions(pathBundleSid);
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadEvaluationOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Numbers,
"/v2/RegulatoryCompliance/Bundles/" + options.PathBundleSid + "/Evaluations",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of Evaluations associated to the Bundle resource.
/// </summary>
/// <param name="options"> Read Evaluation parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Evaluation </returns>
public static ResourceSet<EvaluationResource> Read(ReadEvaluationOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<EvaluationResource>.FromJson("results", response.Content);
return new ResourceSet<EvaluationResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of Evaluations associated to the Bundle resource.
/// </summary>
/// <param name="options"> Read Evaluation parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Evaluation </returns>
public static async System.Threading.Tasks.Task<ResourceSet<EvaluationResource>> ReadAsync(ReadEvaluationOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<EvaluationResource>.FromJson("results", response.Content);
return new ResourceSet<EvaluationResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of Evaluations associated to the Bundle resource.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Evaluation </returns>
public static ResourceSet<EvaluationResource> Read(string pathBundleSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadEvaluationOptions(pathBundleSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of Evaluations associated to the Bundle resource.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Evaluation </returns>
public static async System.Threading.Tasks.Task<ResourceSet<EvaluationResource>> ReadAsync(string pathBundleSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadEvaluationOptions(pathBundleSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<EvaluationResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<EvaluationResource>.FromJson("results", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<EvaluationResource> NextPage(Page<EvaluationResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Numbers)
);
var response = client.Request(request);
return Page<EvaluationResource>.FromJson("results", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<EvaluationResource> PreviousPage(Page<EvaluationResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Numbers)
);
var response = client.Request(request);
return Page<EvaluationResource>.FromJson("results", response.Content);
}
private static Request BuildFetchRequest(FetchEvaluationOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Numbers,
"/v2/RegulatoryCompliance/Bundles/" + options.PathBundleSid + "/Evaluations/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch specific Evaluation Instance.
/// </summary>
/// <param name="options"> Fetch Evaluation parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Evaluation </returns>
public static EvaluationResource Fetch(FetchEvaluationOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch specific Evaluation Instance.
/// </summary>
/// <param name="options"> Fetch Evaluation parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Evaluation </returns>
public static async System.Threading.Tasks.Task<EvaluationResource> FetchAsync(FetchEvaluationOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch specific Evaluation Instance.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource </param>
/// <param name="pathSid"> The unique string that identifies the Evaluation resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Evaluation </returns>
public static EvaluationResource Fetch(string pathBundleSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchEvaluationOptions(pathBundleSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch specific Evaluation Instance.
/// </summary>
/// <param name="pathBundleSid"> The unique string that identifies the resource </param>
/// <param name="pathSid"> The unique string that identifies the Evaluation resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Evaluation </returns>
public static async System.Threading.Tasks.Task<EvaluationResource> FetchAsync(string pathBundleSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchEvaluationOptions(pathBundleSid, pathSid);
return await FetchAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a EvaluationResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> EvaluationResource object represented by the provided JSON </returns>
public static EvaluationResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<EvaluationResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the Evaluation resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The unique string of a regulation
/// </summary>
[JsonProperty("regulation_sid")]
public string RegulationSid { get; private set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("bundle_sid")]
public string BundleSid { get; private set; }
/// <summary>
/// The compliance status of the Evaluation resource
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public EvaluationResource.StatusEnum Status { get; private set; }
/// <summary>
/// The results of the Evaluation resource
/// </summary>
[JsonProperty("results")]
public List<object> Results { get; private set; }
/// <summary>
/// The date_created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The url
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private EvaluationResource()
{
}
}
}
| |
//-----------------------------------------------------------------------------
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
//^ using Microsoft.Contracts;
namespace Microsoft.Cci {
/// <summary>
/// A definition that is a member of a namespace. Typically a nested namespace or a namespace type definition.
/// </summary>
[ContractClass(typeof(INamespaceMemberContract))]
public interface INamespaceMember : IContainerMember<INamespaceDefinition>, IDefinition, IScopeMember<IScope<INamespaceMember>> {
/// <summary>
/// The namespace that contains this member.
/// </summary>
INamespaceDefinition ContainingNamespace { get; }
}
[ContractClassFor(typeof(INamespaceMember))]
abstract class INamespaceMemberContract : INamespaceMember {
public INamespaceDefinition ContainingNamespace {
get {
Contract.Ensures(Contract.Result<INamespaceDefinition>() != null);
throw new NotImplementedException();
}
}
public INamespaceDefinition Container {
get { throw new NotImplementedException(); }
}
public IName Name {
get { throw new NotImplementedException(); }
}
public IEnumerable<ICustomAttribute> Attributes {
get { throw new NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
public IEnumerable<ILocation> Locations {
get { throw new NotImplementedException(); }
}
public IScope<INamespaceMember> ContainingScope {
get { throw new NotImplementedException(); }
}
public void DispatchAsReference(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
}
/// <summary>
/// Implemented by objects that are associated with a root INamespace object.
/// </summary>
[ContractClass(typeof(INamespaceRootOwnerContract))]
public interface INamespaceRootOwner {
/// <summary>
/// The associated root namespace.
/// </summary>
INamespaceDefinition NamespaceRoot {
get;
//^ ensures result.RootOwner == this;
}
}
[ContractClassFor(typeof(INamespaceRootOwner))]
abstract class INamespaceRootOwnerContract : INamespaceRootOwner {
public INamespaceDefinition NamespaceRoot {
get {
Contract.Ensures(Contract.Result<INamespaceDefinition>() != null);
throw new NotImplementedException();
}
}
}
/// <summary>
/// A unit namespace that is nested inside another unit namespace.
/// </summary>
[ContractClass(typeof(INestedUnitNamespaceContract))]
public interface INestedUnitNamespace : IUnitNamespace, INamespaceMember, INestedUnitNamespaceReference {
/// <summary>
/// The unit namespace that contains this member.
/// </summary>
new IUnitNamespace ContainingUnitNamespace { get; }
}
[ContractClassFor(typeof(INestedUnitNamespace))]
abstract class INestedUnitNamespaceContract : INestedUnitNamespace {
public IUnitNamespace ContainingUnitNamespace {
get {
Contract.Ensures(Contract.Result<IUnitNamespace>() != null);
throw new NotImplementedException();
}
}
public IUnit Unit {
get { throw new NotImplementedException(); }
}
public INamespaceRootOwner RootOwner {
get { throw new NotImplementedException(); }
}
public IEnumerable<INamespaceMember> Members {
get { throw new NotImplementedException(); }
}
public IEnumerable<ICustomAttribute> Attributes {
get { throw new NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
public IEnumerable<ILocation> Locations {
get { throw new NotImplementedException(); }
}
public IName Name {
get { throw new NotImplementedException(); }
}
public bool Contains(INamespaceMember member) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMatchingMembersNamed(IName name, bool ignoreCase, Function<INamespaceMember, bool> predicate) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMatchingMembers(Function<INamespaceMember, bool> predicate) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMembersNamed(IName name, bool ignoreCase) {
throw new NotImplementedException();
}
IUnitReference IUnitNamespaceReference.Unit {
get { throw new NotImplementedException(); }
}
public IUnitNamespace ResolvedUnitNamespace {
get { throw new NotImplementedException(); }
}
public INamespaceDefinition ContainingNamespace {
get { throw new NotImplementedException(); }
}
public INamespaceDefinition Container {
get { throw new NotImplementedException(); }
}
public IScope<INamespaceMember> ContainingScope {
get { throw new NotImplementedException(); }
}
IUnitNamespaceReference INestedUnitNamespaceReference.ContainingUnitNamespace {
get { throw new NotImplementedException(); }
}
public INestedUnitNamespace ResolvedNestedUnitNamespace {
get { throw new NotImplementedException(); }
}
public void DispatchAsReference(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
}
/// <summary>
/// A reference to a nested unit namespace.
/// </summary>
[ContractClass(typeof(INestedUnitNamespaceReferenceContract))]
public interface INestedUnitNamespaceReference : IUnitNamespaceReference, INamedEntity {
/// <summary>
/// A reference to the unit namespace that contains the referenced nested unit namespace.
/// </summary>
IUnitNamespaceReference ContainingUnitNamespace { get; }
/// <summary>
/// The namespace definition being referred to.
/// </summary>
INestedUnitNamespace ResolvedNestedUnitNamespace { get; }
}
[ContractClassFor(typeof(INestedUnitNamespaceReference))]
abstract class INestedUnitNamespaceReferenceContract : INestedUnitNamespaceReference {
public IUnitNamespaceReference ContainingUnitNamespace {
get {
Contract.Ensures(Contract.Result<IUnitNamespaceReference>() != null);
Contract.Ensures(Contract.Result<IUnitNamespaceReference>() != this);
throw new NotImplementedException();
}
}
public INestedUnitNamespace ResolvedNestedUnitNamespace {
get {
Contract.Ensures(Contract.Result<INestedUnitNamespace>() != null);
throw new NotImplementedException();
}
}
public IUnitReference Unit {
get { throw new NotImplementedException(); }
}
public IUnitNamespace ResolvedUnitNamespace {
get { throw new NotImplementedException(); }
}
public IEnumerable<ICustomAttribute> Attributes {
get { throw new NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
public IEnumerable<ILocation> Locations {
get { throw new NotImplementedException(); }
}
public IName Name {
get { throw new NotImplementedException(); }
}
public void DispatchAsReference(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
}
/// <summary>
/// A unit set namespace that is nested inside another unit set namespace.
/// </summary>
[ContractClass(typeof(INestedUnitSetNamespaceContract))]
public interface INestedUnitSetNamespace : IUnitSetNamespace, INamespaceMember {
/// <summary>
/// The unit set namespace that contains this member.
/// </summary>
IUnitSetNamespace ContainingUnitSetNamespace { get; }
}
[ContractClassFor(typeof(INestedUnitSetNamespace))]
abstract class INestedUnitSetNamespaceContract : INestedUnitSetNamespace {
public IUnitSetNamespace ContainingUnitSetNamespace {
get {
Contract.Ensures(Contract.Result<IUnitSetNamespace>() != null);
throw new NotImplementedException();
}
}
public IUnitSet UnitSet {
get { throw new NotImplementedException(); }
}
public INamespaceRootOwner RootOwner {
get { throw new NotImplementedException(); }
}
public IEnumerable<INamespaceMember> Members {
get { throw new NotImplementedException(); }
}
public IEnumerable<ICustomAttribute> Attributes {
get { throw new NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
public IEnumerable<ILocation> Locations {
get { throw new NotImplementedException(); }
}
public IName Name {
get { throw new NotImplementedException(); }
}
public bool Contains(INamespaceMember member) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMatchingMembersNamed(IName name, bool ignoreCase, Function<INamespaceMember, bool> predicate) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMatchingMembers(Function<INamespaceMember, bool> predicate) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMembersNamed(IName name, bool ignoreCase) {
throw new NotImplementedException();
}
public INamespaceDefinition ContainingNamespace {
get { throw new NotImplementedException(); }
}
public INamespaceDefinition Container {
get { throw new NotImplementedException(); }
}
public IScope<INamespaceMember> ContainingScope {
get { throw new NotImplementedException(); }
}
public void DispatchAsReference(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
}
/// <summary>
/// A named collection of namespace members, with routines to search and maintain the collection.
/// </summary>
[ContractClass(typeof(INamespaceDefinitionContract))]
public interface INamespaceDefinition : IContainer<INamespaceMember>, IDefinition, INamedEntity, IScope<INamespaceMember> {
/// <summary>
/// The object associated with the namespace. For example an IUnit or IUnitSet instance. This namespace is either the root namespace of that object
/// or it is a nested namespace that is directly of indirectly nested in the root namespace.
/// </summary>
INamespaceRootOwner RootOwner {
get;
}
/// <summary>
/// The collection of member objects comprising the namespaces.
/// </summary>
new IEnumerable<INamespaceMember> Members {
get;
}
}
[ContractClassFor(typeof(INamespaceDefinition))]
abstract class INamespaceDefinitionContract : INamespaceDefinition {
public INamespaceRootOwner RootOwner {
get {
Contract.Ensures(Contract.Result<INamespaceRootOwner>() != null);
throw new NotImplementedException();
}
}
IEnumerable<INamespaceMember> INamespaceDefinition.Members {
get {
Contract.Ensures(Contract.Result<IEnumerable<INamespaceMember>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<INamespaceMember>>(), x => x != null));
throw new NotImplementedException();
}
}
public IEnumerable<ICustomAttribute> Attributes {
get { throw new NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
public IEnumerable<ILocation> Locations {
get { throw new NotImplementedException(); }
}
public IName Name {
get { throw new NotImplementedException(); }
}
public bool Contains(INamespaceMember member) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMatchingMembersNamed(IName name, bool ignoreCase, Function<INamespaceMember, bool> predicate) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMatchingMembers(Function<INamespaceMember, bool> predicate) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMembersNamed(IName name, bool ignoreCase) {
throw new NotImplementedException();
}
public void DispatchAsReference(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> Members {
get { throw new NotImplementedException(); }
}
}
/// <summary>
/// A unit namespace that is not nested inside another namespace.
/// </summary>
public interface IRootUnitNamespace : IUnitNamespace, IRootUnitNamespaceReference {
}
/// <summary>
/// A reference to a root unit namespace.
/// </summary>
public interface IRootUnitNamespaceReference : IUnitNamespaceReference {
}
/// <summary>
/// A named collection of namespace members, with routines to search and maintain the collection. All the members belong to an associated
/// IUnit instance.
/// </summary>
[ContractClass(typeof(IUnitNamespaceContract))]
public interface IUnitNamespace : INamespaceDefinition, IUnitNamespaceReference {
/// <summary>
/// The IUnit instance associated with this namespace.
/// </summary>
new IUnit Unit {
get;
}
}
[ContractClassFor(typeof(IUnitNamespace))]
abstract class IUnitNamespaceContract : IUnitNamespace {
public IUnit Unit {
get {
Contract.Ensures(Contract.Result<IUnit>() != null);
throw new NotImplementedException();
}
}
public INamespaceRootOwner RootOwner {
get { throw new NotImplementedException(); }
}
public IEnumerable<INamespaceMember> Members {
get { throw new NotImplementedException(); }
}
public IEnumerable<ICustomAttribute> Attributes {
get { throw new NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
public IEnumerable<ILocation> Locations {
get { throw new NotImplementedException(); }
}
public IName Name {
get { throw new NotImplementedException(); }
}
public bool Contains(INamespaceMember member) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMatchingMembersNamed(IName name, bool ignoreCase, Function<INamespaceMember, bool> predicate) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMatchingMembers(Function<INamespaceMember, bool> predicate) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMembersNamed(IName name, bool ignoreCase) {
throw new NotImplementedException();
}
IUnitReference IUnitNamespaceReference.Unit {
get { throw new NotImplementedException(); }
}
public IUnitNamespace ResolvedUnitNamespace {
get { throw new NotImplementedException(); }
}
public void DispatchAsReference(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
}
/// <summary>
/// A reference to an unit namespace.
/// </summary>
public partial interface IUnitNamespaceReference : IReference {
/// <summary>
/// A reference to the unit that defines the referenced namespace.
/// </summary>
IUnitReference Unit {
get;
}
/// <summary>
/// The namespace definition being referred to.
/// </summary>
IUnitNamespace ResolvedUnitNamespace { get; }
}
#region IUnitNamespaceReference contract binding
[ContractClass(typeof(IUnitNamespaceReferenceContract))]
public partial interface IUnitNamespaceReference {
}
[ContractClassFor(typeof(IUnitNamespaceReference))]
abstract class IUnitNamespaceReferenceContract : IUnitNamespaceReference {
public IUnitReference Unit {
get {
Contract.Ensures(Contract.Result<IUnitReference>() != null);
throw new NotImplementedException();
}
}
public IUnitNamespace ResolvedUnitNamespace {
get {
Contract.Ensures(Contract.Result<IUnitNamespace>() != null);
throw new NotImplementedException();
}
}
public IEnumerable<ICustomAttribute> Attributes {
get { throw new NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
public IEnumerable<ILocation> Locations {
get { throw new NotImplementedException(); }
}
public void DispatchAsReference(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
}
#endregion
/// <summary>
/// A named collection of namespace members, with routines to search and maintain the collection. The collection of members
/// is the union of the individual members collections of one of more IUnit instances making up the IUnitSet instance associated
/// with this namespace.
/// </summary>
// Issue: If we just want to model Metadata/Language independent model faithfully, why do we need unit sets etc? This seems to be more of an
// Symbol table lookup helper interface.
[ContractClass(typeof(IUnitSetNamespaceContract))]
public interface IUnitSetNamespace : INamespaceDefinition {
/// <summary>
/// The IUnitSet instance associated with the namespace.
/// </summary>
IUnitSet UnitSet {
get;
}
}
[ContractClassFor(typeof(IUnitSetNamespace))]
abstract class IUnitSetNamespaceContract : IUnitSetNamespace {
public IUnitSet UnitSet {
get {
Contract.Ensures(Contract.Result<IUnitSet>() != null);
throw new NotImplementedException();
}
}
public INamespaceRootOwner RootOwner {
get { throw new NotImplementedException(); }
}
public IEnumerable<INamespaceMember> Members {
get { throw new NotImplementedException(); }
}
public IEnumerable<ICustomAttribute> Attributes {
get { throw new NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
public IEnumerable<ILocation> Locations {
get { throw new NotImplementedException(); }
}
public IName Name {
get { throw new NotImplementedException(); }
}
public bool Contains(INamespaceMember member) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMatchingMembersNamed(IName name, bool ignoreCase, Function<INamespaceMember, bool> predicate) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMatchingMembers(Function<INamespaceMember, bool> predicate) {
throw new NotImplementedException();
}
public IEnumerable<INamespaceMember> GetMembersNamed(IName name, bool ignoreCase) {
throw new NotImplementedException();
}
public void DispatchAsReference(IMetadataVisitor visitor) {
throw new NotImplementedException();
}
}
/// <summary>
/// A unit set namespace that is not nested inside another namespace.
/// </summary>
public interface IRootUnitSetNamespace : IUnitSetNamespace {
}
}
| |
// <copyright file="DriverService.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Permissions;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium
{
/// <summary>
/// Exposes the service provided by a native WebDriver server executable.
/// </summary>
public abstract class DriverService : ICommandServer
{
private string driverServicePath;
private string driverServiceExecutableName;
private string driverServiceHostName = "localhost";
private int driverServicePort;
private bool silent;
private bool hideCommandPromptWindow;
private bool isDisposed;
private Process driverServiceProcess;
/// <summary>
/// Initializes a new instance of the <see cref="DriverService"/> class.
/// </summary>
/// <param name="servicePath">The full path to the directory containing the executable providing the service to drive the browser.</param>
/// <param name="port">The port on which the driver executable should listen.</param>
/// <param name="driverServiceExecutableName">The file name of the driver service executable.</param>
/// <param name="driverServiceDownloadUrl">A URL at which the driver service executable may be downloaded.</param>
/// <exception cref="ArgumentException">
/// If the path specified is <see langword="null"/> or an empty string.
/// </exception>
/// <exception cref="DriverServiceNotFoundException">
/// If the specified driver service executable does not exist in the specified directory.
/// </exception>
protected DriverService(string servicePath, int port, string driverServiceExecutableName, Uri driverServiceDownloadUrl)
{
if (string.IsNullOrEmpty(servicePath))
{
throw new ArgumentException("Path to locate driver executable cannot be null or empty.", "servicePath");
}
string executablePath = Path.Combine(servicePath, driverServiceExecutableName);
if (!File.Exists(executablePath))
{
throw new DriverServiceNotFoundException(string.Format(CultureInfo.InvariantCulture, "The file {0} does not exist. The driver can be downloaded at {1}", executablePath, driverServiceDownloadUrl));
}
this.driverServicePath = servicePath;
this.driverServiceExecutableName = driverServiceExecutableName;
this.driverServicePort = port;
}
/// <summary>
/// Occurs when the driver process is starting.
/// </summary>
public event EventHandler<DriverProcessStartingEventArgs> DriverProcessStarting;
/// <summary>
/// Occurs when the driver process has completely started.
/// </summary>
public event EventHandler<DriverProcessStartedEventArgs> DriverProcessStarted;
/// <summary>
/// Gets the Uri of the service.
/// </summary>
public Uri ServiceUrl
{
get { return new Uri(string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}", this.driverServiceHostName, this.driverServicePort)); }
}
/// <summary>
/// Gets or sets the host name of the service. Defaults to "localhost."
/// </summary>
/// <remarks>
/// Most driver service executables do not allow connections from remote
/// (non-local) machines. This property can be used as a workaround so
/// that an IP address (like "127.0.0.1" or "::1") can be used instead.
/// </remarks>
public string HostName
{
get { return this.driverServiceHostName; }
set { this.driverServiceHostName = value; }
}
/// <summary>
/// Gets or sets the port of the service.
/// </summary>
public int Port
{
get { return this.driverServicePort; }
set { this.driverServicePort = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the initial diagnostic information is suppressed
/// when starting the driver server executable. Defaults to <see langword="false"/>, meaning
/// diagnostic information should be shown by the driver server executable.
/// </summary>
public bool SuppressInitialDiagnosticInformation
{
get { return this.silent; }
set { this.silent = value; }
}
/// <summary>
/// Gets a value indicating whether the service is running.
/// </summary>
public bool IsRunning
{
[SecurityPermission(SecurityAction.Demand)]
get { return this.driverServiceProcess != null && !this.driverServiceProcess.HasExited; }
}
/// <summary>
/// Gets or sets a value indicating whether the command prompt window of the service should be hidden.
/// </summary>
public bool HideCommandPromptWindow
{
get { return this.hideCommandPromptWindow; }
set { this.hideCommandPromptWindow = value; }
}
/// <summary>
/// Gets the process ID of the running driver service executable. Returns 0 if the process is not running.
/// </summary>
public int ProcessId
{
get
{
if (this.IsRunning)
{
// There's a slight chance that the Process object is running,
// but does not have an ID set. This should be rare, but we
// definitely don't want to throw an exception.
try
{
return this.driverServiceProcess.Id;
}
catch (InvalidOperationException)
{
}
}
return 0;
}
}
/// <summary>
/// Gets the executable file name of the driver service.
/// </summary>
protected string DriverServiceExecutableName
{
get { return this.driverServiceExecutableName; }
}
/// <summary>
/// Gets the command-line arguments for the driver service.
/// </summary>
protected virtual string CommandLineArguments
{
get { return string.Format(CultureInfo.InvariantCulture, "--port={0}", this.driverServicePort); }
}
/// <summary>
/// Gets a value indicating the time to wait for an initial connection before timing out.
/// </summary>
protected virtual TimeSpan InitializationTimeout
{
get { return TimeSpan.FromSeconds(20); }
}
/// <summary>
/// Gets a value indicating the time to wait for the service to terminate before forcing it to terminate.
/// </summary>
protected virtual TimeSpan TerminationTimeout
{
get { return TimeSpan.FromSeconds(10); }
}
/// <summary>
/// Gets a value indicating whether the service has a shutdown API that can be called to terminate
/// it gracefully before forcing a termination.
/// </summary>
protected virtual bool HasShutdown
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the service is responding to HTTP requests.
/// </summary>
protected virtual bool IsInitialized
{
get
{
bool isInitialized = false;
try
{
Uri serviceHealthUri = new Uri(this.ServiceUrl, new Uri(DriverCommand.Status, UriKind.Relative));
HttpWebRequest request = HttpWebRequest.Create(serviceHealthUri) as HttpWebRequest;
request.KeepAlive = false;
request.Timeout = 5000;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// Checking the response from the 'status' end point. Note that we are simply checking
// that the HTTP status returned is a 200 status, and that the resposne has the correct
// Content-Type header. A more sophisticated check would parse the JSON response and
// validate its values. At the moment we do not do this more sophisticated check.
isInitialized = response.StatusCode == HttpStatusCode.OK && response.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase);
response.Close();
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}
return isInitialized;
}
}
/// <summary>
/// Releases all resources associated with this <see cref="DriverService"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Starts the DriverService.
/// </summary>
[SecurityPermission(SecurityAction.Demand)]
public void Start()
{
this.driverServiceProcess = new Process();
this.driverServiceProcess.StartInfo.FileName = Path.Combine(this.driverServicePath, this.driverServiceExecutableName);
this.driverServiceProcess.StartInfo.Arguments = this.CommandLineArguments;
this.driverServiceProcess.StartInfo.UseShellExecute = false;
this.driverServiceProcess.StartInfo.CreateNoWindow = this.hideCommandPromptWindow;
DriverProcessStartingEventArgs eventArgs = new DriverProcessStartingEventArgs(this.driverServiceProcess.StartInfo);
this.OnDriverProcessStarting(eventArgs);
this.driverServiceProcess.Start();
bool serviceAvailable = this.WaitForServiceInitialization();
DriverProcessStartedEventArgs processStartedEventArgs = new DriverProcessStartedEventArgs(this.driverServiceProcess);
this.OnDriverProcessStarted(processStartedEventArgs);
if (!serviceAvailable)
{
string msg = "Cannot start the driver service on " + this.ServiceUrl;
throw new WebDriverException(msg);
}
}
/// <summary>
/// Finds the specified driver service executable.
/// </summary>
/// <param name="executableName">The file name of the executable to find.</param>
/// <param name="downloadUrl">A URL at which the driver service executable may be downloaded.</param>
/// <returns>The directory containing the driver service executable.</returns>
/// <exception cref="DriverServiceNotFoundException">
/// If the specified driver service executable does not exist in the current directory or in a directory on the system path.
/// </exception>
protected static string FindDriverServiceExecutable(string executableName, Uri downloadUrl)
{
string serviceDirectory = FileUtilities.FindFile(executableName);
if (string.IsNullOrEmpty(serviceDirectory))
{
throw new DriverServiceNotFoundException(string.Format(CultureInfo.InvariantCulture, "The {0} file does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at {1}.", executableName, downloadUrl));
}
return serviceDirectory;
}
/// <summary>
/// Releases all resources associated with this <see cref="DriverService"/>.
/// </summary>
/// <param name="disposing"><see langword="true"/> if the Dispose method was explicitly called; otherwise, <see langword="false"/>.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
this.Stop();
}
this.isDisposed = true;
}
}
/// <summary>
/// Raises the <see cref="DriverProcessStarting"/> event.
/// </summary>
/// <param name="eventArgs">A <see cref="DriverProcessStartingEventArgs"/> that contains the event data.</param>
protected void OnDriverProcessStarting(DriverProcessStartingEventArgs eventArgs)
{
if (eventArgs == null)
{
throw new ArgumentNullException("eventArgs", "eventArgs must not be null");
}
if (this.DriverProcessStarting != null)
{
this.DriverProcessStarting(this, eventArgs);
}
}
/// <summary>
/// Raises the <see cref="DriverProcessStarted"/> event.
/// </summary>
/// <param name="eventArgs">A <see cref="DriverProcessStartedEventArgs"/> that contains the event data.</param>
protected void OnDriverProcessStarted(DriverProcessStartedEventArgs eventArgs)
{
if (eventArgs == null)
{
throw new ArgumentNullException("eventArgs", "eventArgs must not be null");
}
if (this.DriverProcessStarted != null)
{
this.DriverProcessStarted(this, eventArgs);
}
}
/// <summary>
/// Stops the DriverService.
/// </summary>
[SecurityPermission(SecurityAction.Demand)]
private void Stop()
{
if (this.IsRunning)
{
if (this.HasShutdown)
{
Uri shutdownUrl = new Uri(this.ServiceUrl, "/shutdown");
DateTime timeout = DateTime.Now.Add(this.TerminationTimeout);
while (this.IsRunning && DateTime.Now < timeout)
{
try
{
// Issue the shutdown HTTP request, then wait a short while for
// the process to have exited. If the process hasn't yet exited,
// we'll retry. We wait for exit here, since catching the exception
// for a failed HTTP request due to a closed socket is particularly
// expensive.
HttpWebRequest request = HttpWebRequest.Create(shutdownUrl) as HttpWebRequest;
request.KeepAlive = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
response.Close();
this.driverServiceProcess.WaitForExit(3000);
}
catch (WebException)
{
}
}
}
// If at this point, the process still hasn't exited, wait for one
// last-ditch time, then, if it still hasn't exited, kill it. Note
// that falling into this branch of code should be exceedingly rare.
if (this.IsRunning)
{
this.driverServiceProcess.WaitForExit(Convert.ToInt32(this.TerminationTimeout.TotalMilliseconds));
if (!this.driverServiceProcess.HasExited)
{
this.driverServiceProcess.Kill();
}
}
this.driverServiceProcess.Dispose();
this.driverServiceProcess = null;
}
}
/// <summary>
/// Waits until a the service is initialized, or the timeout set
/// by the <see cref="InitializationTimeout"/> property is reached.
/// </summary>
/// <returns><see langword="true"/> if the service is properly started and receiving HTTP requests;
/// otherwise; <see langword="false"/>.</returns>
private bool WaitForServiceInitialization()
{
bool isInitialized = false;
DateTime timeout = DateTime.Now.Add(this.InitializationTimeout);
while (!isInitialized && DateTime.Now < timeout)
{
// If the driver service process has exited, we can exit early.
if (!this.IsRunning)
{
break;
}
isInitialized = this.IsInitialized;
}
return isInitialized;
}
}
}
| |
//! \file ArcTAC.cs
//! \date Wed Jan 25 04:41:35 2017
//! \brief TanukiSoft resource archive.
//
// Copyright (C) 2017 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;
using GameRes.Compression;
using GameRes.Cryptography;
namespace GameRes.Formats.Tanuki
{
[Export(typeof(ArchiveFormat))]
public class TacOpener : ArchiveFormat
{
public override string Tag { get { return "TAC"; } }
public override string Description { get { return "TanukiSoft resource archive"; } }
public override uint Signature { get { return 0x63724154; } } // 'TArc'
public override bool IsHierarchic { get { return true; } }
public override bool CanWrite { get { return false; } }
public TacOpener ()
{
Extensions = new string[] { "tac", "stx" };
}
static readonly byte[] IndexKey = Encoding.ASCII.GetBytes ("TLibArchiveData");
static readonly string ListFileName = "tanuki.lst";
public override ArcFile TryOpen (ArcView file)
{
int version;
if (file.View.AsciiEqual (4, "1.00"))
version = 100;
else if (file.View.AsciiEqual (4, "1.10"))
version = 110;
else
return null;
int count = file.View.ReadInt32 (0x14);
if (!IsSaneCount (count))
return null;
int bucket_count = file.View.ReadInt32 (0x18);
uint index_size = file.View.ReadUInt32 (0x1C);
uint arc_seed = file.View.ReadUInt32 (0x20);
long index_offset = version >= 110 ? 0x2C : 0x24;
long base_offset = index_offset + index_size;
var blowfish = new Blowfish (IndexKey);
var packed_bytes = file.View.ReadBytes (index_offset, index_size);
blowfish.Decipher (packed_bytes, packed_bytes.Length & ~7);
using (var input = new MemoryStream (packed_bytes))
using (var unpacked = new ZLibStream (input, CompressionMode.Decompress))
using (var index = new BinaryReader (unpacked))
{
var file_map = BuildFileNameMap (arc_seed);
var dir_table = new List<TacBucket> (bucket_count);
for (int i = 0; i < bucket_count; ++i)
{
var entry = new TacBucket();
entry.Hash = index.ReadUInt16();
entry.Count = index.ReadUInt16();
entry.Index = index.ReadInt32();
dir_table.Add (entry);
}
var dir = new List<Entry> (count);
for (int i = 0; i < count; ++i)
{
var entry = new TacEntry();
entry.Hash = index.ReadUInt64();
entry.IsPacked = index.ReadInt32() != 0;
entry.UnpackedSize = index.ReadUInt32();
entry.Offset = base_offset + index.ReadUInt32();
entry.Size = index.ReadUInt32();
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
}
var buffer = new byte[8];
foreach (var bucket in dir_table)
{
for (int i = 0; i < bucket.Count; ++i)
{
var entry = dir[bucket.Index+i] as TacEntry;
entry.Hash = entry.Hash << 16 | bucket.Hash;
bool known_name = file_map.ContainsKey (entry.Hash);
if (known_name)
{
entry.Name = file_map[entry.Hash];
entry.Type = FormatCatalog.Instance.GetTypeFromName (entry.Name);
}
else
{
entry.Name = string.Format ("{0:X16}", entry.Hash);
}
if (entry.IsPacked)
continue;
entry.Key = Encoding.ASCII.GetBytes (string.Format ("{0}_tlib_secure_", entry.Hash));
if (!known_name)
{
var bf = new Blowfish (entry.Key);
file.View.Read (entry.Offset, buffer, 0, 8);
bf.Decipher (buffer, 8);
var res = AutoEntry.DetectFileType (buffer.ToUInt32 (0));
if (res != null)
entry.ChangeType (res);
}
if ("image" == entry.Type && !entry.Name.HasExtension (".af"))
entry.EncryptedSize = Math.Min (10240, entry.Size);
else
entry.EncryptedSize = entry.Size;
}
}
return new ArcFile (file, this, dir);
}
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var tent = entry as TacEntry;
if (null == tent)
return base.OpenEntry (arc, entry);
if (tent.IsPacked)
{
var input = arc.File.CreateStream (entry.Offset, entry.Size);
return new ZLibStream (input, CompressionMode.Decompress);
}
var bf = new Blowfish (tent.Key);
if (tent.EncryptedSize < tent.Size)
{
var header = arc.File.View.ReadBytes (tent.Offset, tent.EncryptedSize);
bf.Decipher (header, header.Length);
var rest = arc.File.CreateStream (tent.Offset+tent.EncryptedSize, tent.Size-tent.EncryptedSize);
return new PrefixStream (header, rest);
}
else if (0 == (tent.Size & 7))
{
var input = arc.File.CreateStream (tent.Offset, tent.Size);
return new InputCryptoStream (input, bf.CreateDecryptor());
}
else
{
var data = arc.File.View.ReadBytes (tent.Offset, tent.Size);
bf.Decipher (data, data.Length & ~7);
return new BinMemoryStream (data);
}
}
internal static ulong HashFromString (string s, uint seed)
{
s = s.Replace ('\\', '/').ToUpperInvariant();
var bytes = Encodings.cp932.GetBytes (s);
ulong hash = 0;
for (int i = 0; i < bytes.Length; ++i)
{
hash = bytes[i] + 0x19919 * hash + seed;
}
return hash;
}
internal static ulong HashFromAsciiString (string s, uint seed)
{
ulong hash = 0;
for (int i = 0; i < s.Length; ++i)
{
hash = (uint)char.ToUpperInvariant (s[i]) + 0x19919 * hash + seed;
}
return hash;
}
Dictionary<ulong, string> BuildFileNameMap (uint seed)
{
var map = new Dictionary<ulong, string> (KnownNames.Length);
foreach (var name in KnownNames)
{
map[HashFromAsciiString (name, seed)] = name;
}
return map;
}
internal string[] KnownNames { get { return s_known_file_names.Value; } }
static Lazy<string[]> s_known_file_names = new Lazy<string[]> (ReadTanukiLst);
static string[] ReadTanukiLst ()
{
try
{
var names = new List<string>();
FormatCatalog.Instance.ReadFileList (ListFileName, name => names.Add (name));
return names.ToArray();
}
catch (Exception X)
{
System.Diagnostics.Trace.WriteLine (X.Message, "[TAC]");
return new string[0];
}
}
}
internal class TacEntry : PackedEntry
{
public ulong Hash;
public byte[] Key;
public uint EncryptedSize;
}
internal class TacBucket
{
public ushort Hash;
public int Count;
public int Index;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.IO;
using ICSharpCode.WpfDesign.Designer;
using ICSharpCode.WpfDesign.Designer.Xaml;
using ICSharpCode.WpfDesign.Designer.OutlineView;
using System.Xml;
using ICSharpCode.WpfDesign;
using ICSharpCode.WpfDesign.Designer.Services;
using System.Diagnostics;
using ICSharpCode.WpfDesign.XamlDom;
namespace ICSharpCode.XamlDesigner
{
public class Document : INotifyPropertyChanged
{
public Document(string tempName, string text)
{
this.tempName = tempName;
Text = text;
IsDirty = false;
}
public Document(string filePath)
{
this.filePath = filePath;
ReloadFile();
}
string tempName;
DesignSurface designSurface = new DesignSurface();
string text;
public string Text {
get {
return text;
}
set {
if (text != value) {
text = value;
IsDirty = true;
RaisePropertyChanged("Text");
}
}
}
DocumentMode mode;
public DocumentMode Mode {
get {
return mode;
}
set {
mode = value;
if (InDesignMode) {
UpdateDesign();
}
else {
UpdateXaml();
if (this.DesignContext.Services.Selection.PrimarySelection != null)
{
var sel = this.DesignContext.Services.Selection.PrimarySelection;
var ln = ((PositionXmlElement) ((XamlDesignItem) sel).XamlObject.XmlElement).LineNumber;
Console.WriteLine(ln);
}
}
RaisePropertyChanged("Mode");
RaisePropertyChanged("InXamlMode");
RaisePropertyChanged("InDesignMode");
}
}
public bool InXamlMode {
get { return Mode == DocumentMode.Xaml; }
}
public bool InDesignMode {
get { return Mode == DocumentMode.Design; }
}
string filePath;
public string FilePath {
get {
return filePath;
}
private set {
filePath = value;
RaisePropertyChanged("FilePath");
RaisePropertyChanged("FileName");
RaisePropertyChanged("Title");
RaisePropertyChanged("Name");
}
}
bool isDirty;
public bool IsDirty {
get {
return isDirty;
}
private set {
isDirty = value;
RaisePropertyChanged("IsDirty");
RaisePropertyChanged("Name");
RaisePropertyChanged("Title");
}
}
public XamlElementLineInfo xamlElementLineInfo;
public XamlElementLineInfo XamlElementLineInfo
{
get
{
return xamlElementLineInfo;
}
private set
{
xamlElementLineInfo = value;
RaisePropertyChanged("XamlElementLineInfo");
}
}
public string FileName {
get {
if (FilePath == null) return null;
return Path.GetFileName(FilePath);
}
}
public string Name {
get {
return FileName ?? tempName;
}
}
public string Title {
get {
return IsDirty ? Name + "*" : Name;
}
}
public DesignSurface DesignSurface {
get { return designSurface; }
}
public DesignContext DesignContext {
get { return designSurface.DesignContext; }
}
public UndoService UndoService {
get { return DesignContext.Services.GetService<UndoService>(); }
}
public ISelectionService SelectionService {
get {
if (InDesignMode) {
return DesignContext.Services.Selection;
}
return null;
}
}
public XamlErrorService XamlErrorService {
get {
if (DesignContext != null) {
return DesignContext.Services.GetService<XamlErrorService>();
}
return null;
}
}
IOutlineNode outlineRoot;
public IOutlineNode OutlineRoot {
get {
return outlineRoot;
}
private set {
outlineRoot = value;
RaisePropertyChanged("OutlineRoot");
}
}
void ReloadFile()
{
Text = File.ReadAllText(FilePath);
UpdateDesign();
IsDirty = false;
}
public void Save()
{
if (InDesignMode) {
UpdateXaml();
}
File.WriteAllText(FilePath, Text);
IsDirty = false;
}
public void SaveAs(string filePath)
{
FilePath = filePath;
Save();
}
public void Refresh()
{
UpdateXaml();
UpdateDesign();
}
void UpdateXaml()
{
var sb = new StringBuilder();
using (var xmlWriter = new XamlXmlWriter(sb)) {
DesignSurface.SaveDesigner(xmlWriter);
Dictionary<XamlElementLineInfo, XamlElementLineInfo> d;
Text = XamlFormatter.Format(sb.ToString(), out d);
if (DesignSurface.DesignContext.Services.Selection.PrimarySelection != null)
{
var item = DesignSurface.DesignContext.Services.Selection.PrimarySelection;
var line = ((PositionXmlElement) ((XamlDesignItem) item).XamlObject.XmlElement).LineNumber;
var pos = (((XamlDesignItem)item).XamlObject.PositionXmlElement).LinePosition;
var newP = d.FirstOrDefault(x => x.Key.LineNumber == line && x.Key.LinePosition == pos);
XamlElementLineInfo = newP.Value;
}
}
}
void UpdateDesign()
{
OutlineRoot = null;
using (var xmlReader = XmlReader.Create(new StringReader(Text))) {
XamlLoadSettings settings = new XamlLoadSettings();
foreach (var assNode in Toolbox.Instance.AssemblyNodes)
{
settings.DesignerAssemblies.Add(assNode.Assembly);
}
settings.TypeFinder = MyTypeFinder.Instance;
DesignSurface.LoadDesigner(xmlReader, settings);
}
if (DesignContext.RootItem != null) {
OutlineRoot = OutlineNode.Create(DesignContext.RootItem);
UndoService.UndoStackChanged += new EventHandler(UndoService_UndoStackChanged);
}
RaisePropertyChanged("SelectionService");
RaisePropertyChanged("XamlErrorService");
}
void UndoService_UndoStackChanged(object sender, EventArgs e)
{
IsDirty = true;
if (InXamlMode) {
UpdateXaml();
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string name)
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
#endregion
}
public enum DocumentMode
{
Xaml, Design
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Collections;
using System.Linq;
using System.Globalization;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Text.RegularExpressions;
namespace Newtonsoft.Json.Utilities
{
internal static class ReflectionUtils
{
public static Type GetObjectType(object v)
{
return (v != null) ? v.GetType() : null;
}
public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat)
{
switch (assemblyFormat)
{
case FormatterAssemblyStyle.Simple:
return GetSimpleTypeName(t);
case FormatterAssemblyStyle.Full:
return t.AssemblyQualifiedName;
default:
throw new ArgumentOutOfRangeException();
}
}
private static string GetSimpleTypeName(Type type)
{
#if !SILVERLIGHT
string fullyQualifiedTypeName = type.FullName + ", " + type.Assembly.GetName().Name;
// for type names with no nested type names then return
if (!type.IsGenericType || type.IsGenericTypeDefinition)
return fullyQualifiedTypeName;
#else
// Assembly.GetName() is marked SecurityCritical
string fullyQualifiedTypeName = type.AssemblyQualifiedName;
#endif
StringBuilder builder = new StringBuilder();
// loop through the type name and filter out qualified assembly details from nested type names
bool writingAssemblyName = false;
bool skippingAssemblyDetails = false;
for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
{
char current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(current);
break;
case ']':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(current);
break;
case ',':
if (!writingAssemblyName)
{
writingAssemblyName = true;
builder.Append(current);
}
else
{
skippingAssemblyDetails = true;
}
break;
default:
if (!skippingAssemblyDetails)
builder.Append(current);
break;
}
}
return builder.ToString();
}
public static bool IsInstantiatableType(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
if (t.IsAbstract || t.IsInterface || t.IsArray || t.IsGenericTypeDefinition || t == typeof(void))
return false;
if (!HasDefaultConstructor(t))
return false;
return true;
}
public static bool HasDefaultConstructor(Type t)
{
return HasDefaultConstructor(t, false);
}
public static bool HasDefaultConstructor(Type t, bool nonPublic)
{
ValidationUtils.ArgumentNotNull(t, "t");
if (t.IsValueType)
return true;
return (GetDefaultConstructor(t, nonPublic) != null);
}
public static ConstructorInfo GetDefaultConstructor(Type t)
{
return GetDefaultConstructor(t, false);
}
public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic)
{
BindingFlags accessModifier = BindingFlags.Public;
if (nonPublic)
accessModifier = accessModifier | BindingFlags.NonPublic;
return t.GetConstructor(accessModifier | BindingFlags.Instance, null, new Type[0], null);
}
public static bool IsNullable(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
if (t.IsValueType)
return IsNullableType(t);
return true;
}
public static bool IsNullableType(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
public static Type EnsureNotNullableType(Type t)
{
return (IsNullableType(t))
? Nullable.GetUnderlyingType(t)
: t;
}
//public static bool IsValueTypeUnitializedValue(ValueType value)
//{
// if (value == null)
// return true;
// return value.Equals(CreateUnitializedValue(value.GetType()));
//}
public static bool IsUnitializedValue(object value)
{
if (value == null)
{
return true;
}
else
{
object unitializedValue = CreateUnitializedValue(value.GetType());
return value.Equals(unitializedValue);
}
}
public static object CreateUnitializedValue(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
if (type.IsGenericTypeDefinition)
throw new ArgumentException("Type {0} is a generic type definition and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type");
if (type.IsClass || type.IsInterface || type == typeof(void))
return null;
else if (type.IsValueType)
return Activator.CreateInstance(type);
else
throw new ArgumentException("Type {0} cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type");
}
public static bool IsPropertyIndexed(PropertyInfo property)
{
ValidationUtils.ArgumentNotNull(property, "property");
return !CollectionUtils.IsNullOrEmpty<ParameterInfo>(property.GetIndexParameters());
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition)
{
Type implementingType;
return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType);
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition");
if (!genericInterfaceDefinition.IsInterface || !genericInterfaceDefinition.IsGenericTypeDefinition)
throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition));
if (type.IsInterface)
{
if (type.IsGenericType)
{
Type interfaceDefinition = type.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = type;
return true;
}
}
}
foreach (Type i in type.GetInterfaces())
{
if (i.IsGenericType)
{
Type interfaceDefinition = i.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = i;
return true;
}
}
}
implementingType = null;
return false;
}
public static bool AssignableToTypeName(this Type type, string fullTypeName, out Type match)
{
Type current = type;
while (current != null)
{
if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal))
{
match = current;
return true;
}
current = current.BaseType;
}
foreach (Type i in type.GetInterfaces())
{
if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal))
{
match = type;
return true;
}
}
match = null;
return false;
}
public static bool AssignableToTypeName(this Type type, string fullTypeName)
{
Type match;
return type.AssignableToTypeName(fullTypeName, out match);
}
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition)
{
Type implementingType;
return InheritsGenericDefinition(type, genericClassDefinition, out implementingType);
}
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition");
if (!genericClassDefinition.IsClass || !genericClassDefinition.IsGenericTypeDefinition)
throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition));
return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType);
}
private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType)
{
if (currentType.IsGenericType)
{
Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition();
if (genericClassDefinition == currentGenericClassDefinition)
{
implementingType = currentType;
return true;
}
}
if (currentType.BaseType == null)
{
implementingType = null;
return false;
}
return InheritsGenericDefinitionInternal(currentType.BaseType, genericClassDefinition, out implementingType);
}
/// <summary>
/// Gets the type of the typed collection's items.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The type of the typed collection's items.</returns>
public static Type GetCollectionItemType(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
Type genericListType;
if (type.IsArray)
{
return type.GetElementType();
}
else if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType))
{
if (genericListType.IsGenericTypeDefinition)
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
return genericListType.GetGenericArguments()[0];
}
else if (typeof(IEnumerable).IsAssignableFrom(type))
{
return null;
}
else
{
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
}
}
public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType)
{
ValidationUtils.ArgumentNotNull(dictionaryType, "type");
Type genericDictionaryType;
if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType))
{
if (genericDictionaryType.IsGenericTypeDefinition)
throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments();
keyType = dictionaryGenericArguments[0];
valueType = dictionaryGenericArguments[1];
return;
}
else if (typeof(IDictionary).IsAssignableFrom(dictionaryType))
{
keyType = null;
valueType = null;
return;
}
else
{
throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
}
}
public static Type GetDictionaryValueType(Type dictionaryType)
{
Type keyType;
Type valueType;
GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType);
return valueType;
}
public static Type GetDictionaryKeyType(Type dictionaryType)
{
Type keyType;
Type valueType;
GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType);
return keyType;
}
/// <summary>
/// Tests whether the list's items are their unitialized value.
/// </summary>
/// <param name="list">The list.</param>
/// <returns>Whether the list's items are their unitialized value</returns>
public static bool ItemsUnitializedValue<T>(IList<T> list)
{
ValidationUtils.ArgumentNotNull(list, "list");
Type elementType = GetCollectionItemType(list.GetType());
if (elementType.IsValueType)
{
object unitializedValue = CreateUnitializedValue(elementType);
for (int i = 0; i < list.Count; i++)
{
if (!list[i].Equals(unitializedValue))
return false;
}
}
else if (elementType.IsClass)
{
for (int i = 0; i < list.Count; i++)
{
object value = list[i];
if (value != null)
return false;
}
}
else
{
throw new Exception("Type {0} is neither a ValueType or a Class.".FormatWith(CultureInfo.InvariantCulture, elementType));
}
return true;
}
/// <summary>
/// Gets the member's underlying type.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>The underlying type of the member.</returns>
public static Type GetMemberUnderlyingType(MemberInfo member)
{
ValidationUtils.ArgumentNotNull(member, "member");
switch (member.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo)member).FieldType;
case MemberTypes.Property:
return ((PropertyInfo)member).PropertyType;
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
default:
throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo or EventInfo", "member");
}
}
/// <summary>
/// Determines whether the member is an indexed property.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>
/// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(MemberInfo member)
{
ValidationUtils.ArgumentNotNull(member, "member");
PropertyInfo propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
return IsIndexedProperty(propertyInfo);
else
return false;
}
/// <summary>
/// Determines whether the property is an indexed property.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>
/// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(PropertyInfo property)
{
ValidationUtils.ArgumentNotNull(property, "property");
return (property.GetIndexParameters().Length > 0);
}
/// <summary>
/// Gets the member's value on the object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target object.</param>
/// <returns>The member's value on the object.</returns>
public static object GetMemberValue(MemberInfo member, object target)
{
ValidationUtils.ArgumentNotNull(member, "member");
ValidationUtils.ArgumentNotNull(target, "target");
switch (member.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo)member).GetValue(target);
case MemberTypes.Property:
try
{
return ((PropertyInfo)member).GetValue(target, null);
}
catch (TargetParameterCountException e)
{
throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e);
}
default:
throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), "member");
}
}
/// <summary>
/// Sets the member's value on the target object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target.</param>
/// <param name="value">The value.</param>
public static void SetMemberValue(MemberInfo member, object target, object value)
{
ValidationUtils.ArgumentNotNull(member, "member");
ValidationUtils.ArgumentNotNull(target, "target");
switch (member.MemberType)
{
case MemberTypes.Field:
((FieldInfo)member).SetValue(target, value);
break;
case MemberTypes.Property:
((PropertyInfo)member).SetValue(target, value, null);
break;
default:
throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), "member");
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be read.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be read.</param>
/// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>.
/// </returns>
public static bool CanReadMemberValue(MemberInfo member, bool nonPublic)
{
switch (member.MemberType)
{
case MemberTypes.Field:
FieldInfo fieldInfo = (FieldInfo)member;
if (nonPublic)
return true;
else if (fieldInfo.IsPublic)
return true;
return false;
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo) member;
if (!propertyInfo.CanRead)
return false;
if (nonPublic)
return true;
return (propertyInfo.GetGetMethod(nonPublic) != null);
default:
return false;
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be set.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be set.</param>
/// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>.
/// </returns>
public static bool CanSetMemberValue(MemberInfo member, bool nonPublic)
{
switch (member.MemberType)
{
case MemberTypes.Field:
FieldInfo fieldInfo = (FieldInfo)member;
if (fieldInfo.IsInitOnly)
return false;
if (nonPublic)
return true;
else if (fieldInfo.IsPublic)
return true;
return false;
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo)member;
if (!propertyInfo.CanWrite)
return false;
if (nonPublic)
return true;
return (propertyInfo.GetSetMethod(nonPublic) != null);
default:
return false;
}
}
public static List<MemberInfo> GetFieldsAndProperties<T>(BindingFlags bindingAttr)
{
return GetFieldsAndProperties(typeof(T), bindingAttr);
}
public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr)
{
List<MemberInfo> targetMembers = new List<MemberInfo>();
targetMembers.AddRange(GetFields(type, bindingAttr));
targetMembers.AddRange(GetProperties(type, bindingAttr));
// for some reason .NET returns multiple members when overriding a generic member on a base class
// http://forums.msdn.microsoft.com/en-US/netfxbcl/thread/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/
// filter members to only return the override on the topmost class
// update: I think this is fixed in .NET 3.5 SP1 - leave this in for now...
List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count);
var groupedMembers = targetMembers.GroupBy(m => m.Name).Select(g => new { Count = g.Count(), Members = g.Cast<MemberInfo>() });
foreach (var groupedMember in groupedMembers)
{
if (groupedMember.Count == 1)
{
distinctMembers.Add(groupedMember.Members.First());
}
else
{
var members = groupedMember.Members.Where(m => !IsOverridenGenericMember(m, bindingAttr) || m.Name == "Item");
distinctMembers.AddRange(members);
}
}
return distinctMembers;
}
private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr)
{
if (memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property)
throw new ArgumentException("Member must be a field or property.");
Type declaringType = memberInfo.DeclaringType;
if (!declaringType.IsGenericType)
return false;
Type genericTypeDefinition = declaringType.GetGenericTypeDefinition();
if (genericTypeDefinition == null)
return false;
MemberInfo[] members = genericTypeDefinition.GetMember(memberInfo.Name, bindingAttr);
if (members.Length == 0)
return false;
Type memberUnderlyingType = GetMemberUnderlyingType(members[0]);
if (!memberUnderlyingType.IsGenericParameter)
return false;
return true;
}
public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute
{
return GetAttribute<T>(attributeProvider, true);
}
public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute
{
T[] attributes = GetAttributes<T>(attributeProvider, inherit);
return CollectionUtils.GetSingleItem(attributes, true);
}
public static T[] GetAttributes<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute
{
ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider");
// http://hyperthink.net/blog/getcustomattributes-gotcha/
// ICustomAttributeProvider doesn't do inheritance
if (attributeProvider is Assembly)
return (T[])Attribute.GetCustomAttributes((Assembly)attributeProvider, typeof(T), inherit);
if (attributeProvider is MemberInfo)
return (T[])Attribute.GetCustomAttributes((MemberInfo)attributeProvider, typeof(T), inherit);
if (attributeProvider is Module)
return (T[])Attribute.GetCustomAttributes((Module)attributeProvider, typeof(T), inherit);
if (attributeProvider is ParameterInfo)
return (T[])Attribute.GetCustomAttributes((ParameterInfo)attributeProvider, typeof(T), inherit);
return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit);
}
public static string GetNameAndAssessmblyName(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
return t.FullName + ", " + t.Assembly.GetName().Name;
}
public static Type MakeGenericType(Type genericTypeDefinition, params Type[] innerTypes)
{
ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition");
ValidationUtils.ArgumentNotNullOrEmpty<Type>(innerTypes, "innerTypes");
ValidationUtils.ArgumentConditionTrue(genericTypeDefinition.IsGenericTypeDefinition, "genericTypeDefinition", "Type {0} is not a generic type definition.".FormatWith(CultureInfo.InvariantCulture, genericTypeDefinition));
return genericTypeDefinition.MakeGenericType(innerTypes);
}
public static object CreateGeneric(Type genericTypeDefinition, Type innerType, params object[] args)
{
return CreateGeneric(genericTypeDefinition, new [] { innerType }, args);
}
public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, params object[] args)
{
return CreateGeneric(genericTypeDefinition, innerTypes, (t, a) => CreateInstance(t, a.ToArray()), args);
}
public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, Func<Type, IList<object>, object> instanceCreator, params object[] args)
{
ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition");
ValidationUtils.ArgumentNotNullOrEmpty(innerTypes, "innerTypes");
ValidationUtils.ArgumentNotNull(instanceCreator, "createInstance");
Type specificType = MakeGenericType(genericTypeDefinition, innerTypes.ToArray());
return instanceCreator(specificType, args);
}
public static bool IsCompatibleValue(object value, Type type)
{
if (value == null)
return IsNullable(type);
if (type.IsAssignableFrom(value.GetType()))
return true;
return false;
}
public static object CreateInstance(Type type, params object[] args)
{
ValidationUtils.ArgumentNotNull(type, "type");
#if !PocketPC
return Activator.CreateInstance(type, args);
#else
// CF doesn't have a Activator.CreateInstance overload that takes args
// lame
if (type.IsValueType && CollectionUtils.IsNullOrEmpty<object>(args))
return Activator.CreateInstance(type);
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfo match = constructors.Where(c =>
{
ParameterInfo[] parameters = c.GetParameters();
if (parameters.Length != args.Length)
return false;
for (int i = 0; i < parameters.Length; i++)
{
ParameterInfo parameter = parameters[i];
object value = args[i];
if (!IsCompatibleValue(value, parameter.ParameterType))
return false;
}
return true;
}).FirstOrDefault();
if (match == null)
throw new Exception("Could not create '{0}' with given parameters.".FormatWith(CultureInfo.InvariantCulture, type));
return match.Invoke(args);
#endif
}
public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName)
{
int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName);
if (assemblyDelimiterIndex != null)
{
typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.Value).Trim();
assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.Value + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.Value - 1).Trim();
}
else
{
typeName = fullyQualifiedTypeName;
assemblyName = null;
}
}
private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName)
{
// we need to get the first comma following all surrounded in brackets because of generic types
// e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
int scope = 0;
for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
{
char current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
scope++;
break;
case ']':
scope--;
break;
case ',':
if (scope == 0)
return i;
break;
}
}
return null;
}
public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr)
{
ValidationUtils.ArgumentNotNull(targetType, "targetType");
List<MemberInfo> fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr));
// Type.GetFields doesn't return inherited private fields
// manually find private fields from base class
GetChildPrivateFields(fieldInfos, targetType, bindingAttr);
return fieldInfos.Cast<FieldInfo>();
}
private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr)
{
// fix weirdness with private FieldInfos only being returned for the current Type
// find base type fields and add them to result
if ((bindingAttr & BindingFlags.NonPublic) != 0)
{
// modify flags to not search for public fields
BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public);
while ((targetType = targetType.BaseType) != null)
{
// filter out protected fields
IEnumerable<MemberInfo> childPrivateFields =
targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>();
initialFields.AddRange(childPrivateFields);
}
}
}
public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr)
{
ValidationUtils.ArgumentNotNull(targetType, "targetType");
List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr));
GetChildPrivateProperties(propertyInfos, targetType, bindingAttr);
// a base class private getter/setter will be inaccessable unless the property was gotten from the base class
for (int i = 0; i < propertyInfos.Count; i++)
{
PropertyInfo member = propertyInfos[i];
if (member.DeclaringType != targetType)
{
PropertyInfo declaredMember = member.DeclaringType.GetProperty(member.Name, bindingAttr);
propertyInfos[i] = declaredMember;
}
}
return propertyInfos;
}
public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag)
{
return ((bindingAttr & flag) == flag)
? bindingAttr ^ flag
: bindingAttr;
}
private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr)
{
// fix weirdness with private PropertyInfos only being returned for the current Type
// find base type properties and add them to result
if ((bindingAttr & BindingFlags.NonPublic) != 0)
{
// modify flags to not search for public fields
BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public);
while ((targetType = targetType.BaseType) != null)
{
foreach (PropertyInfo propertyInfo in targetType.GetProperties(nonPublicBindingAttr))
{
PropertyInfo nonPublicProperty = propertyInfo;
// have to test on name rather than reference because instances are different
// depending on the type that GetProperties was called on
int index = initialProperties.IndexOf(p => p.Name == nonPublicProperty.Name);
if (index == -1)
{
initialProperties.Add(nonPublicProperty);
}
else
{
// replace nonpublic properties for a child, but gotten from
// the parent with the one from the child
// the property gotten from the child will have access to private getter/setter
initialProperties[index] = nonPublicProperty;
}
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using OLEDB.Test.ModuleCore;
using System.Collections.Generic;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
/////////////////////////////////////////////////////////////////////////
// TestCase ReadOuterXml
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCReadSubtree : TCXMLReaderBaseGeneral
{
[Variation("ReadSubtree only works on Element Node")]
public int ReadSubtreeWorksOnlyOnElementNode()
{
ReloadSource();
while (DataReader.Read())
{
if (DataReader.NodeType != XmlNodeType.Element)
{
string nodeType = DataReader.NodeType.ToString();
bool flag = true;
try
{
DataReader.ReadSubtree();
}
catch (InvalidOperationException)
{
flag = false;
}
if (flag)
{
CError.WriteLine("ReadSubtree doesnt throw InvalidOp Exception on NodeType : " + nodeType);
return TEST_FAIL;
}
//now try next read
try
{
DataReader.Read();
}
catch (XmlException)
{
CError.WriteLine("Cannot Read after an invalid operation exception");
return TEST_FAIL;
}
}
else
{
if (DataReader.HasAttributes)
{
bool flag = true;
DataReader.MoveToFirstAttribute();
try
{
DataReader.ReadSubtree();
}
catch (InvalidOperationException)
{
flag = false;
}
if (flag)
{
CError.WriteLine("ReadSubtree doesnt throw InvalidOp Exception on Attribute Node Type");
return TEST_FAIL;
}
//now try next read.
try
{
DataReader.Read();
}
catch (XmlException)
{
CError.WriteLine("Cannot Read after an invalid operation exception");
return TEST_FAIL;
}
}
}
}//end while
return TEST_PASS;
}
private string _xml = "<root><elem1><elempi/><?pi target?><elem2 xmlns='xyz'><elem/><!--Comment--><x:elem3 xmlns:x='pqr'><elem4 attr4='4'/></x:elem3></elem2></elem1><elem5/><elem6/></root>";
//[Variation("ReadSubtree Test on Root", Pri = 0, Params = new object[]{"root", "", "ELEMENT", "", "", "NONE" })]
//[Variation("ReadSubtree Test depth=1", Pri = 0, Params = new object[] { "elem1", "", "ELEMENT", "elem5", "", "ELEMENT" })]
//[Variation("ReadSubtree Test depth=2", Pri = 0, Params = new object[] { "elem2", "", "ELEMENT", "elem1", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test depth=3", Pri = 0, Params = new object[] { "x:elem3", "", "ELEMENT", "elem2", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test depth=4", Pri = 0, Params = new object[] { "elem4", "", "ELEMENT", "x:elem3", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test empty element", Pri = 0, Params = new object[] { "elem5", "", "ELEMENT", "elem6", "", "ELEMENT" })]
//[Variation("ReadSubtree Test empty element before root", Pri = 0, Params = new object[] { "elem6", "", "ELEMENT", "root", "", "ENDELEMENT" })]
//[Variation("ReadSubtree Test PI after element", Pri = 0, Params = new object[] { "elempi", "", "ELEMENT", "pi", "target", "PROCESSINGINSTRUCTION" })]
//[Variation("ReadSubtree Test Comment after element", Pri = 0, Params = new object[] { "elem", "", "ELEMENT", "", "Comment", "COMMENT" })]
public int v2()
{
int count = 0;
string name = CurVariation.Params[count++].ToString();
string value = CurVariation.Params[count++].ToString();
string type = CurVariation.Params[count++].ToString();
string oname = CurVariation.Params[count++].ToString();
string ovalue = CurVariation.Params[count++].ToString();
string otype = CurVariation.Params[count++].ToString();
ReloadSource(new StringReader(_xml));
DataReader.PositionOnElement(name);
XmlReader r = DataReader.ReadSubtree();
CError.Compare(r.ReadState, ReadState.Initial, "Reader state is not Initial");
CError.Compare(r.Name, String.Empty, "Name is not empty");
CError.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty");
CError.Compare(r.Depth, 0, "Depth is not zero");
r.Read();
CError.Compare(r.ReadState, ReadState.Interactive, "Reader state is not Interactive");
CError.Compare(r.Name, name, "Subreader name doesnt match");
CError.Compare(r.Value, value, "Subreader value doesnt match");
CError.Compare(r.NodeType.ToString().ToUpperInvariant(), type, "Subreader nodetype doesnt match");
CError.Compare(r.Depth, 0, "Subreader Depth is not zero");
while (r.Read()) ;
r.Dispose();
CError.Compare(r.ReadState, ReadState.Closed, "Reader state is not Initial");
CError.Compare(r.Name, String.Empty, "Name is not empty");
CError.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty");
DataReader.Read();
CError.Compare(DataReader.Name, oname, "Main name doesnt match");
CError.Compare(DataReader.Value, ovalue, "Main value doesnt match");
CError.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), otype, "Main nodetype doesnt match");
DataReader.Close();
return TEST_PASS;
}
[Variation("Read with entities", Pri = 1)]
public int v3()
{
ReloadSource();
DataReader.PositionOnElement("PLAY");
XmlReader r = DataReader.ReadSubtree();
while (r.Read())
{
if (r.NodeType == XmlNodeType.EntityReference)
{
if (r.CanResolveEntity)
r.ResolveEntity();
}
}
DataReader.Close();
return TEST_PASS;
}
[Variation("Inner XML on Subtree reader", Pri = 1)]
public int v4()
{
string xmlStr = "<elem1><elem2/></elem1>";
ReloadSource(new StringReader(xmlStr));
DataReader.PositionOnElement("elem1");
XmlReader r = DataReader.ReadSubtree();
r.Read();
CError.Compare(r.ReadInnerXml(), "<elem2 />", "Inner Xml Fails");
CError.Compare(r.Read(), false, "Read returns false");
DataReader.Close();
return TEST_PASS;
}
[Variation("Outer XML on Subtree reader", Pri = 1)]
public int v5()
{
string xmlStr = "<elem1><elem2/></elem1>";
ReloadSource(new StringReader(xmlStr));
DataReader.PositionOnElement("elem1");
XmlReader r = DataReader.ReadSubtree();
r.Read();
CError.Compare(r.ReadOuterXml(), "<elem1><elem2 /></elem1>", "Outer Xml Fails");
CError.Compare(r.Read(), false, "Read returns true");
DataReader.Close();
return TEST_PASS;
}
//[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "true" })]
//[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "false" })]
public int v7()
{
if (!(IsFactoryTextReader() || IsBinaryReader() || IsFactoryValidatingReader()))
{
return TEST_SKIPPED;
}
string fileName = GetTestFileName(EREADER_TYPE.GENERIC);
bool ci = Boolean.Parse(CurVariation.Params[0].ToString());
XmlReaderSettings settings = new XmlReaderSettings();
settings.CloseInput = ci;
CError.WriteLine(ci);
MyDict<string, object> options = new MyDict<string, object>();
options.Add(ReaderFactory.HT_FILENAME, fileName);
options.Add(ReaderFactory.HT_READERSETTINGS, settings);
ReloadSource(options);
DataReader.PositionOnElement("elem2");
XmlReader r = DataReader.ReadSubtree();
CError.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState not interactive");
DataReader.Close();
return TEST_PASS;
}
private XmlReader NestRead(XmlReader r)
{
r.Read();
r.Read();
if (!(r.Name == "elem0" && r.NodeType == XmlNodeType.Element))
{
CError.WriteLine(r.Name);
NestRead(r.ReadSubtree());
}
r.Dispose();
return r;
}
[Variation("Nested Subtree reader calls", Pri = 2)]
public int v8()
{
string xmlStr = "<elem1><elem2><elem3><elem4><elem5><elem6><elem7><elem8><elem9><elem0></elem0></elem9></elem8></elem7></elem6></elem5></elem4></elem3></elem2></elem1>";
ReloadSource(new StringReader(xmlStr));
XmlReader r = DataReader.Internal;
NestRead(r);
CError.Compare(r.ReadState, ReadState.Closed, "Reader Read State is not closed");
return TEST_PASS;
}
[Variation("ReadSubtree for element depth more than 4K chars", Pri = 2)]
public int v100()
{
ManagedNodeWriter mnw = new ManagedNodeWriter();
mnw.PutPattern("X");
do
{
mnw.OpenElement();
mnw.CloseElement();
}
while (mnw.GetNodes().Length < 4096);
mnw.Finish();
ReloadSource(new StringReader(mnw.GetNodes()));
DataReader.PositionOnElement("ELEMENT_2");
XmlReader r = DataReader.ReadSubtree();
while (r.Read()) ;
DataReader.Read();
CError.Compare(DataReader.Name, "ELEMENT_1", "Main name doesnt match");
CError.Compare(DataReader.Value, "", "Main value doesnt match");
CError.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), "ENDELEMENT", "Main nodetype doesnt match");
DataReader.Close();
return TEST_PASS;
}
[Variation("Multiple Namespaces on Subtree reader", Pri = 1)]
public int SubtreeReaderCanDealWithMultipleNamespaces()
{
string xmlStr = "<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a=''></e></root>";
ReloadSource(new StringReader(xmlStr));
DataReader.PositionOnElement("e");
XmlReader r = DataReader.ReadSubtree();
while (r.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Subtree Reader caches the NodeType and reports node type of Attribute on subsequent reads.", Pri = 1)]
public int SubtreeReaderReadsProperlyNodeTypeOfAttributes()
{
string xmlStr = "<root xmlns='foo'><b blah='blah'/><b/></root>";
ReloadSource(new StringReader(xmlStr));
DataReader.PositionOnElement("root");
XmlReader xxr = DataReader.ReadSubtree();
xxr.Read(); //Now on root.
CError.Compare(xxr.Name, "root", "Root Elem");
CError.Compare(xxr.MoveToNextAttribute(), true, "MTNA 1");
CError.Compare(xxr.NodeType, XmlNodeType.Attribute, "XMLNS NT");
CError.Compare(xxr.Name, "xmlns", "XMLNS Attr");
CError.Compare(xxr.Value, "foo", "XMLNS Value");
CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 2");
xxr.Read(); //Now on b.
CError.Compare(xxr.Name, "b", "b Elem");
CError.Compare(xxr.MoveToNextAttribute(), true, "MTNA 3");
CError.Compare(xxr.NodeType, XmlNodeType.Attribute, "blah NT");
CError.Compare(xxr.Name, "blah", "blah Attr");
CError.Compare(xxr.Value, "blah", "blah Value");
CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 4");
xxr.Read(); //Now on /b.
CError.Compare(xxr.Name, "b", "b EndElem");
CError.Compare(xxr.NodeType, XmlNodeType.Element, "b Elem NT");
CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 5");
xxr.Read(); //Now on /root.
CError.Compare(xxr.Name, "root", "root EndElem");
CError.Compare(xxr.NodeType, XmlNodeType.EndElement, "root EndElem NT");
CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 6");
DataReader.Close();
return TEST_PASS;
}
[Variation("XmlSubtreeReader add duplicate namespace declaration")]
public int XmlSubtreeReaderDoesntDuplicateLocalNames()
{
Dictionary<string, object> localNames = new Dictionary<string, object>();
string xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<IXmlSerializable z:CLRType='A' z:ClrAssembly='test, " +
"Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' " +
"xmlns='http://schemas.datacontract.org' xmlns:z='http://schemas.microsoft.com' >" +
"<WriteAttributeString p3:attributeName3='attributeValue3' " +
"abc:attributeName='attributeValue' attributeName2='attributeValue2' " +
"xmlns:abc='myNameSpace' xmlns:p3='myNameSpace3' /></IXmlSerializable>";
ReloadSourceStr(xml);
DataReader.MoveToContent();
XmlReader reader = DataReader.ReadSubtree();
reader.ReadToDescendant("WriteAttributeString");
while (reader.MoveToNextAttribute())
{
if (localNames.ContainsKey(reader.LocalName))
{
CError.WriteLine("Duplicated LocalName: {0}", reader.LocalName);
return TEST_FAIL;
}
localNames.Add(reader.LocalName, null);
}
return TEST_PASS;
}
[Variation("XmlSubtreeReader adds duplicate namespace declaration")]
public int XmlSubtreeReaderDoesntAddMultipleNamespaceDeclarations()
{
ReloadSource(new StringReader("<r xmlns:a='X'><a:e/></r>"));
DataReader.Read();
DataReader.Read();
if (IsBinaryReader())
DataReader.Read();
XmlReader r1 = DataReader.ReadSubtree();
r1.Read();
XmlReader r2 = r1.ReadSubtree();
r2.Read();
string xml = r2.ReadOuterXml();
CError.Compare(xml, "<a:e xmlns:a=\"X\" />", "Mismatch");
return TEST_PASS;
}
[Variation("XmlSubtreeReader.Dispose disposes the main reader")]
public int XmlReaderDisposeDoesntDisposeMainReader()
{
ReloadSource(new StringReader("<a><b></b></a>"));
DataReader.PositionOnElement("b");
using (XmlReader subtreeReader = DataReader.ReadSubtree()) { }
if (DataReader.NodeType.ToString() == "EndElement" && DataReader.Name.ToString() == "b" && DataReader.Read() == true)
return TEST_PASS;
return TEST_FAIL;
}
private string[] _s = new string[] {
"<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a=''></e></root>",
"<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a='' xmlns:p2='b' ></e></root>",
"<root xmlns:p1='a' xmlns:p2='b'><e xmlns:p2='b' p1:a='' p2:a='' ></e></root>",
"<root xmlns:p1='a' ><e p1:a='' p2:a='' xmlns:p2='b' ></e></root>",
"<root xmlns:p2='b'><e xmlns:p1='a' p1:a='' p2:a=''></e></root>",
"<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a='' xmlns:p1='a' xmlns:p2='b'></e></root>"
};
private string[][] _exp = {
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
new string[] {"p1:a", "p2:a", "xmlns:p2", "xmlns:p1"},
new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1" },
new string[] {"p1:a", "p2:a", "xmlns:p2", "xmlns:p1"},
new string[] {"xmlns:p1", "p1:a", "p2:a", "xmlns:p2"},
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
};
private string[][] _expXpath = {
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1"},
new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1" },
new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1"},
new string[] {"xmlns:p1", "p1:a", "p2:a", "xmlns:p2"},
new string[] {"xmlns:p1", "xmlns:p2", "p1:a", "p2:a"},
};
private string[][] _expXslt = {
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2" },
new string[] {"p1:a", "p2:a", "xmlns:p2", "xmlns:p1"},
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"},
};
//[Variation("0. XmlReader.Name inconsistent when reading namespace node attribute", Param = 0)]
//[Variation("1. XmlReader.Name inconsistent when reading namespace node attribute", Param = 1)]
//[Variation("2. XmlReader.Name inconsistent when reading namespace node attribute", Param = 2)]
//[Variation("3. XmlReader.Name inconsistent when reading namespace node attribute", Param = 3)]
//[Variation("4. XmlReader.Name inconsistent when reading namespace node attribute", Param = 4)]
//[Variation("5. XmlReader.Name inconsistent when reading namespace node attribute", Param = 5)]
public int XmlReaderNameIsConsistentWhenReadingNamespaceNodeAttribute()
{
int param = (int)CurVariation.Param;
ReloadSource(new StringReader(_s[param]));
DataReader.PositionOnElement("e");
using (XmlReader r = DataReader.ReadSubtree())
{
while (r.Read())
{
for (int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
if (IsXPathNavigatorReader())
CError.Compare(r.Name, _expXpath[param][i], "Error");
else if (IsXsltReader())
CError.Compare(r.Name, _expXslt[param][i], "Error");
else
CError.Compare(r.Name, _exp[param][i], "Error");
}
}
}
return TEST_PASS;
}
[Variation("Indexing methods cause infinite recursion & stack overflow")]
public int IndexingMethodsWorksProperly()
{
string xml = "<e1 a='a1' b='b1'> 123 <e2 a='a2' b='b2'> abc</e2><e3 b='b3'/></e1>";
ReloadSourceStr(xml);
DataReader.Read();
XmlReader r2 = DataReader.ReadSubtree();
r2.Read();
CError.Compare(r2[0], "a1", "Error 1");
CError.Compare(r2["b"], "b1", "Error 2");
CError.Compare(r2["a", null], "a1", "Error 3");
return TEST_PASS;
}
//[Variation("1. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 1)]
//[Variation("2. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 2)]
//[Variation("3. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 3)]
//[Variation("4. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 4)]
//[Variation("5. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 5)]
//[Variation("6. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 6)]
//[Variation("7. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 7)]
//[Variation("8. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 8)]
//[Variation("9. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 9)]
//[Variation("10. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 10)]
//[Variation("11. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 11)]
//[Variation("12. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 12)]
//[Variation("13. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 13)]
//[Variation("14. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 14)]
//[Variation("15. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 15)]
//[Variation("16. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 16)]
//[Variation("17. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 17)]
//[Variation("18. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 18)]
//[Variation("19. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 19)]
//[Variation("20. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 20)]
//[Variation("21. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 21)]
//[Variation("22. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 22)]
//[Variation("23. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 23)]
//[Variation("24. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 24)]
public int DisposingSubtreeReaderThatIsInErrorStateWorksProperly()
{
int param = (int)CurVariation.Param;
byte[] b = new byte[4];
string xml = "<Report><Account><Balance>-4,095,783.00" +
"</Balance><LastActivity>2006/01/05</LastActivity>" +
"</Account></Report>";
ReloadSourceStr(xml);
while (DataReader.Name != "Account")
DataReader.Read();
XmlReader sub = DataReader.ReadSubtree();
while (sub.Read())
{
if (sub.Name == "Balance")
{
try
{
switch (param)
{
case 1: decimal num1 = sub.ReadElementContentAsDecimal(); break;
case 2: object num2 = sub.ReadElementContentAs(typeof(float), null); break;
case 3: bool num3 = sub.ReadElementContentAsBoolean(); break;
case 5: float num5 = sub.ReadElementContentAsFloat(); break;
case 6: double num6 = sub.ReadElementContentAsDouble(); break;
case 7: int num7 = sub.ReadElementContentAsInt(); break;
case 8: long num8 = sub.ReadElementContentAsLong(); break;
case 9: object num9 = sub.ReadElementContentAs(typeof(double), null); break;
case 10: object num10 = sub.ReadElementContentAs(typeof(decimal), null); break;
case 11: sub.Read(); decimal num11 = sub.ReadContentAsDecimal(); break;
case 12: sub.Read(); object num12 = sub.ReadContentAs(typeof(float), null); break;
case 13: sub.Read(); bool num13 = sub.ReadContentAsBoolean(); break;
case 15: sub.Read(); float num15 = sub.ReadContentAsFloat(); break;
case 16: sub.Read(); double num16 = sub.ReadContentAsDouble(); break;
case 17: sub.Read(); int num17 = sub.ReadContentAsInt(); break;
case 18: sub.Read(); long num18 = sub.ReadContentAsLong(); break;
case 19: sub.Read(); object num19 = sub.ReadContentAs(typeof(double), null); break;
case 20: sub.Read(); object num20 = sub.ReadContentAs(typeof(decimal), null); break;
case 21: object num21 = sub.ReadElementContentAsBase64(b, 0, 2); break;
case 22: object num22 = sub.ReadElementContentAsBinHex(b, 0, 2); break;
case 23: sub.Read(); object num23 = sub.ReadContentAsBase64(b, 0, 2); break;
case 24: sub.Read(); object num24 = sub.ReadContentAsBinHex(b, 0, 2); break;
}
}
catch (XmlException)
{
try
{
switch (param)
{
case 1: decimal num1 = sub.ReadElementContentAsDecimal(); break;
case 2: object num2 = sub.ReadElementContentAs(typeof(float), null); break;
case 3: bool num3 = sub.ReadElementContentAsBoolean(); break;
case 5: float num5 = sub.ReadElementContentAsFloat(); break;
case 6: double num6 = sub.ReadElementContentAsDouble(); break;
case 7: int num7 = sub.ReadElementContentAsInt(); break;
case 8: long num8 = sub.ReadElementContentAsLong(); break;
case 9: object num9 = sub.ReadElementContentAs(typeof(double), null); break;
case 10: object num10 = sub.ReadElementContentAs(typeof(decimal), null); break;
case 11: sub.Read(); decimal num11 = sub.ReadContentAsDecimal(); break;
case 12: sub.Read(); object num12 = sub.ReadContentAs(typeof(float), null); break;
case 13: sub.Read(); bool num13 = sub.ReadContentAsBoolean(); break;
case 15: sub.Read(); float num15 = sub.ReadContentAsFloat(); break;
case 16: sub.Read(); double num16 = sub.ReadContentAsDouble(); break;
case 17: sub.Read(); int num17 = sub.ReadContentAsInt(); break;
case 18: sub.Read(); long num18 = sub.ReadContentAsLong(); break;
case 19: sub.Read(); object num19 = sub.ReadContentAs(typeof(double), null); break;
case 20: sub.Read(); object num20 = sub.ReadContentAs(typeof(decimal), null); break;
case 21: object num21 = sub.ReadElementContentAsBase64(b, 0, 2); break;
case 22: object num22 = sub.ReadElementContentAsBinHex(b, 0, 2); break;
case 23: sub.Read(); object num23 = sub.ReadContentAsBase64(b, 0, 2); break;
case 24: sub.Read(); object num24 = sub.ReadContentAsBinHex(b, 0, 2); break;
}
}
catch (InvalidOperationException) { return TEST_PASS; }
catch (XmlException) { return TEST_PASS; }
if (param == 24 || param == 23) return TEST_PASS;
}
catch (NotSupportedException) { return TEST_PASS; }
}
}
return TEST_FAIL;
}
[Variation("SubtreeReader has empty namespace")]
public int v101()
{
string xml = @"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
"<b><c xsi:type='f:mytype'>some content</c></b></a>";
ReloadSourceStr(xml);
DataReader.Read(); CError.Compare(DataReader.Name, "a", "a");
DataReader.Read(); CError.Compare(DataReader.Name, "b", "b");
using (XmlReader subtree = DataReader.ReadSubtree())
{
subtree.Read(); CError.Compare(subtree.Name, "b", "b2");
subtree.Read(); CError.Compare(subtree.Name, "c", "c");
subtree.MoveToAttribute("type", "http://www.w3.org/2001/XMLSchema-instance");
CError.Compare(subtree.Value, "f:mytype", "value");
string ns = subtree.LookupNamespace("f");
if (ns == null) { return TEST_PASS; }
}
return TEST_FAIL;
}
[Variation("ReadValueChunk on an xmlns attribute that has been added by the subtree reader")]
public int v102()
{
char[] c = new char[10];
string xml = @"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
"<b><c xsi:type='f:mytype'>some content</c></b></a>";
ReloadSourceStr(xml);
DataReader.Read();
using (XmlReader subtree = DataReader.ReadSubtree())
{
subtree.Read();
CError.Compare(subtree.Name, "a", "a");
string s = subtree[0];
CError.Compare(s, "urn:foobar", "urn:foobar");
CError.Compare(subtree.LookupNamespace("xmlns"), "http://www.w3.org/2000/xmlns/", "xmlns");
CError.Compare(subtree.MoveToFirstAttribute(), "True");
try
{
CError.Compare(subtree.ReadValueChunk(c, 0, 10), 10, "ReadValueChunk");
CError.Compare(c[0].ToString(), "u", "u");
CError.Compare(c[9].ToString(), "r", "r");
}
catch (NotSupportedException) { if (IsCustomReader() || IsCharCheckingReader()) return TEST_PASS; }
}
return TEST_PASS;
}
}
}
| |
using fyiReporting.RDL;
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
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 [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel; // need this for the properties metadata
using System.Drawing.Design;
using System.Globalization;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Xml;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// PropertyImage - The Image specific Properties
/// </summary>
internal class PropertyImage : PropertyReportItem
{
internal PropertyImage(DesignXmlDraw d, DesignCtl dc, List<XmlNode> ris) : base(d, dc, ris)
{
}
[LocalizedCategory("Image")]
[LocalizedDisplayName("Image_Image")]
[LocalizedDescription("Image_Image")]
public PropertyImageI Image
{
get { return new PropertyImageI(this); }
}
}
[TypeConverter(typeof(PropertyImageConverter))]
[Editor(typeof(PropertyImageUIEditor), typeof(System.Drawing.Design.UITypeEditor))]
internal class PropertyImageI : IReportItem
{
PropertyImage _pi;
internal PropertyImageI(PropertyImage pi)
{
_pi = pi;
}
[RefreshProperties(RefreshProperties.Repaint)]
[TypeConverter(typeof(ImageSourceConverter))]
[LocalizedDisplayName("ImageI_Source")]
[LocalizedDescription("ImageI_Source")]
public string Source
{
get
{
return _pi.GetValue("Source", "External");
}
set
{
_pi.SetValue("Source", value);
}
}
[RefreshProperties(RefreshProperties.Repaint)]
[LocalizedDisplayName("ImageI_Value")]
[LocalizedDescription("ImageI_Value")]
public PropertyExpr Value
{
get
{
return new PropertyExpr(_pi.GetValue("Value", ""));
}
set
{
_pi.SetValue("Value", value.Expression);
}
}
[RefreshProperties(RefreshProperties.Repaint)]
[TypeConverter(typeof(ImageMIMETypeConverter))]
[LocalizedDisplayName("ImageI_MIMEType")]
[LocalizedDescription("ImageI_MIMEType")]
public string MIMEType
{
get
{
return _pi.GetValue("MIMEType", "");
}
set
{
if (string.Compare(this.Source.Trim(), "database", true) == 0)
throw new ArgumentException("MIMEType isn't relevent when Source isn't Database.");
_pi.SetValue("MIMEType", value);
}
}
[LocalizedDisplayName("ImageI_Sizing")]
[LocalizedDescription("ImageI_Sizing")]
public ImageSizingEnum Sizing
{
get
{
string s = _pi.GetValue("Sizing", "AutoSize");
return ImageSizing.GetStyle(s);
}
set
{
_pi.SetValue("Sizing", value.ToString());
}
}
public override string ToString()
{
string s = this.Source;
string v = "";
if (s.ToLower().Trim() != "none")
v = this.Value.Expression;
return string.Format("{0} {1}", s, v);
}
#region IReportItem Members
public PropertyReportItem GetPRI()
{
return this._pi;
}
#endregion
}
#region ImageConverter
internal class PropertyImageConverter : ExpandableObjectConverter
{
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
public override bool CanConvertTo(ITypeDescriptorContext context,
System.Type destinationType)
{
if (destinationType == typeof(PropertyImageI))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value is PropertyImage)
{
PropertyImageI pi = value as PropertyImageI;
return pi.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
#endregion
#region UIEditor
internal class PropertyImageUIEditor : UITypeEditor
{
internal PropertyImageUIEditor()
{
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
if ((context == null) || (provider == null))
return base.EditValue(context, provider, value);
// Access the Property Browser's UI display service
IWindowsFormsEditorService editorService =
(IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (editorService == null)
return base.EditValue(context, provider, value);
// Create an instance of the UI editor form
IReportItem iri = context.Instance as IReportItem;
if (iri == null)
return base.EditValue(context, provider, value);
PropertyImage pre = iri.GetPRI() as PropertyImage;
PropertyImageI pbi = value as PropertyImageI;
if (pbi == null)
return base.EditValue(context, provider, value);
using (SingleCtlDialog scd = new SingleCtlDialog(pre.DesignCtl, pre.Draw, pre.Nodes,
SingleCtlTypeEnum.ImageCtl, null))
{
///////
// Display the UI editor dialog
if (editorService.ShowDialog(scd) == DialogResult.OK)
{
// Return the new property value from the UI editor form
return new PropertyImageI(pre);
}
return base.EditValue(context, provider, value);
}
}
}
#endregion
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using OpenADK.Library;
using OpenADK.Util;
namespace OpenADK.Examples
{
/// <summary> A convenience class to parse the command-line of all Adk Example agents
/// and to read a list of zones from a zones.properties file, if present in
/// the current working directory.<p>
/// *
/// </summary>
/// <version> Adk 1.0
///
/// </version>
public class AdkExamples
{
/// <summary> False if the /noreg option was specified, indicating the agent should
/// not send a SIF_Register message when connecting to zones
/// </summary>
public static bool Reg = true;
/// <summary> True if the /unreg option was specified, indicating the agent should
/// send a SIF_Unregister when shutting down and disconnecting from zones
/// </summary>
public static bool Unreg = false;
/// <summary> The SIFVersion specified on the command-line
/// </summary>
public static SifVersion Version;
/// <summary> Parsed command-line arguments
/// </summary>
private static string[] sArguments = null;
/// <summary> Parse the command-line. This method may be called repeatedly, usually
/// once from the sample agent's <c>main</code> function prior to
/// initializing the Adk and again from the <c>Agent.initialize</code>
/// method after initializing the Agent superclass. When called without an
/// Agent instance, only those options that do not rely on an AgentProperties
/// object are processed (e.g. the /D option).
/// <p>
/// *
/// If a file named 'agent.rsp' exists in the current directory, any command
/// line options specified will be appended to the command-line arguments
/// passed to this method. Each line of the agent.rsp text file may be
/// comprised of one or more arguments separated by spaces, so that the
/// entirely set of arguments can be on one line or broken up onto many
/// lines.<p>
/// *
/// </summary>
/// <param name="agent">An Agent instance that will be updated when certain
/// command-line options are parsed
/// </param>
/// <param name="arguments">The string of arguments provided by the <c>main</code>
/// function
///
/// </param>
public static NameValueCollection parseCL( Agent agent,
string[] arguments )
{
if( sArguments == null )
{
sArguments = ReadArgsFromResponseFile( arguments );
}
if( agent == null )
{
ParseGlobalProperties();
return null;
}
else
{
return ParseAgentProperties( agent );
}
}
private static NameValueCollection ParseAgentProperties( Agent agent )
{
// Parse all other options...
AgentProperties props = agent.Properties;
NameValueCollection misc = new NameValueCollection();
int port = -1;
string host = null;
bool useHttps = false;
string sslCert = null;
string clientCert = null;
int clientAuth = 0;
for( int i = 0; i < sArguments.Length; i++ )
{
if( sArguments[ i ].ToUpper().Equals( "/sourceId".ToUpper() ) &&
i != sArguments.Length - 1 )
{
agent.Id = sArguments[ ++i ];
}
else if( sArguments[ i ].ToUpper().Equals( "/noreg".ToUpper() ) )
{
Reg = false;
}
else if( sArguments[ i ].ToUpper().Equals( "/unreg".ToUpper() ) )
{
Unreg = true;
}
else if( sArguments[ i ].ToUpper().Equals( "/pull".ToUpper() ) )
{
props.MessagingMode = AgentMessagingMode.Pull;
}
else if( sArguments[ i ].ToUpper().Equals( "/push".ToUpper() ) )
{
props.MessagingMode = AgentMessagingMode.Push;
}
else if( sArguments[ i ].ToUpper().Equals( "/port".ToUpper() ) &&
i != sArguments.Length - 1 )
{
try
{
port = Int32.Parse( sArguments[ ++i ] );
}
catch( FormatException )
{
Console.WriteLine( "Invalid port: " + sArguments[ i - 1 ] );
}
}
else if( sArguments[ i ].ToUpper().Equals( "/https".ToUpper() ) )
{
useHttps = true;
}
else if( sArguments[ i ].ToUpper().Equals( "/sslCert".ToUpper() ) )
{
sslCert = sArguments[ ++i ];
}
else if( sArguments[ i ].ToUpper().Equals( "/clientCert".ToUpper() ) )
{
clientCert = sArguments[ ++i ];
}
else if( sArguments[ i ].ToUpper().Equals( "/clientAuth".ToUpper() ) )
{
try
{
clientAuth = int.Parse( sArguments[ ++i ] );
}
catch( FormatException )
{
clientAuth = 0;
}
}
else if( sArguments[ i ].ToUpper().Equals( "/host".ToUpper() ) &&
i != sArguments.Length - 1 )
{
host = sArguments[ ++i ];
}
else if( sArguments[ i ].ToUpper().Equals( "/timeout".ToUpper() ) &&
i != sArguments.Length - 1 )
{
try
{
props.DefaultTimeout =
TimeSpan.FromMilliseconds( Int32.Parse( sArguments[ ++i ] ) );
}
catch( FormatException )
{
Console.WriteLine( "Invalid timeout: " + sArguments[ i - 1 ] );
}
}
else if( sArguments[ i ].ToUpper().Equals( "/freq".ToUpper() ) &&
i != sArguments.Length - 1 )
{
try
{
props.PullFrequency =
TimeSpan.FromMilliseconds( int.Parse( sArguments[ ++i ] ) );
}
catch( FormatException )
{
Console.WriteLine
( "Invalid pull frequency: " + sArguments[ i - 1 ] );
}
}
else if( sArguments[ i ].ToUpper().Equals( "/opensif".ToUpper() ) )
{
// OpenSIF reports attempts to re-subscribe to objects as an
// error instead of a success status code. The Adk would therefore
// throw an exception if it encountered the error, so we can
// disable that behavior here.
props.IgnoreProvisioningErrors = true;
}
else if( sArguments[ i ][ 0 ] == '/' )
{
if( i == sArguments.Length - 1 ||
sArguments[ i + 1 ].StartsWith( "/" ) )
{
misc[ sArguments[ i ].Substring( 1 ) ] = null;
}
else
{
misc[ sArguments[ i ].Substring( 1 ) ] = sArguments[ ++i ];
}
}
}
if( useHttps )
{
// Set transport properties (HTTPS)
HttpsProperties https = agent.DefaultHttpsProperties;
if( sslCert != null )
{
https.SSLCertName = sslCert;
}
if( clientCert != null )
{
https.ClientCertName = clientCert;
}
https.ClientAuthLevel = clientAuth;
if( port != -1 )
{
https.Port = port;
}
https.Host = host;
props.TransportProtocol = "https";
}
else
{
// Set transport properties (HTTP)
HttpProperties http = agent.DefaultHttpProperties;
if( port != -1 )
{
http.Port = port;
}
http.Host = host;
props.TransportProtocol = "http";
}
return misc;
}
private static void ParseGlobalProperties()
{
// Look for options that do not affect the AgentProperties...
for( int i = 0; i < sArguments.Length; i++ )
{
if( sArguments[ i ].ToUpper().Equals( "/debug".ToUpper() ) )
{
if( i < sArguments.Length - 1 )
{
try
{
Adk.Debug = AdkDebugFlags.None;
int k = Int32.Parse( sArguments[ ++i ] );
if( k == 1 )
{
Adk.Debug = AdkDebugFlags.Minimal;
}
else if( k == 2 )
{
Adk.Debug = AdkDebugFlags.Moderate;
}
else if( k == 3 )
{
Adk.Debug = AdkDebugFlags.Detailed;
}
else if( k == 4 )
{
Adk.Debug = AdkDebugFlags.Very_Detailed;
}
else if( k == 5 )
{
Adk.Debug = AdkDebugFlags.All;
}
}
catch( Exception )
{
Adk.Debug = AdkDebugFlags.All;
}
}
else
{
Adk.Debug = AdkDebugFlags.All;
}
}
else if( sArguments[ i ].StartsWith( "/D" ) )
{
string prop = sArguments[ i ].Substring( 2 );
if( i != sArguments.Length - 1 )
{
Properties.SetProperty( prop, sArguments[ ++i ] );
}
else
{
Console.WriteLine( "Usage: /Dproperty value" );
}
}
else if( sArguments[ i ].ToUpper().Equals( "/log".ToUpper() ) &&
i != sArguments.Length - 1 )
{
try
{
Adk.SetLogFile( sArguments[ ++i ] );
}
catch( IOException ioe )
{
Console.WriteLine( "Could not redirect debug output to log file: " + ioe );
}
}
else if( sArguments[ i ].ToUpper().Equals( "/ver".ToUpper() ) &&
i != sArguments.Length - 1 )
{
Version = SifVersion.Parse( sArguments[ ++i ] );
}
else if( sArguments[ i ].Equals( "/?" ) )
{
Console.WriteLine();
Console.WriteLine
( "These options are common to all Adk Example agents. For help on the usage" );
Console.WriteLine
( "of this agent in particular, run the agent without any parameters. Note that" );
Console.WriteLine
( "most agents support multiple zones if a zones.properties file is found in" );
Console.WriteLine( "the current directory." );
Console.WriteLine();
printHelp();
Environment.Exit( 0 );
}
}
}
private static string[] ReadArgsFromResponseFile( string[] arguments )
{
if( arguments.Length > 0 && arguments[ 0 ][ 0 ] != '/' )
{
// Look for an agent.rsp response file
FileInfo rsp = new FileInfo( arguments[ 0 ] );
if( rsp.Exists )
{
try
{
ArrayList v = new ArrayList();
using( StreamReader reader = File.OpenText( rsp.FullName ) )
{
string line;
while( ( line = reader.ReadLine() ) != null )
{
// allow comment lines, starting with a ;
if( !line.StartsWith( ";" ) )
{
foreach( string token in line.Split( ' ' ) )
{
v.Add( token );
}
}
}
reader.Close();
}
// Append any arguments found to the args array
if( v.Count > 0 )
{
string[] args = new string[ arguments.Length + v.Count ];
Array.Copy( arguments, 0, arguments, 0, arguments.Length );
v.CopyTo( arguments, arguments.Length );
Console.Out.Write
( "Reading command-line arguments from " + arguments[ 0 ] + ": " );
for( int i = 0; i < args.Length; i++ )
{
Console.Out.Write( args[ i ] + " " );
}
Console.WriteLine();
Console.WriteLine();
return args;
}
}
catch( Exception ex )
{
Console.WriteLine
( "Error reading command-line arguments from agent.rsp file: " + ex );
}
}
}
return arguments;
}
/// <summary> Display help to System.out
/// </summary>
public static void printHelp()
{
Console.WriteLine( " /sourceId name The name of the agent" );
Console.WriteLine
( " /ver version Default SIF Version to use (e.g. 10r1, 10r2, etc.)" );
Console.WriteLine( " /debug level Enable debugging to the console" );
Console.WriteLine( " 1 - Minimal" );
Console.WriteLine( " 2 - Moderate" );
Console.WriteLine( " 3 - Detailed" );
Console.WriteLine( " 4 - Very Detailed" );
Console.WriteLine( " 5 - All" );
Console.WriteLine( " /log file Redirects logging to the specified file" );
Console.WriteLine( " /pull Use Pull mode" );
Console.WriteLine
( " /freq Sets the Pull frequency (defaults to 15 seconds)" );
Console.WriteLine( " /push Use Push mode" );
Console.WriteLine
( " /port n The local port for Push mode (defaults to 12000)" );
Console.WriteLine
( " /host addr The local IP address for push mode (defaults to any)" );
Console.WriteLine
( " /noreg Do not send a SIF_Register on startup (sent by default)" );
Console.WriteLine
( " /unreg Send a SIF_Unregister on exit (not sent by default)" );
Console.WriteLine( " /timeout ms Sets the Adk timeout period (defaults to 30000)" );
Console.WriteLine( " /opensif Ignores provisioning errors from OpenSIF" );
Console.WriteLine( " /Dproperty val Sets a Java System property" );
Console.WriteLine();
Console.WriteLine( " HTTPS Transport Options:" );
Console.WriteLine
( " Certificates will be retrieved from the Current User's Personal Store" );
Console.WriteLine( " /https Use HTTPS instead of HTTP." );
Console.WriteLine( " /clientAuth [1|2|3] Require Client Authentication level" );
Console.WriteLine( " /sslCert cert The subject of the certificate to use for SSL" );
Console.WriteLine
( " /clientCert The subject of the certificate to use for Client Authentication" );
Console.WriteLine();
Console.WriteLine();
Console.WriteLine( " Response Files:" );
Console.WriteLine
( " To use a response file instead of typing arguments on the command-line," );
Console.WriteLine
( " pass the name of the response file as the first argument. This text" );
Console.WriteLine
( " file may contain any combination of arguments on one or more lines," );
Console.WriteLine
( " which are appended to any arguments specified on the command-line." );
}
/// <summary> Looks for a file named zones.properties and if found reads its contents
/// into a HashMap where the key of each entry is the Zone ID and the value
/// is the Zone URL. A valid HashMap is always returned by this method; the
/// called typically assigns the value of the /zone and /url command-line
/// options to that map (when applicable).
/// </summary>
public static NameValueCollection ReadZonesList()
{
NameValueCollection list = new NameValueCollection();
return list;
}
static AdkExamples()
{
Version = SifVersion.LATEST;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace DotVVM.Framework.Compilation.Parser.Binding.Tokenizer
{
public class BindingTokenizer : TokenizerBase<BindingToken, BindingTokenType>
{
private readonly ISet<char> operatorCharacters = new HashSet<char> { '+', '-', '*', '/', '^', '\\', '%', '<', '>', '=', '&', '|', '~', '!' };
protected override BindingTokenType TextTokenType => BindingTokenType.Identifier;
protected override BindingTokenType WhiteSpaceTokenType => BindingTokenType.WhiteSpace;
public bool IsOperator(char c) => operatorCharacters.Contains(c);
public override void Tokenize(string sourceText)
{
TokenizeInternal(sourceText, () => { TokenizeBindingValue(); return true; });
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void TokenizeBindingValue()
{
while (Peek() != NullChar)
{
var ch = Peek();
switch (ch)
{
case '.':
if (CurrentTokenChars.Length > 0 && Enumerable.Range(0, CurrentTokenChars.Length).All(i => Char.IsDigit(CurrentTokenChars[i])))
{
// treat dot in a number as part of the number
Read();
if (!char.IsDigit(Peek()))
{
CreateToken(BindingTokenType.Identifier, 1);
CreateToken(BindingTokenType.Dot);
}
}
else
{
FinishIncompleteIdentifier();
Read();
CreateToken(BindingTokenType.Dot);
}
break;
case ',':
FinishIncompleteIdentifier();
Read();
CreateToken(BindingTokenType.Comma);
break;
case '(':
FinishIncompleteIdentifier();
Read();
CreateToken(BindingTokenType.OpenParenthesis);
break;
case ')':
FinishIncompleteIdentifier();
Read();
CreateToken(BindingTokenType.CloseParenthesis);
break;
case '[':
FinishIncompleteIdentifier();
Read();
CreateToken(BindingTokenType.OpenArrayBrace);
break;
case ']':
FinishIncompleteIdentifier();
Read();
CreateToken(BindingTokenType.CloseArrayBrace);
break;
case '+':
FinishIncompleteIdentifier();
Read();
EnsureUnsupportedOperator(BindingTokenType.AddOperator);
break;
case '-':
FinishIncompleteIdentifier();
Read();
EnsureUnsupportedOperator(BindingTokenType.SubtractOperator);
break;
case '*':
FinishIncompleteIdentifier();
Read();
EnsureUnsupportedOperator(BindingTokenType.MultiplyOperator);
break;
case '/':
FinishIncompleteIdentifier();
Read();
EnsureUnsupportedOperator(BindingTokenType.DivideOperator);
break;
case '%':
FinishIncompleteIdentifier();
Read();
EnsureUnsupportedOperator(BindingTokenType.ModulusOperator);
break;
case '^':
FinishIncompleteIdentifier();
Read();
EnsureUnsupportedOperator(BindingTokenType.UnsupportedOperator);
break;
case ':':
FinishIncompleteIdentifier();
Read();
CreateToken(BindingTokenType.ColonOperator);
break;
case '=':
FinishIncompleteIdentifier();
Read();
if (Peek() == '=')
{
Read();
EnsureUnsupportedOperator(BindingTokenType.EqualsEqualsOperator);
}
else {
EnsureUnsupportedOperator(BindingTokenType.AssignOperator);
}
break;
case '|':
FinishIncompleteIdentifier();
Read();
if (Peek() == '|')
{
Read();
EnsureUnsupportedOperator(BindingTokenType.OrElseOperator);
}
else
{
EnsureUnsupportedOperator(BindingTokenType.OrOperator);
}
break;
case '&':
FinishIncompleteIdentifier();
Read();
if (Peek() == '&')
{
Read();
EnsureUnsupportedOperator(BindingTokenType.AndAlsoOperator);
}
else
{
EnsureUnsupportedOperator(BindingTokenType.AndOperator);
}
break;
case '<':
FinishIncompleteIdentifier();
Read();
if (Peek() == '=')
{
Read();
EnsureUnsupportedOperator(BindingTokenType.LessThanEqualsOperator);
}
else
{
EnsureUnsupportedOperator(BindingTokenType.LessThanOperator);
}
break;
case '>':
FinishIncompleteIdentifier();
Read();
if (Peek() == '=')
{
Read();
EnsureUnsupportedOperator(BindingTokenType.GreaterThanEqualsOperator);
}
else
{
//I need to take somting like >>>> into accout if it si something like
//>&*% or whatever, it will be other operator's problem.
CreateToken(BindingTokenType.GreaterThanOperator);
}
break;
case '!':
FinishIncompleteIdentifier();
Read();
if (Peek() == '=')
{
Read();
EnsureUnsupportedOperator(BindingTokenType.NotEqualsOperator);
}
else
{
EnsureUnsupportedOperator(BindingTokenType.NotOperator);
}
break;
case '\'':
case '"':
FinishIncompleteIdentifier();
string errorMessage;
ReadStringLiteral(out errorMessage);
CreateToken(BindingTokenType.StringLiteralToken, errorProvider: t => CreateTokenError(t, errorMessage));
break;
case '?':
FinishIncompleteIdentifier();
Read();
if (Peek() == '?')
{
Read();
EnsureUnsupportedOperator(BindingTokenType.NullCoalescingOperator);
}
else
{
EnsureUnsupportedOperator(BindingTokenType.QuestionMarkOperator);
}
break;
default:
if (char.IsWhiteSpace(ch))
{
// white space
FinishIncompleteIdentifier();
SkipWhitespace();
}
else
{
// text content
Read();
}
break;
}
}
// treat remaining content as text
FinishIncompleteIdentifier();
}
protected override BindingToken NewToken()
{
return new BindingToken();
}
private void FinishIncompleteIdentifier()
{
if (DistanceSinceLastToken > 0)
{
CreateToken(BindingTokenType.Identifier);
}
}
internal void EnsureUnsupportedOperator(BindingTokenType preferedOperatorToken)
{
if (IsOperator(Peek()))
{
while (IsOperator(Peek()))
{
Read();
}
CreateToken(BindingTokenType.UnsupportedOperator);
}
else
{
CreateToken(preferedOperatorToken);
}
}
internal void ReadStringLiteral(out string errorMessage)
{
ReadStringLiteral(Peek, Read, out errorMessage);
}
/// <summary>
/// Reads the string literal.
/// </summary>
internal static void ReadStringLiteral(Func<char> peekFunction, Func<char> readFunction, out string errorMessage)
{
var quoteChar = peekFunction();
readFunction();
while (peekFunction() != quoteChar)
{
if (peekFunction() == NullChar)
{
// unfinished string literal
errorMessage = "The string literal was not closed!";
return;
}
if (peekFunction() == '\\')
{
// escape char - read it and skip the next char so it won't end the loop
readFunction();
readFunction();
}
else
{
// normal character - read it
readFunction();
}
}
readFunction();
errorMessage = null;
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Avalonia.VisualTree
{
/// <summary>
/// Provides extension methods for working with the visual tree.
/// </summary>
public static class VisualExtensions
{
/// <summary>
/// Tries to get the first common ancestor of two visuals.
/// </summary>
/// <param name="visual">The first visual.</param>
/// <param name="target">The second visual.</param>
/// <returns>The common ancestor, or null if not found.</returns>
public static IVisual FindCommonVisualAncestor(this IVisual visual, IVisual target)
{
return visual.GetSelfAndVisualAncestors().Intersect(target.GetSelfAndVisualAncestors())
.FirstOrDefault();
}
/// <summary>
/// Enumerates the ancestors of an <see cref="IVisual"/> in the visual tree.
/// </summary>
/// <param name="visual">The visual.</param>
/// <returns>The visual's ancestors.</returns>
public static IEnumerable<IVisual> GetVisualAncestors(this IVisual visual)
{
Contract.Requires<ArgumentNullException>(visual != null);
visual = visual.VisualParent;
while (visual != null)
{
yield return visual;
visual = visual.VisualParent;
}
}
/// <summary>
/// Enumerates an <see cref="IVisual"/> and its ancestors in the visual tree.
/// </summary>
/// <param name="visual">The visual.</param>
/// <returns>The visual and its ancestors.</returns>
public static IEnumerable<IVisual> GetSelfAndVisualAncestors(this IVisual visual)
{
yield return visual;
foreach (var ancestor in visual.GetVisualAncestors())
{
yield return ancestor;
}
}
/// <summary>
/// Gets the first visual in the visual tree whose bounds contain a point.
/// </summary>
/// <param name="visual">The root visual to test.</param>
/// <param name="p">The point.</param>
/// <returns>The visuals at the requested point.</returns>
public static IVisual GetVisualAt(this IVisual visual, Point p)
{
Contract.Requires<ArgumentNullException>(visual != null);
return visual.GetVisualsAt(p).FirstOrDefault();
}
/// <summary>
/// Enumerates the visible visuals in the visual tree whose bounds contain a point.
/// </summary>
/// <param name="visual">The root visual to test.</param>
/// <param name="p">The point.</param>
/// <returns>The visuals at the requested point.</returns>
public static IEnumerable<IVisual> GetVisualsAt(
this IVisual visual,
Point p)
{
Contract.Requires<ArgumentNullException>(visual != null);
return visual.GetVisualsAt(p, x => x.IsVisible);
}
/// <summary>
/// Enumerates the visuals in the visual tree whose bounds contain a point.
/// </summary>
/// <param name="visual">The root visual to test.</param>
/// <param name="p">The point.</param>
/// <param name="filter">
/// A filter predicate. If the predicate returns false then the visual and all its
/// children will be excluded from the results.
/// </param>
/// <returns>The visuals at the requested point.</returns>
public static IEnumerable<IVisual> GetVisualsAt(
this IVisual visual,
Point p,
Func<IVisual, bool> filter)
{
Contract.Requires<ArgumentNullException>(visual != null);
if (filter?.Invoke(visual) != false)
{
bool containsPoint = BoundsTracker.GetTransformedBounds((Visual)visual)?.Contains(p) == true;
if ((containsPoint || !visual.ClipToBounds) && visual.VisualChildren.Any())
{
foreach (var child in visual.VisualChildren.SortByZIndex())
{
foreach (var result in child.GetVisualsAt(p, filter))
{
yield return result;
}
}
}
if (containsPoint)
{
yield return visual;
}
}
}
/// <summary>
/// Enumerates the children of an <see cref="IVisual"/> in the visual tree.
/// </summary>
/// <param name="visual">The visual.</param>
/// <returns>The visual children.</returns>
public static IEnumerable<IVisual> GetVisualChildren(this IVisual visual)
{
return visual.VisualChildren;
}
/// <summary>
/// Enumerates the descendents of an <see cref="IVisual"/> in the visual tree.
/// </summary>
/// <param name="visual">The visual.</param>
/// <returns>The visual's ancestors.</returns>
public static IEnumerable<IVisual> GetVisualDescendents(this IVisual visual)
{
foreach (IVisual child in visual.VisualChildren)
{
yield return child;
foreach (IVisual descendent in child.GetVisualDescendents())
{
yield return descendent;
}
}
}
/// <summary>
/// Enumerates an <see cref="IVisual"/> and its descendents in the visual tree.
/// </summary>
/// <param name="visual">The visual.</param>
/// <returns>The visual and its ancestors.</returns>
public static IEnumerable<IVisual> GetSelfAndVisualDescendents(this IVisual visual)
{
yield return visual;
foreach (var ancestor in visual.GetVisualDescendents())
{
yield return ancestor;
}
}
/// <summary>
/// Gets the visual parent of an <see cref="IVisual"/>.
/// </summary>
/// <param name="visual">The visual.</param>
/// <returns>The parent, or null if the visual is unparented.</returns>
public static IVisual GetVisualParent(this IVisual visual)
{
return visual.VisualParent;
}
/// <summary>
/// Gets the visual parent of an <see cref="IVisual"/>.
/// </summary>
/// <typeparam name="T">The type of the visual parent.</typeparam>
/// <param name="visual">The visual.</param>
/// <returns>
/// The parent, or null if the visual is unparented or its parent is not of type <typeparamref name="T"/>.
/// </returns>
public static T GetVisualParent<T>(this IVisual visual) where T : class
{
return visual.VisualParent as T;
}
/// <summary>
/// Gets the root visual for an <see cref="IVisual"/>.
/// </summary>
/// <param name="visual">The visual.</param>
/// <returns>
/// The root visual or null if the visual is not rooted.
/// </returns>
public static IVisual GetVisualRoot(this IVisual visual)
{
Contract.Requires<ArgumentNullException>(visual != null);
return visual.VisualRoot as IVisual;
}
/// <summary>
/// Tests whether an <see cref="IVisual"/> is an ancestor of another visual.
/// </summary>
/// <param name="visual">The visual.</param>
/// <param name="target">The potential descendent.</param>
/// <returns>
/// True if <paramref name="visual"/> is an ancestor of <paramref name="target"/>;
/// otherwise false.
/// </returns>
public static bool IsVisualAncestorOf(this IVisual visual, IVisual target)
{
return target.GetVisualAncestors().Any(x => x == visual);
}
public static IEnumerable<IVisual> SortByZIndex(this IEnumerable<IVisual> elements)
{
return elements
.Select((element, index) => new ZOrderElement
{
Element = element,
Index = index,
ZIndex = element.ZIndex,
})
.OrderBy(x => x, null)
.Select(x => x.Element);
}
private class ZOrderElement : IComparable<ZOrderElement>
{
public IVisual Element { get; set; }
public int Index { get; set; }
public int ZIndex { get; set; }
public int CompareTo(ZOrderElement other)
{
var z = other.ZIndex - ZIndex;
if (z != 0)
{
return z;
}
else
{
return other.Index - Index;
}
}
}
}
}
| |
using Glimpse;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using MusicStore.Components;
using MusicStore.Models;
namespace MusicStore
{
public class Startup
{
private readonly Platform _platform;
public Startup(IHostingEnvironment hostingEnvironment)
{
// Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1'
// is found in both the registered sources, then the later source will win. By this way a Local config
// can be overridden by a different setting while deployed remotely.
var builder = new ConfigurationBuilder()
.SetBasePath(hostingEnvironment.ContentRootPath)
.AddJsonFile("config.json")
//All environment variables in the process's context flow in as configuration values.
.AddEnvironmentVariables();
Configuration = builder.Build();
_platform = new Platform();
}
public IConfiguration Configuration { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddGlimpse();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
// Add EF services to the services container
if (_platform.UseInMemoryStore)
{
services.AddDbContext<MusicStoreContext>(options =>
options.UseInMemoryDatabase());
}
else
{
services.AddDbContext<MusicStoreContext>(options =>
options.UseSqlServer(Configuration[StoreConfig.ConnectionStringKey.Replace("__", ":")]));
}
// Add Identity services to the services container
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Cookies.ApplicationCookie.AccessDeniedPath = "/Home/AccessDenied";
})
.AddEntityFrameworkStores<MusicStoreContext>()
.AddDefaultTokenProviders();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder.WithOrigins("http://example.com");
});
});
services.AddLogging();
// Add MVC services to the services container
services.AddMvc();
// Add memory cache services
services.AddMemoryCache();
services.AddDistributedMemoryCache();
// Add session related services.
services.AddSession();
// Add the system clock service
services.AddSingleton<ISystemClock, SystemClock>();
// Configure Auth
services.AddAuthorization(options =>
{
options.AddPolicy(
"ManageStore",
authBuilder =>
{
authBuilder.RequireClaim("ManageStore", "Allowed");
});
});
}
//This method is invoked when ASPNETCORE_ENVIRONMENT is 'Development' or is not defined
//The allowed values are Development,Staging and Production
public void ConfigureDevelopment(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseGlimpse();
loggerFactory.AddConsole(minLevel: LogLevel.Information);
// StatusCode pages to gracefully handle status codes 400-599.
app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage");
// Display custom error page in production when error occurs
// During development use the ErrorPage middleware to display error information in the browser
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
Configure(app);
}
//This method is invoked when ASPNETCORE_ENVIRONMENT is 'Staging'
//The allowed values are Development,Staging and Production
public void ConfigureStaging(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseGlimpse();
loggerFactory.AddConsole(minLevel: LogLevel.Warning);
// StatusCode pages to gracefully handle status codes 400-599.
app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage");
app.UseExceptionHandler("/Home/Error");
Configure(app);
}
//This method is invoked when ASPNETCORE_ENVIRONMENT is 'Production'
//The allowed values are Development,Staging and Production
public void ConfigureProduction(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseGlimpse();
loggerFactory.AddConsole(minLevel: LogLevel.Warning);
// StatusCode pages to gracefully handle status codes 400-599.
app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage");
app.UseExceptionHandler("/Home/Error");
Configure(app);
}
public void Configure(IApplicationBuilder app)
{
// Configure Session.
app.UseSession();
// Add static files to the request pipeline
app.UseStaticFiles();
// Add cookie-based authentication to the request pipeline
app.UseIdentity();
app.UseFacebookAuthentication(new FacebookOptions
{
AppId = "550624398330273",
AppSecret = "10e56a291d6b618da61b1e0dae3a8954"
});
app.UseGoogleAuthentication(new GoogleOptions
{
ClientId = "995291875932-0rt7417v5baevqrno24kv332b7d6d30a.apps.googleusercontent.com",
ClientSecret = "J_AT57H5KH_ItmMdu0r6PfXm"
});
app.UseTwitterAuthentication(new TwitterOptions
{
ConsumerKey = "lDSPIu480ocnXYZ9DumGCDw37",
ConsumerSecret = "fpo0oWRNc3vsZKlZSq1PyOSoeXlJd7NnG4Rfc94xbFXsdcc3nH"
});
// The MicrosoftAccount service has restrictions that prevent the use of
// http://localhost:5001/ for test applications.
// As such, here is how to change this sample to uses http://ktesting.com:5001/ instead.
// Edit the Project.json file and replace http://localhost:5001/ with http://ktesting.com:5001/.
// From an admin command console first enter:
// notepad C:\Windows\System32\drivers\etc\hosts
// and add this to the file, save, and exit (and reboot?):
// 127.0.0.1 ktesting.com
// Then you can choose to run the app as admin (see below) or add the following ACL as admin:
// netsh http add urlacl url=http://ktesting:5001/ user=[domain\user]
// The sample app can then be run via:
// dnx . web
app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions
{
DisplayName = "MicrosoftAccount - Requires project changes",
ClientId = "000000004012C08A",
ClientSecret = "GaMQ2hCnqAC6EcDLnXsAeBVIJOLmeutL"
});
// Add MVC to the request pipeline
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller}/{action}",
defaults: new { action = "Index" });
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
routes.MapRoute(
name: "api",
template: "{controller}/{id?}");
});
//Populates the MusicStore sample data
SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait();
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE 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.
*****************************************************************************/
#pragma warning disable 0219
/*****************************************************************************
* Spine Editor Utilities created by Mitch Thompson
* Full irrevocable rights and permissions granted to Esoteric Software
*****************************************************************************/
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection;
using Spine;
[InitializeOnLoad]
public class SpineEditorUtilities : AssetPostprocessor {
public static class Icons {
public static Texture2D skeleton;
public static Texture2D nullBone;
public static Texture2D bone;
public static Texture2D poseBones;
public static Texture2D boneNib;
public static Texture2D slot;
public static Texture2D slotRoot;
public static Texture2D skinPlaceholder;
public static Texture2D image;
public static Texture2D boundingBox;
public static Texture2D mesh;
public static Texture2D weights;
public static Texture2D skin;
public static Texture2D skinsRoot;
public static Texture2D animation;
public static Texture2D animationRoot;
public static Texture2D spine;
public static Texture2D _event;
public static Texture2D constraintNib;
public static Texture2D warning;
public static Texture2D skeletonUtility;
public static Texture2D hingeChain;
public static Texture2D subMeshRenderer;
public static Texture2D unityIcon;
public static Texture2D controllerIcon;
public static Mesh boneMesh {
get {
if (_boneMesh == null) {
_boneMesh = new Mesh();
_boneMesh.vertices = new Vector3[4] {
Vector3.zero,
new Vector3(-0.1f, 0.1f, 0),
Vector3.up,
new Vector3(0.1f, 0.1f, 0)
};
_boneMesh.uv = new Vector2[4];
_boneMesh.triangles = new int[6] { 0, 1, 2, 2, 3, 0 };
_boneMesh.RecalculateBounds();
_boneMesh.RecalculateNormals();
}
return _boneMesh;
}
}
internal static Mesh _boneMesh;
public static Material boneMaterial {
get {
if (_boneMaterial == null) {
#if UNITY_4_3
_boneMaterial = new Material(Shader.Find("Particles/Alpha Blended"));
_boneMaterial.SetColor("_TintColor", new Color(0.4f, 0.4f, 0.4f, 0.25f));
#else
_boneMaterial = new Material(Shader.Find("Spine/Bones"));
_boneMaterial.SetColor("_Color", new Color(0.4f, 0.4f, 0.4f, 0.25f));
#endif
}
return _boneMaterial;
}
}
internal static Material _boneMaterial;
public static void Initialize () {
skeleton = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-skeleton.png");
nullBone = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-null.png");
bone = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-bone.png");
poseBones = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-poseBones.png");
boneNib = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-boneNib.png");
slot = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-slot.png");
slotRoot = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-slotRoot.png");
skinPlaceholder = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-skinPlaceholder.png");
image = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-image.png");
boundingBox = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-boundingBox.png");
mesh = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-mesh.png");
weights = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-weights.png");
skin = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-skinPlaceholder.png");
skinsRoot = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-skinsRoot.png");
animation = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-animation.png");
animationRoot = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-animationRoot.png");
spine = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-spine.png");
_event = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-event.png");
constraintNib = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-constraintNib.png");
warning = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-warning.png");
skeletonUtility = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-skeletonUtility.png");
hingeChain = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-hingeChain.png");
subMeshRenderer = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-subMeshRenderer.png");
unityIcon = EditorGUIUtility.FindTexture("SceneAsset Icon");
controllerIcon = EditorGUIUtility.FindTexture("AnimatorController Icon");
}
}
public static string editorPath = "";
public static string editorGUIPath = "";
static Dictionary<int, GameObject> skeletonRendererTable;
static Dictionary<int, SkeletonUtilityBone> skeletonUtilityBoneTable;
static Dictionary<int, BoundingBoxFollower> boundingBoxFollowerTable;
public static float defaultScale = 0.01f;
public static float defaultMix = 0.2f;
public static string defaultShader = "Spine/Skeleton";
public static bool initialized;
const string DEFAULT_MIX_KEY = "SPINE_DEFAULT_MIX";
static SpineEditorUtilities () {
Initialize();
}
static void Initialize () {
defaultMix = EditorPrefs.GetFloat(DEFAULT_MIX_KEY, 0.2f);
DirectoryInfo rootDir = new DirectoryInfo(Application.dataPath);
FileInfo[] files = rootDir.GetFiles("SpineEditorUtilities.cs", SearchOption.AllDirectories);
editorPath = Path.GetDirectoryName(files[0].FullName.Replace("\\", "/").Replace(Application.dataPath, "Assets"));
editorGUIPath = editorPath + "/GUI";
Icons.Initialize();
skeletonRendererTable = new Dictionary<int, GameObject>();
skeletonUtilityBoneTable = new Dictionary<int, SkeletonUtilityBone>();
boundingBoxFollowerTable = new Dictionary<int, BoundingBoxFollower>();
EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged;
EditorApplication.hierarchyWindowItemOnGUI += HierarchyWindowItemOnGUI;
HierarchyWindowChanged();
initialized = true;
}
public static void ConfirmInitialization () {
if (!initialized || Icons.skeleton == null)
Initialize();
}
static void HierarchyWindowChanged () {
skeletonRendererTable.Clear();
skeletonUtilityBoneTable.Clear();
boundingBoxFollowerTable.Clear();
SkeletonRenderer[] arr = Object.FindObjectsOfType<SkeletonRenderer>();
foreach (SkeletonRenderer r in arr)
skeletonRendererTable.Add(r.gameObject.GetInstanceID(), r.gameObject);
SkeletonUtilityBone[] boneArr = Object.FindObjectsOfType<SkeletonUtilityBone>();
foreach (SkeletonUtilityBone b in boneArr)
skeletonUtilityBoneTable.Add(b.gameObject.GetInstanceID(), b);
BoundingBoxFollower[] bbfArr = Object.FindObjectsOfType<BoundingBoxFollower>();
foreach (BoundingBoxFollower bbf in bbfArr)
boundingBoxFollowerTable.Add(bbf.gameObject.GetInstanceID(), bbf);
}
static void HierarchyWindowItemOnGUI (int instanceId, Rect selectionRect) {
if (skeletonRendererTable.ContainsKey(instanceId)) {
Rect r = new Rect(selectionRect);
r.x = r.width - 15;
r.width = 15;
GUI.Label(r, Icons.spine);
} else if (skeletonUtilityBoneTable.ContainsKey(instanceId)) {
Rect r = new Rect(selectionRect);
r.x -= 26;
if (skeletonUtilityBoneTable[instanceId] != null) {
if (skeletonUtilityBoneTable[instanceId].transform.childCount == 0)
r.x += 13;
r.y += 2;
r.width = 13;
r.height = 13;
if (skeletonUtilityBoneTable[instanceId].mode == SkeletonUtilityBone.Mode.Follow) {
GUI.DrawTexture(r, Icons.bone);
} else {
GUI.DrawTexture(r, Icons.poseBones);
}
}
} else if (boundingBoxFollowerTable.ContainsKey(instanceId)) {
Rect r = new Rect(selectionRect);
r.x -= 26;
if (boundingBoxFollowerTable[instanceId] != null) {
if (boundingBoxFollowerTable[instanceId].transform.childCount == 0)
r.x += 13;
r.y += 2;
r.width = 13;
r.height = 13;
GUI.DrawTexture(r, Icons.boundingBox);
}
}
}
static void OnPostprocessAllAssets (string[] imported, string[] deleted, string[] moved, string[] movedFromAssetPaths) {
ImportSpineContent(imported, false);
}
public static void ImportSpineContent (string[] imported, bool reimport = false) {
List<string> atlasPaths = new List<string>();
List<string> imagePaths = new List<string>();
List<string> skeletonPaths = new List<string>();
foreach (string str in imported) {
string extension = Path.GetExtension(str).ToLower();
switch (extension) {
case ".txt":
if (str.EndsWith(".atlas.txt")) {
atlasPaths.Add(str);
}
break;
case ".png":
case ".jpg":
imagePaths.Add(str);
break;
case ".json":
if (IsValidSpineData((TextAsset)AssetDatabase.LoadAssetAtPath(str, typeof(TextAsset))))
skeletonPaths.Add(str);
break;
case ".bytes":
if (str.ToLower().EndsWith(".skel.bytes")) {
if (IsValidSpineData((TextAsset)AssetDatabase.LoadAssetAtPath(str, typeof(TextAsset))))
skeletonPaths.Add(str);
}
break;
}
}
List<AtlasAsset> atlases = new List<AtlasAsset>();
//import atlases first
foreach (string ap in atlasPaths) {
if (!reimport && CheckForValidAtlas(ap))
continue;
TextAsset atlasText = (TextAsset)AssetDatabase.LoadAssetAtPath(ap, typeof(TextAsset));
AtlasAsset atlas = IngestSpineAtlas(atlasText);
atlases.Add(atlas);
}
//import skeletons and match them with atlases
bool abortSkeletonImport = false;
foreach (string sp in skeletonPaths) {
if (!reimport && CheckForValidSkeletonData(sp)) {
ResetExistingSkeletonData(sp);
continue;
}
string dir = Path.GetDirectoryName(sp);
var localAtlases = FindAtlasesAtPath(dir);
var requiredPaths = GetRequiredAtlasRegions(sp);
var atlasMatch = GetMatchingAtlas(requiredPaths, localAtlases);
if (atlasMatch != null) {
IngestSpineProject(AssetDatabase.LoadAssetAtPath(sp, typeof(TextAsset)) as TextAsset, atlasMatch);
} else {
bool resolved = false;
while (!resolved) {
int result = EditorUtility.DisplayDialogComplex("Skeleton JSON Import Error!", "Could not find matching AtlasAsset for " + Path.GetFileNameWithoutExtension(sp), "Select", "Skip", "Abort");
switch (result) {
case -1:
Debug.Log("Select Atlas");
AtlasAsset selectedAtlas = GetAtlasDialog(Path.GetDirectoryName(sp));
if (selectedAtlas != null) {
localAtlases.Clear();
localAtlases.Add(selectedAtlas);
atlasMatch = GetMatchingAtlas(requiredPaths, localAtlases);
if (atlasMatch != null) {
resolved = true;
IngestSpineProject(AssetDatabase.LoadAssetAtPath(sp, typeof(TextAsset)) as TextAsset, atlasMatch);
}
}
break;
case 0:
var atlasList = MultiAtlasDialog(requiredPaths, Path.GetDirectoryName(sp), Path.GetFileNameWithoutExtension(sp));
if (atlasList != null)
IngestSpineProject(AssetDatabase.LoadAssetAtPath(sp, typeof(TextAsset)) as TextAsset, atlasList.ToArray());
resolved = true;
break;
case 1:
Debug.Log("Skipped importing: " + Path.GetFileName(sp));
resolved = true;
break;
case 2:
//abort
abortSkeletonImport = true;
resolved = true;
break;
}
}
}
if (abortSkeletonImport)
break;
}
//TODO: any post processing of images
}
static bool CheckForValidSkeletonData (string skeletonJSONPath) {
string dir = Path.GetDirectoryName(skeletonJSONPath);
TextAsset textAsset = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonJSONPath, typeof(TextAsset));
DirectoryInfo dirInfo = new DirectoryInfo(dir);
FileInfo[] files = dirInfo.GetFiles("*.asset");
foreach (var f in files) {
string localPath = dir + "/" + f.Name;
var obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object));
if (obj is SkeletonDataAsset) {
var skeletonDataAsset = (SkeletonDataAsset)obj;
if (skeletonDataAsset.skeletonJSON == textAsset)
return true;
}
}
return false;
}
static void ResetExistingSkeletonData (string skeletonJSONPath) {
string dir = Path.GetDirectoryName(skeletonJSONPath);
TextAsset textAsset = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonJSONPath, typeof(TextAsset));
DirectoryInfo dirInfo = new DirectoryInfo(dir);
FileInfo[] files = dirInfo.GetFiles("*.asset");
foreach (var f in files) {
string localPath = dir + "/" + f.Name;
var obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object));
if (obj is SkeletonDataAsset) {
var skeletonDataAsset = (SkeletonDataAsset)obj;
if (skeletonDataAsset.skeletonJSON == textAsset) {
if (Selection.activeObject == skeletonDataAsset)
Selection.activeObject = null;
skeletonDataAsset.Reset();
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(skeletonDataAsset));
string lastHash = EditorPrefs.GetString(guid + "_hash");
if (lastHash != skeletonDataAsset.GetSkeletonData(true).Hash) {
//do any upkeep on synchronized assets
UpdateMecanimClips(skeletonDataAsset);
}
EditorPrefs.SetString(guid + "_hash", skeletonDataAsset.GetSkeletonData(true).Hash);
}
}
}
}
static void UpdateMecanimClips (SkeletonDataAsset skeletonDataAsset) {
if (skeletonDataAsset.controller == null)
return;
SkeletonBaker.GenerateMecanimAnimationClips(skeletonDataAsset);
}
static bool CheckForValidAtlas (string atlasPath) {
return false;
//////////////DEPRECATED - always check for new atlas data now
/*
string dir = Path.GetDirectoryName(atlasPath);
TextAsset textAsset = (TextAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(TextAsset));
DirectoryInfo dirInfo = new DirectoryInfo(dir);
FileInfo[] files = dirInfo.GetFiles("*.asset");
foreach (var f in files) {
string localPath = dir + "/" + f.Name;
var obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object));
if (obj is AtlasAsset) {
var atlasAsset = (AtlasAsset)obj;
if (atlasAsset.atlasFile == textAsset) {
Atlas atlas = atlasAsset.GetAtlas();
FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic);
List<AtlasRegion> regions = (List<AtlasRegion>)field.GetValue(atlas);
string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset);
string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath);
string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name);
for (int i = 0; i < regions.Count; i++) {
AtlasRegion region = regions[i];
string bakedPrefabPath = Path.Combine(bakedDirPath, SpineEditorUtilities.GetPathSafeRegionName(region) + ".prefab").Replace("\\", "/");
GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject));
if (prefab != null) {
Debug.Log("Updating: " + region.name);
BakeRegion(atlasAsset, region);
}
}
return true;
}
}
}
return false;
*/
}
static List<AtlasAsset> MultiAtlasDialog (List<string> requiredPaths, string initialDirectory, string header = "") {
List<AtlasAsset> atlasAssets = new List<AtlasAsset>();
bool resolved = false;
string lastAtlasPath = initialDirectory;
while (!resolved) {
StringBuilder sb = new StringBuilder();
sb.AppendLine(header);
sb.AppendLine("Atlases:");
if (atlasAssets.Count == 0) {
sb.AppendLine("\t--none--");
}
for (int i = 0; i < atlasAssets.Count; i++) {
sb.AppendLine("\t" + atlasAssets[i].name);
}
sb.AppendLine();
sb.AppendLine("Missing Regions:");
List<string> missingRegions = new List<string>(requiredPaths);
foreach (var atlasAsset in atlasAssets) {
var atlas = atlasAsset.GetAtlas();
for (int i = 0; i < missingRegions.Count; i++) {
if (atlas.FindRegion(missingRegions[i]) != null) {
missingRegions.RemoveAt(i);
i--;
}
}
}
if (missingRegions.Count == 0) {
break;
}
for (int i = 0; i < missingRegions.Count; i++) {
sb.AppendLine("\t" + missingRegions[i]);
}
int result = EditorUtility.DisplayDialogComplex("Atlas Selection", sb.ToString(), "Select", "Finish", "Abort");
switch (result) {
case 0:
AtlasAsset selectedAtlasAsset = GetAtlasDialog(lastAtlasPath);
if (selectedAtlasAsset != null) {
var atlas = selectedAtlasAsset.GetAtlas();
bool hasValidRegion = false;
foreach (string str in missingRegions) {
if (atlas.FindRegion(str) != null) {
hasValidRegion = true;
break;
}
}
atlasAssets.Add(selectedAtlasAsset);
}
break;
case 1:
resolved = true;
break;
case 2:
atlasAssets = null;
resolved = true;
break;
}
}
return atlasAssets;
}
static AtlasAsset GetAtlasDialog (string dirPath) {
string path = EditorUtility.OpenFilePanel("Select AtlasAsset...", dirPath, "asset");
if (path == "")
return null;
int subLen = Application.dataPath.Length - 6;
string assetRelativePath = path.Substring(subLen, path.Length - subLen).Replace("\\", "/");
Object obj = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(AtlasAsset));
if (obj == null || obj.GetType() != typeof(AtlasAsset))
return null;
return (AtlasAsset)obj;
}
static void AddRequiredAtlasRegionsFromBinary (string skeletonDataPath, List<string> requiredPaths) {
SkeletonBinary binary = new SkeletonBinary(new AtlasRequirementLoader(requiredPaths));
TextAsset data = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonDataPath, typeof(TextAsset));
MemoryStream input = new MemoryStream(data.bytes);
binary.ReadSkeletonData(input);
binary = null;
}
public static List<string> GetRequiredAtlasRegions (string skeletonDataPath) {
List<string> requiredPaths = new List<string>();
if (skeletonDataPath.Contains(".skel")) {
AddRequiredAtlasRegionsFromBinary(skeletonDataPath, requiredPaths);
return requiredPaths;
}
TextAsset spineJson = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonDataPath, typeof(TextAsset));
StringReader reader = new StringReader(spineJson.text);
var root = Json.Deserialize(reader) as Dictionary<string, object>;
foreach (KeyValuePair<string, object> entry in (Dictionary<string, object>)root["skins"]) {
foreach (KeyValuePair<string, object> slotEntry in (Dictionary<string, object>)entry.Value) {
foreach (KeyValuePair<string, object> attachmentEntry in ((Dictionary<string, object>)slotEntry.Value)) {
var data = ((Dictionary<string, object>)attachmentEntry.Value);
if (data.ContainsKey("type")) {
if ((string)data["type"] == "boundingbox") {
continue;
}
}
if (data.ContainsKey("path"))
requiredPaths.Add((string)data["path"]);
else if (data.ContainsKey("name"))
requiredPaths.Add((string)data["name"]);
else
requiredPaths.Add(attachmentEntry.Key);
//requiredPaths.Add((string)sdf["path"]);
}
}
}
return requiredPaths;
}
static AtlasAsset GetMatchingAtlas (List<string> requiredPaths, List<AtlasAsset> atlasAssets) {
AtlasAsset atlasAssetMatch = null;
foreach (AtlasAsset a in atlasAssets) {
Atlas atlas = a.GetAtlas();
bool failed = false;
foreach (string regionPath in requiredPaths) {
if (atlas.FindRegion(regionPath) == null) {
failed = true;
break;
}
}
if (!failed) {
atlasAssetMatch = a;
break;
}
}
return atlasAssetMatch;
}
static List<AtlasAsset> FindAtlasesAtPath (string path) {
List<AtlasAsset> arr = new List<AtlasAsset>();
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] assetInfoArr = dir.GetFiles("*.asset");
int subLen = Application.dataPath.Length - 6;
foreach (var f in assetInfoArr) {
string assetRelativePath = f.FullName.Substring(subLen, f.FullName.Length - subLen).Replace("\\", "/");
Object obj = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(AtlasAsset));
if (obj != null) {
arr.Add(obj as AtlasAsset);
}
}
return arr;
}
public static bool IsValidSpineData (TextAsset asset) {
if (asset.name.Contains(".skel")) return true;
object obj = null;
try {
obj = Json.Deserialize(new StringReader(asset.text));
} catch (System.Exception) {
}
if (obj == null) {
Debug.LogError("Is not valid JSON");
return false;
}
Dictionary<string, object> root = (Dictionary<string, object>)obj;
if (!root.ContainsKey("skeleton"))
return false;
Dictionary<string, object> skeletonInfo = (Dictionary<string, object>)root["skeleton"];
string spineVersion = (string)skeletonInfo["spine"];
//TODO: reject old versions
return true;
}
static AtlasAsset IngestSpineAtlas (TextAsset atlasText) {
if (atlasText == null) {
Debug.LogWarning("Atlas source cannot be null!");
return null;
}
string primaryName = Path.GetFileNameWithoutExtension(atlasText.name).Replace(".atlas", "");
string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(atlasText));
string atlasPath = assetPath + "/" + primaryName + "_Atlas.asset";
AtlasAsset atlasAsset = (AtlasAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAsset));
List<Material> vestigialMaterials = new List<Material>();
if (atlasAsset == null)
atlasAsset = AtlasAsset.CreateInstance<AtlasAsset>();
else {
foreach (Material m in atlasAsset.materials)
vestigialMaterials.Add(m);
}
atlasAsset.atlasFile = atlasText;
//strip CR
string atlasStr = atlasText.text;
atlasStr = atlasStr.Replace("\r", "");
string[] atlasLines = atlasStr.Split('\n');
List<string> pageFiles = new List<string>();
for (int i = 0; i < atlasLines.Length - 1; i++) {
if (atlasLines[i].Length == 0)
pageFiles.Add(atlasLines[i + 1]);
}
atlasAsset.materials = new Material[pageFiles.Count];
for (int i = 0; i < pageFiles.Count; i++) {
string texturePath = assetPath + "/" + pageFiles[i];
Texture2D texture = (Texture2D)AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D));
TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath);
texImporter.textureType = TextureImporterType.Advanced;
texImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;
texImporter.mipmapEnabled = false;
texImporter.alphaIsTransparency = false;
texImporter.maxTextureSize = 2048;
EditorUtility.SetDirty(texImporter);
AssetDatabase.ImportAsset(texturePath);
AssetDatabase.SaveAssets();
string pageName = Path.GetFileNameWithoutExtension(pageFiles[i]);
//because this looks silly
if (pageName == primaryName && pageFiles.Count == 1)
pageName = "Material";
string materialPath = assetPath + "/" + primaryName + "_" + pageName + ".mat";
Material mat = (Material)AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material));
if (mat == null) {
mat = new Material(Shader.Find(defaultShader));
AssetDatabase.CreateAsset(mat, materialPath);
} else {
vestigialMaterials.Remove(mat);
}
mat.mainTexture = texture;
EditorUtility.SetDirty(mat);
AssetDatabase.SaveAssets();
atlasAsset.materials[i] = mat;
}
for (int i = 0; i < vestigialMaterials.Count; i++)
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(vestigialMaterials[i]));
if (AssetDatabase.GetAssetPath(atlasAsset) == "")
AssetDatabase.CreateAsset(atlasAsset, atlasPath);
else
atlasAsset.Reset();
EditorUtility.SetDirty(atlasAsset);
AssetDatabase.SaveAssets();
//iterate regions and bake marked
Atlas atlas = atlasAsset.GetAtlas();
FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic);
List<AtlasRegion> regions = (List<AtlasRegion>)field.GetValue(atlas);
string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset);
string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath);
string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name);
bool hasBakedRegions = false;
for (int i = 0; i < regions.Count; i++) {
AtlasRegion region = regions[i];
string bakedPrefabPath = Path.Combine(bakedDirPath, SpineEditorUtilities.GetPathSafeRegionName(region) + ".prefab").Replace("\\", "/");
GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject));
if (prefab != null) {
BakeRegion(atlasAsset, region, false);
hasBakedRegions = true;
}
}
if (hasBakedRegions) {
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
return (AtlasAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAsset));
}
public static GameObject BakeRegion (AtlasAsset atlasAsset, AtlasRegion region, bool autoSave = true) {
Atlas atlas = atlasAsset.GetAtlas();
string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset);
string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath);
string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name);
string bakedPrefabPath = Path.Combine(bakedDirPath, GetPathSafeRegionName(region) + ".prefab").Replace("\\", "/");
GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject));
GameObject root;
Mesh mesh;
bool isNewPrefab = false;
if (!Directory.Exists(bakedDirPath))
Directory.CreateDirectory(bakedDirPath);
if (prefab == null) {
root = new GameObject("temp", typeof(MeshFilter), typeof(MeshRenderer));
prefab = (GameObject)PrefabUtility.CreatePrefab(bakedPrefabPath, root);
isNewPrefab = true;
Object.DestroyImmediate(root);
}
mesh = (Mesh)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(Mesh));
Material mat = null;
mesh = atlasAsset.GenerateMesh(region.name, mesh, out mat);
if (isNewPrefab) {
AssetDatabase.AddObjectToAsset(mesh, prefab);
prefab.GetComponent<MeshFilter>().sharedMesh = mesh;
}
EditorUtility.SetDirty(mesh);
EditorUtility.SetDirty(prefab);
if (autoSave) {
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
prefab.GetComponent<MeshRenderer>().sharedMaterial = mat;
return prefab;
}
public static string GetPathSafeRegionName (AtlasRegion region) {
return region.name.Replace("/", "_");
}
static SkeletonDataAsset IngestSpineProject (TextAsset spineJson, params AtlasAsset[] atlasAssets) {
string primaryName = Path.GetFileNameWithoutExtension(spineJson.name);
string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(spineJson));
string filePath = assetPath + "/" + primaryName + "_SkeletonData.asset";
if (spineJson != null && atlasAssets != null) {
SkeletonDataAsset skelDataAsset = (SkeletonDataAsset)AssetDatabase.LoadAssetAtPath(filePath, typeof(SkeletonDataAsset));
if (skelDataAsset == null) {
skelDataAsset = SkeletonDataAsset.CreateInstance<SkeletonDataAsset>();
skelDataAsset.atlasAssets = atlasAssets;
skelDataAsset.skeletonJSON = spineJson;
skelDataAsset.fromAnimation = new string[0];
skelDataAsset.toAnimation = new string[0];
skelDataAsset.duration = new float[0];
skelDataAsset.defaultMix = defaultMix;
skelDataAsset.scale = defaultScale;
AssetDatabase.CreateAsset(skelDataAsset, filePath);
AssetDatabase.SaveAssets();
} else {
skelDataAsset.atlasAssets = atlasAssets;
skelDataAsset.Reset();
skelDataAsset.GetSkeletonData(true);
}
return skelDataAsset;
} else {
EditorUtility.DisplayDialog("Error!", "Must specify both Spine JSON and AtlasAsset array", "OK");
return null;
}
}
[MenuItem("Assets/Spine/Instantiate (SkeletonAnimation)")]
static void InstantiateSkeletonAnimation () {
Object[] arr = Selection.objects;
foreach (Object o in arr) {
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(o));
string skinName = EditorPrefs.GetString(guid + "_lastSkin", "");
InstantiateSkeletonAnimation((SkeletonDataAsset)o, skinName);
SceneView.RepaintAll();
}
}
[MenuItem("Assets/Spine/Instantiate (SkeletonAnimation)", true)]
static bool ValidateInstantiateSkeletonAnimation () {
Object[] arr = Selection.objects;
if (arr.Length == 0)
return false;
foreach (Object o in arr) {
if (o.GetType() != typeof(SkeletonDataAsset))
return false;
}
return true;
}
public static SkeletonAnimation InstantiateSkeletonAnimation (SkeletonDataAsset skeletonDataAsset, string skinName) {
return InstantiateSkeletonAnimation(skeletonDataAsset, skeletonDataAsset.GetSkeletonData(true).FindSkin(skinName));
}
public static SkeletonAnimation InstantiateSkeletonAnimation (SkeletonDataAsset skeletonDataAsset, Skin skin = null) {
GameObject go = new GameObject(skeletonDataAsset.name.Replace("_SkeletonData", ""), typeof(MeshFilter), typeof(MeshRenderer), typeof(SkeletonAnimation));
SkeletonAnimation anim = go.GetComponent<SkeletonAnimation>();
anim.skeletonDataAsset = skeletonDataAsset;
bool requiresNormals = false;
foreach (AtlasAsset atlasAsset in anim.skeletonDataAsset.atlasAssets) {
foreach (Material m in atlasAsset.materials) {
if (m.shader.name.Contains("Lit")) {
requiresNormals = true;
break;
}
}
}
anim.calculateNormals = requiresNormals;
SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
if (data == null) {
for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) {
string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]);
skeletonDataAsset.atlasAssets[i] = (AtlasAsset)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAsset));
}
data = skeletonDataAsset.GetSkeletonData(true);
}
if (skin == null)
skin = data.DefaultSkin;
if (skin == null)
skin = data.Skins.Items[0];
anim.Reset();
anim.skeleton.SetSkin(skin);
anim.initialSkinName = skin.Name;
anim.skeleton.Update(1);
anim.state.Update(1);
anim.state.Apply(anim.skeleton);
anim.skeleton.UpdateWorldTransform();
return anim;
}
[MenuItem("Assets/Spine/Instantiate (Mecanim)")]
static void InstantiateSkeletonAnimator () {
Object[] arr = Selection.objects;
foreach (Object o in arr) {
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(o));
string skinName = EditorPrefs.GetString(guid + "_lastSkin", "");
InstantiateSkeletonAnimator((SkeletonDataAsset)o, skinName);
SceneView.RepaintAll();
}
}
[MenuItem("Assets/Spine/Instantiate (SkeletonAnimation)", true)]
static bool ValidateInstantiateSkeletonAnimator () {
Object[] arr = Selection.objects;
if (arr.Length == 0)
return false;
foreach (Object o in arr) {
if (o.GetType() != typeof(SkeletonDataAsset))
return false;
}
return true;
}
public static SkeletonAnimator InstantiateSkeletonAnimator (SkeletonDataAsset skeletonDataAsset, string skinName) {
return InstantiateSkeletonAnimator(skeletonDataAsset, skeletonDataAsset.GetSkeletonData(true).FindSkin(skinName));
}
public static SkeletonAnimator InstantiateSkeletonAnimator (SkeletonDataAsset skeletonDataAsset, Skin skin = null) {
GameObject go = new GameObject(skeletonDataAsset.name.Replace("_SkeletonData", ""), typeof(MeshFilter), typeof(MeshRenderer), typeof(Animator), typeof(SkeletonAnimator));
if (skeletonDataAsset.controller == null) {
SkeletonBaker.GenerateMecanimAnimationClips(skeletonDataAsset);
}
go.GetComponent<Animator>().runtimeAnimatorController = skeletonDataAsset.controller;
SkeletonAnimator anim = go.GetComponent<SkeletonAnimator>();
anim.skeletonDataAsset = skeletonDataAsset;
bool requiresNormals = false;
foreach (AtlasAsset atlasAsset in anim.skeletonDataAsset.atlasAssets) {
foreach (Material m in atlasAsset.materials) {
if (m.shader.name.Contains("Lit")) {
requiresNormals = true;
break;
}
}
}
anim.calculateNormals = requiresNormals;
SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
if (data == null) {
for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) {
string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]);
skeletonDataAsset.atlasAssets[i] = (AtlasAsset)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAsset));
}
data = skeletonDataAsset.GetSkeletonData(true);
}
if (skin == null)
skin = data.DefaultSkin;
if (skin == null)
skin = data.Skins.Items[0];
anim.Reset();
anim.skeleton.SetSkin(skin);
anim.initialSkinName = skin.Name;
anim.skeleton.Update(1);
anim.skeleton.UpdateWorldTransform();
anim.LateUpdate();
return anim;
}
static bool preferencesLoaded = false;
[PreferenceItem("Spine")]
static void PreferencesGUI () {
if (!preferencesLoaded) {
preferencesLoaded = true;
defaultMix = EditorPrefs.GetFloat(DEFAULT_MIX_KEY, 0.2f);
}
EditorGUILayout.LabelField("Auto-Import Settings", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
defaultMix = EditorGUILayout.FloatField("Default Mix", defaultMix);
if (EditorGUI.EndChangeCheck())
EditorPrefs.SetFloat(DEFAULT_MIX_KEY, defaultMix);
GUILayout.Space(20);
EditorGUILayout.LabelField("3rd Party Settings", EditorStyles.boldLabel);
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("TK2D");
if (GUILayout.Button("Enable", GUILayout.Width(64)))
EnableTK2D();
if (GUILayout.Button("Disable", GUILayout.Width(64)))
DisableTK2D();
GUILayout.EndHorizontal();
}
//TK2D Support
const string SPINE_TK2D_DEFINE = "SPINE_TK2D";
static void EnableTK2D () {
bool added = false;
foreach (BuildTargetGroup group in System.Enum.GetValues(typeof(BuildTargetGroup))) {
string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(group);
if (!defines.Contains(SPINE_TK2D_DEFINE)) {
added = true;
if (defines.EndsWith(";"))
defines = defines + SPINE_TK2D_DEFINE;
else
defines = defines + ";" + SPINE_TK2D_DEFINE;
PlayerSettings.SetScriptingDefineSymbolsForGroup(group, defines);
}
}
if (added) {
Debug.LogWarning("Setting Scripting Define Symbol " + SPINE_TK2D_DEFINE);
} else {
Debug.LogWarning("Already Set Scripting Define Symbol " + SPINE_TK2D_DEFINE);
}
}
static void DisableTK2D () {
bool removed = false;
foreach (BuildTargetGroup group in System.Enum.GetValues(typeof(BuildTargetGroup))) {
string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(group);
if (defines.Contains(SPINE_TK2D_DEFINE)) {
removed = true;
if (defines.Contains(SPINE_TK2D_DEFINE + ";"))
defines = defines.Replace(SPINE_TK2D_DEFINE + ";", "");
else
defines = defines.Replace(SPINE_TK2D_DEFINE, "");
PlayerSettings.SetScriptingDefineSymbolsForGroup(group, defines);
}
}
if (removed) {
Debug.LogWarning("Removing Scripting Define Symbol " + SPINE_TK2D_DEFINE);
} else {
Debug.LogWarning("Already Removed Scripting Define Symbol " + SPINE_TK2D_DEFINE);
}
}
public class AtlasRequirementLoader : AttachmentLoader {
List<string> requirementList;
public AtlasRequirementLoader (List<string> requirementList) {
this.requirementList = requirementList;
}
public RegionAttachment NewRegionAttachment (Skin skin, string name, string path) {
requirementList.Add(path);
return new RegionAttachment(name);
}
public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) {
requirementList.Add(path);
return new MeshAttachment(name);
}
public SkinnedMeshAttachment NewSkinnedMeshAttachment (Skin skin, string name, string path) {
requirementList.Add(path);
return new SkinnedMeshAttachment(name);
}
public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name) {
return new BoundingBoxAttachment(name);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// Symbolic names of BCD Elements taken from Geoff Chappell's website:
// http://www.geoffchappell.com/viewer.htm?doc=notes/windows/boot/bcd/elements.htm
//
//
namespace DiscUtils.BootConfig
{
/// <summary>
/// Enumeration of known BCD elements.
/// </summary>
public enum WellKnownElement : int
{
/// <summary>
/// Not specified.
/// </summary>
None = 0,
/// <summary>
/// Device containing the application.
/// </summary>
LibraryApplicationDevice = 0x11000001,
/// <summary>
/// Path to the application.
/// </summary>
LibraryApplicationPath = 0x12000002,
/// <summary>
/// Description of the object.
/// </summary>
LibraryDescription = 0x12000004,
/// <summary>
/// Preferred locale of the object.
/// </summary>
LibraryPreferredLocale = 0x12000005,
/// <summary>
/// Objects containing elements inherited by the object.
/// </summary>
LibraryInheritedObjects = 0x14000006,
/// <summary>
/// Upper bound on physical addresses used by Windows.
/// </summary>
LibraryTruncatePhysicalMemory = 0x15000007,
/// <summary>
/// List of objects, indicating recovery sequence.
/// </summary>
LibraryRecoverySequence = 0x14000008,
/// <summary>
/// Enables auto recovery.
/// </summary>
LibraryAutoRecoveryEnabled = 0x16000009,
/// <summary>
/// List of bad memory regions.
/// </summary>
LibraryBadMemoryList = 0x1700000A,
/// <summary>
/// Allow use of bad memory regions.
/// </summary>
LibraryAllowBadMemoryAccess = 0x1600000B,
/// <summary>
/// Policy on use of first mega-byte of physical RAM.
/// </summary>
/// <remarks>0 = UseNone, 1 = UseAll, 2 = UsePrivate.</remarks>
LibraryFirstMegaBytePolicy = 0x1500000C,
/// <summary>
/// Debugger enabled.
/// </summary>
LibraryDebuggerEnabled = 0x16000010,
/// <summary>
/// Debugger type.
/// </summary>
/// <remarks>0 = Serial, 1 = 1394, 2 = USB.</remarks>
LibraryDebuggerType = 0x15000011,
/// <summary>
/// Debugger serial port address.
/// </summary>
LibraryDebuggerSerialAddress = 0x15000012,
/// <summary>
/// Debugger serial port.
/// </summary>
LibraryDebuggerSerialPort = 0x15000013,
/// <summary>
/// Debugger serial port baud rate.
/// </summary>
LibraryDebuggerSerialBaudRate = 0x15000014,
/// <summary>
/// Debugger 1394 channel.
/// </summary>
LibraryDebugger1394Channel = 0x15000015,
/// <summary>
/// Debugger USB target name.
/// </summary>
LibraryDebuggerUsbTargetName = 0x12000016,
/// <summary>
/// Debugger ignores user mode exceptions.
/// </summary>
LibraryDebuggerIgnoreUserModeExceptions = 0x16000017,
/// <summary>
/// Debugger start policy.
/// </summary>
/// <remarks>0 = Active, 1 = AutoEnable, 2 = Disable.</remarks>
LibraryDebuggerStartPolicy = 0x15000018,
/// <summary>
/// Emergency Management System enabled.
/// </summary>
LibraryEmergencyManagementSystemEnabled = 0x16000020,
/// <summary>
/// Emergency Management System serial port.
/// </summary>
LibraryEmergencyManagementSystemPort = 0x15000022,
/// <summary>
/// Emergency Management System baud rate.
/// </summary>
LibraryEmergencyManagementSystemBaudRate = 0x15000023,
/// <summary>
/// Load options.
/// </summary>
LibraryLoadOptions = 0x12000030,
/// <summary>
/// Displays advanced options.
/// </summary>
LibraryDisplayAdvancedOptions = 0x16000040,
/// <summary>
/// Displays UI to edit advanced options.
/// </summary>
LibraryDisplayOptionsEdit = 0x16000041,
/// <summary>
/// FVE (Full Volume Encryption - aka BitLocker?) KeyRing address.
/// </summary>
LibraryFveKeyRingAddress = 0x16000042,
/// <summary>
/// Device to contain Boot Status Log.
/// </summary>
LibraryBootStatusLogDevice = 0x11000043,
/// <summary>
/// Path to Boot Status Log.
/// </summary>
LibraryBootStatusLogFile = 0x12000044,
/// <summary>
/// Whether to append to the existing Boot Status Log.
/// </summary>
LibraryBootStatusLogAppend = 0x12000045,
/// <summary>
/// Disables graphics mode.
/// </summary>
LibraryGraphicsModeDisabled = 0x16000046,
/// <summary>
/// Configure access policy.
/// </summary>
/// <remarks>0 = default, 1 = DisallowMmConfig.</remarks>
LibraryConfigAccessPolicy = 0x15000047,
/// <summary>
/// Disables integrity checks.
/// </summary>
LibraryDisableIntegrityChecks = 0x16000048,
/// <summary>
/// Allows pre-release signatures (test signing).
/// </summary>
LibraryAllowPrereleaseSignatures = 0x16000049,
/// <summary>
/// Console extended input.
/// </summary>
LibraryConsoleExtendedInput = 0x16000050,
/// <summary>
/// Initial console input.
/// </summary>
LibraryInitialConsoleInput = 0x15000051,
/// <summary>
/// Application display order.
/// </summary>
BootMgrDisplayOrder = 0x24000001,
/// <summary>
/// Application boot sequence.
/// </summary>
BootMgrBootSequence = 0x24000002,
/// <summary>
/// Default application.
/// </summary>
BootMgrDefaultObject = 0x23000003,
/// <summary>
/// User input timeout.
/// </summary>
BootMgrTimeout = 0x25000004,
/// <summary>
/// Attempt to resume from hibernated state.
/// </summary>
BootMgrAttemptResume = 0x26000005,
/// <summary>
/// The resume application.
/// </summary>
BootMgrResumeObject = 0x23000006,
/// <summary>
/// The tools display order.
/// </summary>
BootMgrToolsDisplayOrder = 0x24000010,
/// <summary>
/// Displays the boot menu.
/// </summary>
BootMgrDisplayBootMenu = 0x26000020,
/// <summary>
/// No error display.
/// </summary>
BootMgrNoErrorDisplay = 0x26000021,
/// <summary>
/// The BCD device.
/// </summary>
BootMgrBcdDevice = 0x21000022,
/// <summary>
/// The BCD file path.
/// </summary>
BootMgrBcdFilePath = 0x22000023,
/// <summary>
/// The custom actions list.
/// </summary>
BootMgrCustomActionsList = 0x27000030,
/// <summary>
/// Device containing the Operating System.
/// </summary>
OsLoaderOsDevice = 0x21000001,
/// <summary>
/// System root on the OS device.
/// </summary>
OsLoaderSystemRoot = 0x22000002,
/// <summary>
/// The resume application associated with this OS.
/// </summary>
OsLoaderAssociatedResumeObject = 0x23000003,
/// <summary>
/// Auto-detect the correct kernel & HAL.
/// </summary>
OsLoaderDetectKernelAndHal = 0x26000010,
/// <summary>
/// The filename of the kernel.
/// </summary>
OsLoaderKernelPath = 0x22000011,
/// <summary>
/// The filename of the HAL.
/// </summary>
OsLoaderHalPath = 0x22000012,
/// <summary>
/// The debug transport path.
/// </summary>
OsLoaderDebugTransportPath = 0x22000013,
/// <summary>
/// NX (No-Execute) policy.
/// </summary>
/// <remarks>0 = OptIn, 1 = OptOut, 2 = AlwaysOff, 3 = AlwaysOn.</remarks>
OsLoaderNxPolicy = 0x25000020,
/// <summary>
/// PAE policy.
/// </summary>
/// <remarks>0 = default, 1 = ForceEnable, 2 = ForceDisable.</remarks>
OsLoaderPaePolicy = 0x25000021,
/// <summary>
/// WinPE mode.
/// </summary>
OsLoaderWinPeMode = 0x26000022,
/// <summary>
/// Disable automatic reboot on OS crash.
/// </summary>
OsLoaderDisableCrashAutoReboot = 0x26000024,
/// <summary>
/// Use the last known good settings.
/// </summary>
OsLoaderUseLastGoodSettings = 0x26000025,
/// <summary>
/// Disable integrity checks.
/// </summary>
OsLoaderDisableIntegrityChecks = 0x26000026,
/// <summary>
/// Allows pre-release signatures (test signing).
/// </summary>
OsLoaderAllowPrereleaseSignatures = 0x26000027,
/// <summary>
/// Loads all executables above 4GB boundary.
/// </summary>
OsLoaderNoLowMemory = 0x26000030,
/// <summary>
/// Excludes a given amount of memory from use by Windows.
/// </summary>
OsLoaderRemoveMemory = 0x25000031,
/// <summary>
/// Increases the User Mode virtual address space.
/// </summary>
OsLoaderIncreaseUserVa = 0x25000032,
/// <summary>
/// Size of buffer (in MB) for perfomance data logging.
/// </summary>
OsLoaderPerformanceDataMemory = 0x25000033,
/// <summary>
/// Uses the VGA display driver.
/// </summary>
OsLoaderUseVgaDriver = 0x26000040,
/// <summary>
/// Quiet boot.
/// </summary>
OsLoaderDisableBootDisplay = 0x26000041,
/// <summary>
/// Disables use of the VESA BIOS.
/// </summary>
OsLoaderDisableVesaBios = 0x26000042,
/// <summary>
/// Maximum processors in a single APIC cluster.
/// </summary>
OsLoaderClusterModeAddressing = 0x25000050,
/// <summary>
/// Forces the physical APIC to be used.
/// </summary>
OsLoaderUsePhysicalDestination = 0x26000051,
/// <summary>
/// The largest APIC cluster number the system can use.
/// </summary>
OsLoaderRestrictApicCluster = 0x25000052,
/// <summary>
/// Forces only the boot processor to be used.
/// </summary>
OsLoaderUseBootProcessorOnly = 0x26000060,
/// <summary>
/// The number of processors to be used.
/// </summary>
OsLoaderNumberOfProcessors = 0x25000061,
/// <summary>
/// Use maximum number of processors.
/// </summary>
OsLoaderForceMaxProcessors = 0x26000062,
/// <summary>
/// Processor specific configuration flags.
/// </summary>
OsLoaderProcessorConfigurationFlags = 0x25000063,
/// <summary>
/// Uses BIOS-configured PCI resources.
/// </summary>
OsLoaderUseFirmwarePciSettings = 0x26000070,
/// <summary>
/// Message Signalled Interrupt setting.
/// </summary>
OsLoaderMsiPolicy = 0x25000071,
/// <summary>
/// PCE Express Policy.
/// </summary>
OsLoaderPciExpressPolicy = 0x25000072,
/// <summary>
/// The safe boot option.
/// </summary>
/// <remarks>0 = Minimal, 1 = Network, 2 = DsRepair.</remarks>
OsLoaderSafeBoot = 0x25000080,
/// <summary>
/// Loads the configured alternate shell during a safe boot.
/// </summary>
OsLoaderSafeBootAlternateShell = 0x26000081,
/// <summary>
/// Enables boot log.
/// </summary>
OsLoaderBootLogInitialization = 0x26000090,
/// <summary>
/// Displays diagnostic information during boot.
/// </summary>
OsLoaderVerboseObjectLoadMode = 0x26000091,
/// <summary>
/// Enables the kernel debugger.
/// </summary>
OsLoaderKernelDebuggerEnabled = 0x260000A0,
/// <summary>
/// Causes the kernal to halt early during boot.
/// </summary>
OsLoaderDebuggerHalBreakpoint = 0x260000A1,
/// <summary>
/// Enables Windows Emergency Management System.
/// </summary>
OsLoaderEmsEnabled = 0x260000B0,
/// <summary>
/// Forces a failure on boot.
/// </summary>
OsLoaderForceFailure = 0x250000C0,
/// <summary>
/// The OS failure policy.
/// </summary>
OsLoaderDriverLoadFailurePolicy = 0x250000C1,
/// <summary>
/// The OS boot status policy.
/// </summary>
OsLoaderBootStatusPolicy = 0x250000E0,
/// <summary>
/// The device containing the hibernation file.
/// </summary>
ResumeHiberFileDevice = 0x21000001,
/// <summary>
/// The path to the hibernation file.
/// </summary>
ResumeHiberFilePath = 0x22000002,
/// <summary>
/// Allows resume loader to use custom settings.
/// </summary>
ResumeUseCustomSettings = 0x26000003,
/// <summary>
/// PAE settings for resume application.
/// </summary>
ResumePaeMode = 0x26000004,
/// <summary>
/// An MS-DOS device with containing resume application.
/// </summary>
ResumeAssociatedDosDevice = 0x21000005,
/// <summary>
/// Enables debug option.
/// </summary>
ResumeDebugOptionEnabled = 0x26000006,
/// <summary>
/// The number of iterations to run.
/// </summary>
MemDiagPassCount = 0x25000001,
/// <summary>
/// The test mix.
/// </summary>
MemDiagTestMix = 0x25000002,
/// <summary>
/// The failure count.
/// </summary>
MemDiagFailureCount = 0x25000003,
/// <summary>
/// The tests to fail.
/// </summary>
MemDiagTestToFail = 0x25000004,
/// <summary>
/// BPB string.
/// </summary>
LoaderBpbString = 0x22000001,
/// <summary>
/// Causes a soft PXE reboot.
/// </summary>
StartupPxeSoftReboot = 0x26000001,
/// <summary>
/// PXE application name.
/// </summary>
StartupPxeApplicationName = 0x22000002,
/// <summary>
/// Offset of the RAM disk image.
/// </summary>
DeviceRamDiskImageOffset = 0x35000001,
/// <summary>
/// Client port for TFTP.
/// </summary>
DeviceRamDiskTftpClientPort = 0x35000002,
/// <summary>
/// Device containing the SDI file.
/// </summary>
DeviceRamDiskSdiDevice = 0x31000003,
/// <summary>
/// Path to the SDI file.
/// </summary>
DeviceRamDiskSdiPath = 0x32000004,
/// <summary>
/// Length of the RAM disk image.
/// </summary>
DeviceRamDiskRamDiskImageLength = 0x35000005,
/// <summary>
/// Exports the image as a CD.
/// </summary>
DeviceRamDiskExportAsCd = 0x36000006,
/// <summary>
/// The TFTP transfer block size.
/// </summary>
DeviceRamDiskTftpBlockSize = 0x35000007,
/// <summary>
/// The device type.
/// </summary>
SetupDeviceType = 0x45000001,
/// <summary>
/// The application relative path.
/// </summary>
SetupAppRelativePath = 0x42000002,
/// <summary>
/// The device relative path.
/// </summary>
SetupRamDiskDeviceRelativePath = 0x42000003,
/// <summary>
/// Omit OS loader elements.
/// </summary>
SetupOmitOsLoaderElements = 0x46000004,
/// <summary>
/// Recovery OS flag.
/// </summary>
SetupRecoveryOs = 0x46000010,
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System;
public class DirectorySyncer
{
public delegate void SyncResultDelegate(SyncResult syncResult);
public readonly string Source;
public readonly string Target;
public SyncResultDelegate WillPerformOperations;
private readonly Regex _ignoreExpression;
// helper classes to simplify transition beyond .NET runtime 3.5
public abstract class CancellationToken
{
protected abstract bool _IsCancellationRequested();
public virtual bool IsCancellationRequested
{
get { return _IsCancellationRequested(); }
}
public void ThrowIfCancellationRequested()
{
if (IsCancellationRequested)
{
throw new Exception("Operation Cancelled");
}
}
public static readonly CancellationToken None = new CancellationTokenNone();
private class CancellationTokenNone : CancellationToken
{
protected override bool _IsCancellationRequested()
{
return false;
}
}
}
public class CancellationTokenSource : CancellationToken
{
private bool _isCancelled;
protected override bool _IsCancellationRequested()
{
return _isCancelled;
}
public void Cancel()
{
_isCancelled = true;
}
public CancellationToken Token
{
get { return this; }
}
}
private static string EnsureTrailingDirectorySeparator(string path)
{
return path.EndsWith("" + Path.DirectorySeparatorChar)
? path
: path + Path.DirectorySeparatorChar;
}
private static string CheckedDirectory(string nameInExceptionText, string directory)
{
directory = Path.GetFullPath(directory);
if (!Directory.Exists(directory))
{
throw new ArgumentException(string.Format("{0} is not a valid directory for argument ${1}", directory,
nameInExceptionText));
}
return EnsureTrailingDirectorySeparator(directory);
}
public DirectorySyncer(string source, string target, string ignoreRegExPattern = null)
{
Source = CheckedDirectory("source", source);
Target = CheckedDirectory("target", target);
if (Source.StartsWith(Target, StringComparison.OrdinalIgnoreCase) ||
Target.StartsWith(Source, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(string.Format("Paths must not contain each other (source: {0}, target: {1}",
Source, Target));
}
ignoreRegExPattern = ignoreRegExPattern ?? "^$";
_ignoreExpression = new Regex(ignoreRegExPattern, RegexOptions.IgnoreCase);
}
public class SyncResult
{
public readonly IEnumerable<string> Created;
public readonly IEnumerable<string> Updated;
public readonly IEnumerable<string> Deleted;
public SyncResult(IEnumerable<string> created, IEnumerable<string> updated, IEnumerable<string> deleted)
{
Created = created;
Updated = updated;
Deleted = deleted;
}
}
public bool RelativeFilePathIsRelevant(string relativeFilename)
{
return !_ignoreExpression.IsMatch(relativeFilename);
}
public bool RelativeDirectoryPathIsRelevant(string relativeDirName)
{
// Since our ignore patterns look at file names, they may contain trailing path separators
// In order for paths to match those rules, we add a path separator here
return !_ignoreExpression.IsMatch(EnsureTrailingDirectorySeparator(relativeDirName));
}
private HashSet<string> RelevantRelativeFilesBeneathDirectory(string path, CancellationToken cancellationToken)
{
return new HashSet<string>(Directory.GetFiles(path, "*", SearchOption.AllDirectories)
.TakeWhile((s) => !cancellationToken.IsCancellationRequested)
.Select(p => PathHelper.MakeRelativePath(path, p)).Where(RelativeFilePathIsRelevant));
}
private HashSet<string> RelevantRelativeDirectoriesBeneathDirectory(string path,
CancellationToken cancellationToken)
{
return new HashSet<string>(Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
.TakeWhile((s) => !cancellationToken.IsCancellationRequested)
.Select(p => PathHelper.MakeRelativePath(path, p)).Where(RelativeDirectoryPathIsRelevant));
}
public SyncResult Synchronize()
{
return Synchronize(CancellationToken.None);
}
private void DeleteOutdatedFilesFromTarget(SyncResult syncResult, CancellationToken cancellationToken)
{
var outdatedFiles = syncResult.Updated.Union(syncResult.Deleted);
foreach (var fileName in outdatedFiles)
{
File.Delete(Path.Combine(Target, fileName));
cancellationToken.ThrowIfCancellationRequested();
}
}
[SuppressMessage("ReSharper", "ParameterTypeCanBeEnumerable.Local")]
private void DeleteOutdatedEmptyDirectoriesFromTarget(HashSet<string> sourceDirs, HashSet<string> targetDirs,
CancellationToken cancellationToken)
{
var deleted = targetDirs.Except(sourceDirs).OrderByDescending(s => s);
// By sorting in descending order above, we delete leaf-first,
// this is simpler than collapsing the list above (which would also allow us to run these ops in parallel).
// Assumption is that there are few empty folders to delete
foreach (var dir in deleted)
{
Directory.Delete(Path.Combine(Target, dir));
cancellationToken.ThrowIfCancellationRequested();
}
}
[SuppressMessage("ReSharper", "ParameterTypeCanBeEnumerable.Local")]
private void CreateRelevantDirectoriesAtTarget(HashSet<string> sourceDirs, HashSet<string> targetDirs,
CancellationToken cancellationToken)
{
var created = sourceDirs.Except(targetDirs);
foreach (var dir in created)
{
Directory.CreateDirectory(Path.Combine(Target, dir));
cancellationToken.ThrowIfCancellationRequested();
}
}
private void MoveRelevantFilesToTarget(SyncResult syncResult, CancellationToken cancellationToken)
{
// step 3: we move all new files to target
var newFiles = syncResult.Created.Union(syncResult.Updated);
foreach (var fileName in newFiles)
{
var sourceFileName = Path.Combine(Source, fileName);
var destFileName = Path.Combine(Target, fileName);
// target directory exists due to step CreateRelevantDirectoriesAtTarget()
File.Move(sourceFileName, destFileName);
cancellationToken.ThrowIfCancellationRequested();
}
}
public SyncResult Synchronize(CancellationToken cancellationToken)
{
var sourceDirs = RelevantRelativeDirectoriesBeneathDirectory(Source, cancellationToken);
var targetDirs = RelevantRelativeDirectoriesBeneathDirectory(Target, cancellationToken);
var sourceFiles = RelevantRelativeFilesBeneathDirectory(Source, cancellationToken);
var targetFiles = RelevantRelativeFilesBeneathDirectory(Target, cancellationToken);
var created = sourceFiles.Except(targetFiles).OrderBy(s => s).ToList();
var updated = sourceFiles.Intersect(targetFiles).OrderBy(s => s).ToList();
var deleted = targetFiles.Except(sourceFiles).OrderBy(s => s).ToList();
var syncResult = new SyncResult(created, updated, deleted);
if (WillPerformOperations != null)
{
WillPerformOperations.Invoke(syncResult);
}
DeleteOutdatedFilesFromTarget(syncResult, cancellationToken);
DeleteOutdatedEmptyDirectoriesFromTarget(sourceDirs, targetDirs, cancellationToken);
CreateRelevantDirectoriesAtTarget(sourceDirs, targetDirs, cancellationToken);
MoveRelevantFilesToTarget(syncResult, cancellationToken);
return syncResult;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Net.Http;
using System.Net.Http.HPack;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.FlowControl;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure.PipeWriterHelpers;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2
{
internal class Http2FrameWriter
{
// Literal Header Field without Indexing - Indexed Name (Index 8 - :status)
// This uses C# compiler's ability to refer to static data directly. For more information see https://vcsjones.dev/2019/02/01/csharp-readonly-span-bytes-static
private static ReadOnlySpan<byte> ContinueBytes => new byte[] { 0x08, 0x03, (byte)'1', (byte)'0', (byte)'0' };
private readonly object _writeLock = new object();
private readonly Http2Frame _outgoingFrame;
private readonly Http2HeadersEnumerator _headersEnumerator = new Http2HeadersEnumerator();
private readonly ConcurrentPipeWriter _outputWriter;
private readonly BaseConnectionContext _connectionContext;
private readonly Http2Connection _http2Connection;
private readonly OutputFlowControl _connectionOutputFlowControl;
private readonly string _connectionId;
private readonly KestrelTrace _log;
private readonly ITimeoutControl _timeoutControl;
private readonly MinDataRate? _minResponseDataRate;
private readonly TimingPipeFlusher _flusher;
private readonly DynamicHPackEncoder _hpackEncoder;
// This is only set to true by tests.
private readonly bool _scheduleInline;
private uint _maxFrameSize = Http2PeerSettings.MinAllowedMaxFrameSize;
private byte[] _headerEncodingBuffer;
private long _unflushedBytes;
private bool _completed;
private bool _aborted;
public Http2FrameWriter(
PipeWriter outputPipeWriter,
BaseConnectionContext connectionContext,
Http2Connection http2Connection,
OutputFlowControl connectionOutputFlowControl,
ITimeoutControl timeoutControl,
MinDataRate? minResponseDataRate,
string connectionId,
MemoryPool<byte> memoryPool,
ServiceContext serviceContext)
{
// Allow appending more data to the PipeWriter when a flush is pending.
_outputWriter = new ConcurrentPipeWriter(outputPipeWriter, memoryPool, _writeLock);
_connectionContext = connectionContext;
_http2Connection = http2Connection;
_connectionOutputFlowControl = connectionOutputFlowControl;
_connectionId = connectionId;
_log = serviceContext.Log;
_timeoutControl = timeoutControl;
_minResponseDataRate = minResponseDataRate;
_flusher = new TimingPipeFlusher(timeoutControl, serviceContext.Log);
_flusher.Initialize(_outputWriter);
_outgoingFrame = new Http2Frame();
_headerEncodingBuffer = new byte[_maxFrameSize];
_scheduleInline = serviceContext.Scheduler == PipeScheduler.Inline;
_hpackEncoder = new DynamicHPackEncoder(serviceContext.ServerOptions.AllowResponseHeaderCompression);
}
public void UpdateMaxHeaderTableSize(uint maxHeaderTableSize)
{
lock (_writeLock)
{
_hpackEncoder.UpdateMaxHeaderTableSize(maxHeaderTableSize);
}
}
public void UpdateMaxFrameSize(uint maxFrameSize)
{
lock (_writeLock)
{
if (_maxFrameSize != maxFrameSize)
{
_maxFrameSize = maxFrameSize;
_headerEncodingBuffer = new byte[_maxFrameSize];
}
}
}
public void Complete()
{
lock (_writeLock)
{
if (_completed)
{
return;
}
_completed = true;
_connectionOutputFlowControl.Abort();
_outputWriter.Abort();
}
}
public void Abort(ConnectionAbortedException error)
{
lock (_writeLock)
{
if (_aborted)
{
return;
}
_aborted = true;
_connectionContext.Abort(error);
Complete();
}
}
public ValueTask<FlushResult> FlushAsync(IHttpOutputAborter? outputAborter, CancellationToken cancellationToken)
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
var bytesWritten = _unflushedBytes;
_unflushedBytes = 0;
return _flusher.FlushAsync(_minResponseDataRate, bytesWritten, outputAborter, cancellationToken);
}
}
public ValueTask<FlushResult> Write100ContinueAsync(int streamId)
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
_outgoingFrame.PrepareHeaders(Http2HeadersFrameFlags.END_HEADERS, streamId);
_outgoingFrame.PayloadLength = ContinueBytes.Length;
WriteHeaderUnsynchronized();
_outputWriter.Write(ContinueBytes);
return TimeFlushUnsynchronizedAsync();
}
}
// Optional header fields for padding and priority are not implemented.
/* https://tools.ietf.org/html/rfc7540#section-6.2
+---------------+
|Pad Length? (8)|
+-+-------------+-----------------------------------------------+
|E| Stream Dependency? (31) |
+-+-------------+-----------------------------------------------+
| Weight? (8) |
+-+-------------+-----------------------------------------------+
| Header Block Fragment (*) ...
+---------------------------------------------------------------+
| Padding (*) ...
+---------------------------------------------------------------+
*/
public void WriteResponseHeaders(int streamId, int statusCode, Http2HeadersFrameFlags headerFrameFlags, HttpResponseHeaders headers)
{
lock (_writeLock)
{
if (_completed)
{
return;
}
try
{
_headersEnumerator.Initialize(headers);
_outgoingFrame.PrepareHeaders(headerFrameFlags, streamId);
var buffer = _headerEncodingBuffer.AsSpan();
var done = HPackHeaderWriter.BeginEncodeHeaders(statusCode, _hpackEncoder, _headersEnumerator, buffer, out var payloadLength);
FinishWritingHeaders(streamId, payloadLength, done);
}
// Any exception from the HPack encoder can leave the dynamic table in a corrupt state.
// Since we allow custom header encoders we don't know what type of exceptions to expect.
catch (Exception ex)
{
_log.HPackEncodingError(_connectionId, streamId, ex);
_http2Connection.Abort(new ConnectionAbortedException(ex.Message, ex));
throw new InvalidOperationException(ex.Message, ex); // Report the error to the user if this was the first write.
}
}
}
public ValueTask<FlushResult> WriteResponseTrailersAsync(int streamId, HttpResponseTrailers headers)
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
try
{
_headersEnumerator.Initialize(headers);
_outgoingFrame.PrepareHeaders(Http2HeadersFrameFlags.END_STREAM, streamId);
var buffer = _headerEncodingBuffer.AsSpan();
var done = HPackHeaderWriter.BeginEncodeHeaders(_hpackEncoder, _headersEnumerator, buffer, out var payloadLength);
FinishWritingHeaders(streamId, payloadLength, done);
}
// Any exception from the HPack encoder can leave the dynamic table in a corrupt state.
// Since we allow custom header encoders we don't know what type of exceptions to expect.
catch (Exception ex)
{
_log.HPackEncodingError(_connectionId, streamId, ex);
_http2Connection.Abort(new ConnectionAbortedException(ex.Message, ex));
}
return TimeFlushUnsynchronizedAsync();
}
}
private void FinishWritingHeaders(int streamId, int payloadLength, bool done)
{
var buffer = _headerEncodingBuffer.AsSpan();
_outgoingFrame.PayloadLength = payloadLength;
if (done)
{
_outgoingFrame.HeadersFlags |= Http2HeadersFrameFlags.END_HEADERS;
}
WriteHeaderUnsynchronized();
_outputWriter.Write(buffer.Slice(0, payloadLength));
while (!done)
{
_outgoingFrame.PrepareContinuation(Http2ContinuationFrameFlags.NONE, streamId);
done = HPackHeaderWriter.ContinueEncodeHeaders(_hpackEncoder, _headersEnumerator, buffer, out payloadLength);
_outgoingFrame.PayloadLength = payloadLength;
if (done)
{
_outgoingFrame.ContinuationFlags = Http2ContinuationFrameFlags.END_HEADERS;
}
WriteHeaderUnsynchronized();
_outputWriter.Write(buffer.Slice(0, payloadLength));
}
}
public ValueTask<FlushResult> WriteDataAsync(int streamId, StreamOutputFlowControl flowControl, in ReadOnlySequence<byte> data, bool endStream, bool firstWrite, bool forceFlush)
{
// Logic in this method is replicated in WriteDataAndTrailersAsync.
// Changes here may need to be mirrored in WriteDataAndTrailersAsync.
// The Length property of a ReadOnlySequence can be expensive, so we cache the value.
var dataLength = data.Length;
lock (_writeLock)
{
if (_completed || flowControl.IsAborted)
{
return default;
}
// Zero-length data frames are allowed to be sent immediately even if there is no space available in the flow control window.
// https://httpwg.org/specs/rfc7540.html#rfc.section.6.9.1
if (dataLength != 0 && dataLength > flowControl.Available)
{
return WriteDataAsync(streamId, flowControl, data, dataLength, endStream, firstWrite);
}
// This cast is safe since if dataLength would overflow an int, it's guaranteed to be greater than the available flow control window.
flowControl.Advance((int)dataLength);
WriteDataUnsynchronized(streamId, data, dataLength, endStream);
if (forceFlush)
{
return TimeFlushUnsynchronizedAsync();
}
return default;
}
}
public ValueTask<FlushResult> WriteDataAndTrailersAsync(int streamId, StreamOutputFlowControl flowControl, in ReadOnlySequence<byte> data, bool firstWrite, HttpResponseTrailers headers)
{
// This method combines WriteDataAsync and WriteResponseTrailers.
// Changes here may need to be mirrored in WriteDataAsync.
// The Length property of a ReadOnlySequence can be expensive, so we cache the value.
var dataLength = data.Length;
lock (_writeLock)
{
if (_completed || flowControl.IsAborted)
{
return default;
}
// Zero-length data frames are allowed to be sent immediately even if there is no space available in the flow control window.
// https://httpwg.org/specs/rfc7540.html#rfc.section.6.9.1
if (dataLength != 0 && dataLength > flowControl.Available)
{
return WriteDataAndTrailersAsyncCore(this, streamId, flowControl, data, dataLength, firstWrite, headers);
}
// This cast is safe since if dataLength would overflow an int, it's guaranteed to be greater than the available flow control window.
flowControl.Advance((int)dataLength);
WriteDataUnsynchronized(streamId, data, dataLength, endStream: false);
return WriteResponseTrailersAsync(streamId, headers);
}
static async ValueTask<FlushResult> WriteDataAndTrailersAsyncCore(Http2FrameWriter writer, int streamId, StreamOutputFlowControl flowControl, ReadOnlySequence<byte> data, long dataLength, bool firstWrite, HttpResponseTrailers headers)
{
await writer.WriteDataAsync(streamId, flowControl, data, dataLength, endStream: false, firstWrite);
return await writer.WriteResponseTrailersAsync(streamId, headers);
}
}
/* Padding is not implemented
+---------------+
|Pad Length? (8)|
+---------------+-----------------------------------------------+
| Data (*) ...
+---------------------------------------------------------------+
| Padding (*) ...
+---------------------------------------------------------------+
*/
private void WriteDataUnsynchronized(int streamId, in ReadOnlySequence<byte> data, long dataLength, bool endStream)
{
Debug.Assert(dataLength == data.Length);
// Note padding is not implemented
_outgoingFrame.PrepareData(streamId);
if (dataLength > _maxFrameSize) // Minus padding
{
TrimAndWriteDataUnsynchronized(in data, dataLength, endStream);
return;
}
if (endStream)
{
_outgoingFrame.DataFlags |= Http2DataFrameFlags.END_STREAM;
}
_outgoingFrame.PayloadLength = (int)dataLength; // Plus padding
WriteHeaderUnsynchronized();
data.CopyTo(_outputWriter);
// Plus padding
return;
void TrimAndWriteDataUnsynchronized(in ReadOnlySequence<byte> data, long dataLength, bool endStream)
{
Debug.Assert(dataLength == data.Length);
var dataPayloadLength = (int)_maxFrameSize; // Minus padding
Debug.Assert(dataLength > dataPayloadLength);
var remainingData = data;
do
{
var currentData = remainingData.Slice(0, dataPayloadLength);
_outgoingFrame.PayloadLength = dataPayloadLength; // Plus padding
WriteHeaderUnsynchronized();
foreach (var buffer in currentData)
{
_outputWriter.Write(buffer.Span);
}
// Plus padding
dataLength -= dataPayloadLength;
remainingData = remainingData.Slice(dataPayloadLength);
} while (dataLength > dataPayloadLength);
if (endStream)
{
_outgoingFrame.DataFlags |= Http2DataFrameFlags.END_STREAM;
}
_outgoingFrame.PayloadLength = (int)dataLength; // Plus padding
WriteHeaderUnsynchronized();
foreach (var buffer in remainingData)
{
_outputWriter.Write(buffer.Span);
}
// Plus padding
}
}
private async ValueTask<FlushResult> WriteDataAsync(int streamId, StreamOutputFlowControl flowControl, ReadOnlySequence<byte> data, long dataLength, bool endStream, bool firstWrite)
{
FlushResult flushResult = default;
while (dataLength > 0)
{
ValueTask<object?> availabilityTask;
var writeTask = default(ValueTask<FlushResult>);
lock (_writeLock)
{
if (_completed || flowControl.IsAborted)
{
break;
}
// Observe HTTP/2 backpressure
var actual = flowControl.AdvanceUpToAndWait(dataLength, out availabilityTask);
var shouldFlush = false;
if (actual > 0)
{
if (actual < dataLength)
{
WriteDataUnsynchronized(streamId, data.Slice(0, actual), actual, endStream: false);
data = data.Slice(actual);
dataLength -= actual;
}
else
{
WriteDataUnsynchronized(streamId, data, actual, endStream);
dataLength = 0;
}
// Don't call FlushAsync() with the min data rate, since we time this write while also accounting for
// flow control induced backpressure below.
shouldFlush = true;
}
else if (firstWrite)
{
// If we're facing flow control induced backpressure on the first write for a given stream's response body,
// we make sure to flush the response headers immediately.
shouldFlush = true;
}
if (shouldFlush)
{
if (_minResponseDataRate != null)
{
// Call BytesWrittenToBuffer before FlushAsync() to make testing easier, otherwise the Flush can cause test code to run before the timeout
// control updates and if the test checks for a timeout it can fail
_timeoutControl.BytesWrittenToBuffer(_minResponseDataRate, _unflushedBytes);
}
_unflushedBytes = 0;
writeTask = _flusher.FlushAsync();
}
firstWrite = false;
}
// Avoid timing writes that are already complete. This is likely to happen during the last iteration.
if (availabilityTask.IsCompleted && writeTask.IsCompleted)
{
continue;
}
if (_minResponseDataRate != null)
{
_timeoutControl.StartTimingWrite();
}
// This awaitable releases continuations in FIFO order when the window updates.
// It should be very rare for a continuation to run without any availability.
if (!availabilityTask.IsCompleted)
{
await availabilityTask;
}
flushResult = await writeTask;
if (_minResponseDataRate != null)
{
_timeoutControl.StopTimingWrite();
}
}
if (!_scheduleInline)
{
// Ensure that the application continuation isn't executed inline by ProcessWindowUpdateFrameAsync.
await ThreadPoolAwaitable.Instance;
}
return flushResult;
}
/* https://tools.ietf.org/html/rfc7540#section-6.9
+-+-------------------------------------------------------------+
|R| Window Size Increment (31) |
+-+-------------------------------------------------------------+
*/
public ValueTask<FlushResult> WriteWindowUpdateAsync(int streamId, int sizeIncrement)
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
_outgoingFrame.PrepareWindowUpdate(streamId, sizeIncrement);
WriteHeaderUnsynchronized();
var buffer = _outputWriter.GetSpan(4);
Bitshifter.WriteUInt31BigEndian(buffer, (uint)sizeIncrement, preserveHighestBit: false);
_outputWriter.Advance(4);
return TimeFlushUnsynchronizedAsync();
}
}
/* https://tools.ietf.org/html/rfc7540#section-6.4
+---------------------------------------------------------------+
| Error Code (32) |
+---------------------------------------------------------------+
*/
public ValueTask<FlushResult> WriteRstStreamAsync(int streamId, Http2ErrorCode errorCode)
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
_outgoingFrame.PrepareRstStream(streamId, errorCode);
WriteHeaderUnsynchronized();
var buffer = _outputWriter.GetSpan(4);
BinaryPrimitives.WriteUInt32BigEndian(buffer, (uint)errorCode);
_outputWriter.Advance(4);
return TimeFlushUnsynchronizedAsync();
}
}
/* https://tools.ietf.org/html/rfc7540#section-6.5.1
List of:
+-------------------------------+
| Identifier (16) |
+-------------------------------+-------------------------------+
| Value (32) |
+---------------------------------------------------------------+
*/
public ValueTask<FlushResult> WriteSettingsAsync(List<Http2PeerSetting> settings)
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
_outgoingFrame.PrepareSettings(Http2SettingsFrameFlags.NONE);
var settingsSize = settings.Count * Http2FrameReader.SettingSize;
_outgoingFrame.PayloadLength = settingsSize;
WriteHeaderUnsynchronized();
var buffer = _outputWriter.GetSpan(settingsSize).Slice(0, settingsSize); // GetSpan isn't precise
WriteSettings(settings, buffer);
_outputWriter.Advance(settingsSize);
return TimeFlushUnsynchronizedAsync();
}
}
internal static void WriteSettings(List<Http2PeerSetting> settings, Span<byte> destination)
{
foreach (var setting in settings)
{
BinaryPrimitives.WriteUInt16BigEndian(destination, (ushort)setting.Parameter);
BinaryPrimitives.WriteUInt32BigEndian(destination.Slice(2), setting.Value);
destination = destination.Slice(Http2FrameReader.SettingSize);
}
}
// No payload
public ValueTask<FlushResult> WriteSettingsAckAsync()
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
_outgoingFrame.PrepareSettings(Http2SettingsFrameFlags.ACK);
WriteHeaderUnsynchronized();
return TimeFlushUnsynchronizedAsync();
}
}
/* https://tools.ietf.org/html/rfc7540#section-6.7
+---------------------------------------------------------------+
| |
| Opaque Data (64) |
| |
+---------------------------------------------------------------+
*/
public ValueTask<FlushResult> WritePingAsync(Http2PingFrameFlags flags, in ReadOnlySequence<byte> payload)
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
_outgoingFrame.PreparePing(flags);
Debug.Assert(payload.Length == _outgoingFrame.PayloadLength); // 8
WriteHeaderUnsynchronized();
foreach (var segment in payload)
{
_outputWriter.Write(segment.Span);
}
return TimeFlushUnsynchronizedAsync();
}
}
/* https://tools.ietf.org/html/rfc7540#section-6.8
+-+-------------------------------------------------------------+
|R| Last-Stream-ID (31) |
+-+-------------------------------------------------------------+
| Error Code (32) |
+---------------------------------------------------------------+
| Additional Debug Data (*) | (not implemented)
+---------------------------------------------------------------+
*/
public ValueTask<FlushResult> WriteGoAwayAsync(int lastStreamId, Http2ErrorCode errorCode)
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
_outgoingFrame.PrepareGoAway(lastStreamId, errorCode);
WriteHeaderUnsynchronized();
var buffer = _outputWriter.GetSpan(8);
Bitshifter.WriteUInt31BigEndian(buffer, (uint)lastStreamId, preserveHighestBit: false);
buffer = buffer.Slice(4);
BinaryPrimitives.WriteUInt32BigEndian(buffer, (uint)errorCode);
_outputWriter.Advance(8);
return TimeFlushUnsynchronizedAsync();
}
}
private void WriteHeaderUnsynchronized()
{
_log.Http2FrameSending(_connectionId, _outgoingFrame);
WriteHeader(_outgoingFrame, _outputWriter);
// We assume the payload will be written prior to the next flush.
_unflushedBytes += Http2FrameReader.HeaderLength + _outgoingFrame.PayloadLength;
}
/* https://tools.ietf.org/html/rfc7540#section-4.1
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+=+=============================================================+
| Frame Payload (0...) ...
+---------------------------------------------------------------+
*/
internal static void WriteHeader(Http2Frame frame, PipeWriter output)
{
var buffer = output.GetSpan(Http2FrameReader.HeaderLength);
Bitshifter.WriteUInt24BigEndian(buffer, (uint)frame.PayloadLength);
buffer = buffer.Slice(3);
buffer[0] = (byte)frame.Type;
buffer[1] = frame.Flags;
buffer = buffer.Slice(2);
Bitshifter.WriteUInt31BigEndian(buffer, (uint)frame.StreamId, preserveHighestBit: false);
output.Advance(Http2FrameReader.HeaderLength);
}
private ValueTask<FlushResult> TimeFlushUnsynchronizedAsync()
{
var bytesWritten = _unflushedBytes;
_unflushedBytes = 0;
return _flusher.FlushAsync(_minResponseDataRate, bytesWritten);
}
public bool TryUpdateConnectionWindow(int bytes)
{
lock (_writeLock)
{
return _connectionOutputFlowControl.TryUpdateWindow(bytes);
}
}
public bool TryUpdateStreamWindow(StreamOutputFlowControl flowControl, int bytes)
{
lock (_writeLock)
{
return flowControl.TryUpdateWindow(bytes);
}
}
public void AbortPendingStreamDataWrites(StreamOutputFlowControl flowControl)
{
lock (_writeLock)
{
flowControl.Abort();
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using FileHelpers.Events;
using FileHelpers.Options;
namespace FileHelpers
{
/// <summary>Abstract Base class for the engines of the library:
/// <see cref="FileHelperEngine"/> and
/// <see cref="FileHelperAsyncEngine"/></summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class EngineBase
{
// The default is 4k we use 16k
internal const int DefaultReadBufferSize = 16 * 1024;
internal const int DefaultWriteBufferSize = 16 * 1024;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal IRecordInfo RecordInfo { get; }
#region " Constructor "
/// <summary>
/// Create an engine on record type, with default encoding
/// </summary>
/// <param name="recordType">Class to base engine on</param>
internal EngineBase(Type recordType)
: this(recordType, Encoding.GetEncoding(0)) { }
/// <summary>
/// Create and engine on type with specified encoding
/// </summary>
/// <param name="recordType">Class to base engine on</param>
/// <param name="encoding">encoding of the file</param>
internal EngineBase(Type recordType, Encoding encoding)
{
if (recordType == null)
throw new BadUsageException("The record type can't be null");
if (recordType.IsValueType)
{
throw new BadUsageException($"The record type must be a class, and the type: {recordType.Name} is a struct.");
}
mRecordType = recordType;
RecordInfo = FileHelpers.RecordInfo.Resolve(recordType);
mEncoding = encoding;
CreateRecordOptions();
}
/// <summary>
/// Create an engine on the record info provided
/// </summary>
/// <param name="ri">Record information</param>
internal EngineBase(RecordInfo ri)
{
mRecordType = ri.RecordType;
RecordInfo = ri;
CreateRecordOptions();
}
#endregion
#region " LineNumber "
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal int mLineNumber;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal int mTotalRecords;
/// <include file='FileHelperEngine.docs.xml' path='doc/LineNum/*'/>
public int LineNumber
{
get { return mLineNumber; }
}
#endregion
#region " TotalRecords "
/// <include file='FileHelperEngine.docs.xml' path='doc/TotalRecords/*'/>
public int TotalRecords
{
get { return mTotalRecords; }
}
#endregion
/// <summary>
/// Builds a line with the name of the fields, for a delimited files it
/// uses the same delimiter, for a fixed length field it writes the
/// fields names separated with tabs
/// </summary>
/// <returns>field names structured for the heading of the file</returns>
public string GetFileHeader()
{
var delimiter = "\t";
if (RecordInfo.IsDelimited)
delimiter = ((DelimitedRecordOptions)Options).Delimiter;
var res = new StringBuilder();
for (int i = 0; i < RecordInfo.Fields.Length; i++)
{
if (i > 0)
res.Append(delimiter);
var field = RecordInfo.Fields[i];
res.Append(field.FieldCaption != null
? field.FieldCaption
: field.FieldFriendlyName);
}
return res.ToString();
}
#region " RecordType "
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Type mRecordType;
/// <include file='FileHelperEngine.docs.xml' path='doc/RecordType/*'/>
public Type RecordType
{
get { return mRecordType; }
}
/// <summary>The Read Header in the last Read operation. If any.</summary>
public string HeaderText { get; set; } = string.Empty;
#endregion
#region " FooterText"
/// <summary>The Read Footer in the last Read operation. If any.</summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
protected string mFooterText = string.Empty;
/// <summary>The Read Footer in the last Read operation. If any.</summary>
public string FooterText
{
get { return mFooterText; }
set { mFooterText = value; }
}
internal void WriteFooter(TextWriter writer)
{
if (!string.IsNullOrEmpty(mFooterText))
{
if (mFooterText.EndsWith(NewLineForWrite))
writer.Write(mFooterText);
else
writer.WriteLine(mFooterText);
}
}
#endregion
#region " Encoding "
/// <summary>
/// The encoding to Read and Write the streams.
/// Default is the system's current ANSI code page.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
protected Encoding mEncoding = Encoding.GetEncoding(0);
/// <summary>
/// The encoding to Read and Write the streams.
/// Default is the system's current ANSI code page.
/// </summary>
/// <value>Default is the system's current ANSI code page.</value>
public Encoding Encoding
{
get { return mEncoding; }
set { mEncoding = value; }
}
#endregion
#region " NewLineForWrite "
/// <summary>
/// Newline string to be used when engine writes to file.
/// Default is the system's newline setting (System.Environment.NewLine).
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string mNewLineForWrite = Environment.NewLine;
/// <summary>
/// Newline string to be used when engine writes to file.
/// Default is the system's newline setting (System.Environment.NewLine).
/// </summary>
/// <value>Default is the system's newline setting.</value>
public string NewLineForWrite
{
get { return mNewLineForWrite; }
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("NewLine string must not be null or empty");
mNewLineForWrite = value;
}
}
#endregion
#region " ErrorManager"
/// <summary>This is a common class that manage the errors of the library.</summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
protected ErrorManager mErrorManager = new ErrorManager();
/// <summary>This is a common class that manages the errors of the library.</summary>
/// <remarks>
/// You can find complete information about the errors encountered while processing.
/// For example, you can get the errors, their number and save them to a file, etc.
/// </remarks>
/// <seealso cref="FileHelpers.ErrorManager"/>
public ErrorManager ErrorManager
{
get { return mErrorManager; }
}
/// <summary>
/// Indicates the behavior of the engine when it finds an error.
/// {Shortcut for <seealso cref="FileHelpers.ErrorManager.ErrorMode"/>)
/// </summary>
public ErrorMode ErrorMode
{
get { return mErrorManager.ErrorMode; }
set { mErrorManager.ErrorMode = value; }
}
#endregion
#region " ResetFields "
/// <summary>
/// Reset back to the beginning
/// </summary>
internal void ResetFields()
{
mLineNumber = 0;
mErrorManager.ClearErrors();
mTotalRecords = 0;
}
#endregion
/// <summary>Event handler called to notify progress.</summary>
public event EventHandler<ProgressEventArgs> Progress;
/// <summary>
/// Determine whether a progress call is needed
/// </summary>
protected bool MustNotifyProgress
{
get { return Progress != null; }
}
/// <summary>
/// Raises the Progress Event
/// </summary>
/// <param name="e">The Event Args</param>
protected void OnProgress(ProgressEventArgs e)
{
if (Progress == null)
return;
Progress(this, e);
}
private void CreateRecordOptions()
{
Options = CreateRecordOptionsCore(RecordInfo);
}
internal static RecordOptions CreateRecordOptionsCore(IRecordInfo info)
{
RecordOptions options;
if (info.IsDelimited)
options = new DelimitedRecordOptions(info);
else
options = new FixedRecordOptions(info);
for (int index = 0; index < options.Fields.Count; index++)
{
var field = options.Fields[index];
field.Parent = options;
field.ParentIndex = index;
}
return options;
}
/// <summary>
/// Allows you to change some record layout options at runtime
/// </summary>
public RecordOptions Options { get; private set; }
internal void WriteHeader(TextWriter textWriter)
{
if (!string.IsNullOrEmpty(HeaderText))
{
if (HeaderText.EndsWith(NewLineForWrite))
textWriter.Write(HeaderText);
else
textWriter.WriteLine(HeaderText);
}
}
}
}
| |
//
// FeedUpdater.cs
//
// Authors:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Migo.Net;
using Migo.TaskCore;
using Migo.TaskCore.Collections;
namespace Migo.Syndication
{
public class FeedManager
{
private bool disposed;
private Dictionary<Feed, FeedUpdateTask> update_feed_map;
private TaskList<FeedUpdateTask> update_task_list;
private TaskGroup<FeedUpdateTask> update_task_group;
#region Public Properties and Events
public event Action<FeedItem> ItemAdded;
public event Action<FeedItem> ItemChanged;
public event Action<FeedItem> ItemRemoved;
public event EventHandler FeedsChanged;
#endregion
#region Constructor
public FeedManager ()
{
update_feed_map = new Dictionary<Feed, FeedUpdateTask> ();
update_task_list = new TaskList<FeedUpdateTask> ();
// Limit to 4 feeds downloading at a time
update_task_group = new TaskGroup<FeedUpdateTask> (2, update_task_list);
update_task_group.TaskStopped += OnUpdateTaskStopped;
update_task_group.TaskAssociated += OnUpdateTaskAdded;
// TODO
// Start timeout to refresh feeds every so often
}
#endregion
#region Public Methods
public bool IsUpdating (Feed feed)
{
return update_feed_map.ContainsKey (feed);
}
public Feed CreateFeed (string url, FeedAutoDownload autoDownload)
{
return CreateFeed (url, autoDownload, true);
}
public Feed CreateFeed (string url, FeedAutoDownload autoDownload, bool is_subscribed)
{
Feed feed = null;
url = url.Trim ().TrimEnd ('/');
if (!Feed.Exists (url)) {
feed = new Feed (url, autoDownload);
feed.IsSubscribed = is_subscribed;
feed.Save ();
feed.Update ();
}
return feed;
}
public void QueueUpdate (Feed feed)
{
lock (update_task_group.SyncRoot) {
if (disposed) {
return;
}
if (!update_feed_map.ContainsKey (feed)) {
FeedUpdateTask task = new FeedUpdateTask (feed);
update_feed_map[feed] = task;
lock (update_task_list.SyncRoot) {
update_task_list.Add (task);
}
}
}
}
public void CancelUpdate (Feed feed)
{
lock (update_task_group.SyncRoot) {
if (update_feed_map.ContainsKey (feed)) {
update_feed_map[feed].CancelAsync ();
}
}
}
public void Dispose (System.Threading.AutoResetEvent disposeHandle)
{
lock (update_task_group.SyncRoot) {
if (update_task_group != null) {
//update_task_group.CancelAsync ();
//update_task_group.Handle.WaitOne ();
update_task_group.Dispose ();
//disposeHandle.WaitOne ();
update_task_group.TaskStopped -= OnUpdateTaskStopped;
update_task_group.TaskAssociated -= OnUpdateTaskAdded;
update_task_group = null;
}
update_task_list = null;
disposed = true;
}
}
#endregion
#region Internal Methods
internal void OnFeedsChanged ()
{
EventHandler handler = FeedsChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
internal void OnItemAdded (FeedItem item)
{
Action<FeedItem> handler = ItemAdded;
if (handler != null) {
handler (item);
}
}
internal void OnItemChanged (FeedItem item)
{
Action<FeedItem> handler = ItemChanged;
if (handler != null) {
handler (item);
}
}
internal void OnItemRemoved (FeedItem item)
{
Action<FeedItem> handler = ItemRemoved;
if (handler != null) {
handler (item);
}
}
#endregion
#region Private Methods
private void OnUpdateTaskAdded (object sender, TaskEventArgs<FeedUpdateTask> e)
{
lock (update_task_group.SyncRoot) {
update_task_group.Execute ();
}
}
private void OnUpdateTaskStopped (object sender, TaskEventArgs<FeedUpdateTask> e)
{
lock (update_task_group.SyncRoot) {
FeedUpdateTask fut = e.Task as FeedUpdateTask;
update_feed_map.Remove (fut.Feed);
lock (update_task_list.SyncRoot) {
update_task_list.Remove (e.Task);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using GDIDrawer;
namespace TestGDIDrawer
{
class Program
{
static Random s_rnd = new Random();
static void Main(string[] args)
{
//PositionTests();
//SubscriberTests();
//SLines();
//Lines();
//SBlocks();
//Bezier();
//RandomBlocks();
//ClickEllipses();
//Background();
CenteredRectangleTest();
}
static void CenteredRectangleTest()
{
CDrawer can = new CDrawer(800, 600, false);
can.AddCenteredRectangle(400, 300, 796, 596, Color.Red);
for (int i = 0; i < 500; ++i)
can.AddCenteredRectangle(s_rnd.Next(100, 700), s_rnd.Next(100, 500), s_rnd.Next(5, 190), s_rnd.Next(5, 190), RandColor.GetColor(), s_rnd.Next(6), RandColor.GetColor());
can.Render();
Console.ReadKey();
}
static void PositionTests()
{
CDrawer A = new CDrawer(200, 200);
CDrawer B = new CDrawer(200, 300);
Console.ReadKey();
A.Position = new Point(100, 50);
B.Position = new Point(A.Position.X + A.DrawerWindowSize.Width + 10, 50);
Console.ReadKey();
}
static void SLines()
{
CDrawer can = new CDrawer(800, 600, false);
can.AddLine(10, 10, 790, 590, Color.Red, 2);
for (double d = 0; d < Math.PI * 2; d += Math.PI / 32)
can.AddLine(new Point (400, 300), 50 * d, d);
for (int x = 0; x < 600; x += 5)
{
can.AddLine(0, 600 - x, x, 0, RandColor.GetColor(), 1);
}
can.Render();
Console.ReadKey();
}
static void SubscriberTests()
{
CDrawer can = new CDrawer();
can.MouseMove += new GDIDrawerMouseEvent(MouseMove);
can.MouseLeftClick += new GDIDrawerMouseEvent(LeftClick);
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
while (sw.ElapsedMilliseconds < 10000)
System.Threading.Thread.Sleep(10);
}
static void LeftClick(Point pos, CDrawer dr)
{
dr.AddEllipse(pos.X, pos.Y, 10, 10, Color.Yellow);
}
static void MouseMove(Point pos, CDrawer dr)
{
dr.AddEllipse(pos.X, pos.Y, 5, 5, Color.Red);
}
static void Bezier()
{
CDrawer can = new CDrawer(800, 600, false);
for (int ix = 0; ix < 800; ix += 50)
{
can.AddBezier(0, 600, ix, 0, 800 - ix, 600, 800, 0, Color.Red, 2);
can.AddBezier(0, 0, ix, 0, 800 - ix, 600, 800, 600, Color.Red, 2);
}
can.Render();
Console.ReadKey();
}
static void SBlocks()
{
CDrawer can = new CDrawer(800, 600, false);
for (int i = 0; i < 500; ++i)
{
can.AddCenteredEllipse(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), RandColor.GetColor(), 1, RandColor.GetColor());
can.AddCenteredEllipse(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), RandColor.GetColor(), 1);
can.AddCenteredEllipse(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), RandColor.GetColor());
can.AddCenteredEllipse(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800));
can.AddEllipse(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), RandColor.GetColor(), 1, RandColor.GetColor());
can.AddEllipse(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), RandColor.GetColor(), 1);
can.AddEllipse(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), RandColor.GetColor());
can.AddEllipse(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 800));
try
{
can.AddPolygon(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 300), s_rnd.Next(0, 64), s_rnd.NextDouble() * Math.PI * 2, RandColor.GetColor(), 1, RandColor.GetColor());
can.AddPolygon(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 300), s_rnd.Next(0, 64), s_rnd.NextDouble() * Math.PI * 2, RandColor.GetColor(), 1);
can.AddPolygon(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 300), s_rnd.Next(0, 64), s_rnd.NextDouble() * Math.PI * 2, RandColor.GetColor());
can.AddPolygon(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 300), s_rnd.Next(0, 64), s_rnd.NextDouble() * Math.PI * 2);
can.AddPolygon(s_rnd.Next(0, 800), s_rnd.Next(0, 800), s_rnd.Next(0, 300), s_rnd.Next(0, 64));
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
try
{
can.AddRectangle(s_rnd.Next(-10, 810), s_rnd.Next(-10, 610), s_rnd.Next(-10, 810), s_rnd.Next(-10, 610), RandColor.GetColor(), 1, RandColor.GetColor());
can.AddRectangle(s_rnd.Next(-10, 810), s_rnd.Next(-10, 610), s_rnd.Next(-10, 810), s_rnd.Next(-10, 610), RandColor.GetColor(), 1);
can.AddRectangle(s_rnd.Next(-10, 810), s_rnd.Next(-10, 610), s_rnd.Next(-10, 810), s_rnd.Next(-10, 610), RandColor.GetColor());
can.AddRectangle(s_rnd.Next(-10, 810), s_rnd.Next(-10, 610), s_rnd.Next(-10, 810), s_rnd.Next(-10, 610));
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
try
{
can.AddText("Rats", s_rnd.Next(0, 100), s_rnd.Next (0, 800), s_rnd.Next (0, 600), s_rnd.Next(0, 200), s_rnd.Next (0, 200), RandColor.GetColor());
can.AddText("Rats", s_rnd.Next(0, 100), s_rnd.Next(0, 800), s_rnd.Next(0, 600), s_rnd.Next(0, 200), s_rnd.Next(0, 200));
can.AddText("Rats", s_rnd.Next(0, 100), RandColor.GetColor());
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
can.Render();
Console.ReadKey();
}
static void Lines()
{
CDrawer can = new CDrawer(800, 600, false);
can.Scale = 10;
for (int i = -10; i < can.ScaledWidth + 1; i += 5)
{
for (int j = -10; j < can.ScaledHeight + 1; j += 5)
{
can.AddLine(i, j, can.ScaledWidth + 1 - i, can.ScaledHeight + 1 - j, RandColor.GetKnownColor(), 1);
}
}
can.AddText("check...check.. ", 48);
can.AddText("one two three", 12, -10, -10, 100, 50, Color.White);
can.Render();
Console.ReadKey();
}
static void RandomBlocks()
{
Random rnd = new Random();
CDrawer can = new CDrawer();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Reset();
watch.Start();
can.AddText("Random Known Colors SetBBPixel : 2s", 28, 0, 0, can.ScaledWidth, can.ScaledHeight, Color.White);
can.AddText("Random Known Colors SetBBPixel : 2s", 28, 2, 2, can.ScaledWidth + 2, can.ScaledHeight + 2, Color.Black);
while (watch.ElapsedMilliseconds < 2000)
{
can.SetBBPixel(rnd.Next(can.ScaledWidth), rnd.Next(can.ScaledHeight), RandColor.GetKnownColor());
}
can.Close();
can = new CDrawer(800, 800);
can.Scale = 10;
Console.WriteLine("Random Known Colors SetBBScaledPixel : 2s");
watch.Reset();
watch.Start();
can.AddText("Random Known Colors SetBBScaledPixel : 2s", 24);
while (watch.ElapsedMilliseconds < 2000)
{
can.SetBBScaledPixel(rnd.Next(can.ScaledWidth), rnd.Next(can.ScaledHeight), RandColor.GetKnownColor());
}
can.Close();
}
static void ClickEllipses()
{
Random rnd = new Random();
CDrawer can = new CDrawer();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Reset();
watch.Start();
can.AddText("Random Bounding Box Ellipses : 2s", 28, 0, 0, can.ScaledWidth, can.ScaledHeight, Color.White);
can.AddText("Random Bounding Box Ellipses : 2s", 28, 2, 2, can.ScaledWidth + 2, can.ScaledHeight + 2, Color.Black);
while (watch.ElapsedMilliseconds < 5000)
{
Point p = new Point(rnd.Next(-50, can.ScaledWidth + 50), rnd.Next(-50, can.ScaledHeight - 50));
switch (rnd.Next(6))
{
case 0:
can.AddEllipse(p.X, p.Y, 100, 100);
break;
case 1:
can.AddEllipse(p.X, p.Y, 100, 100, RandColor.GetKnownColor(), rnd.Next(1, 4), RandColor.GetKnownColor());
break;
case 2:
can.AddPolygon(p.X, p.Y, 100, rnd.Next(3, 8));
break;
case 3:
can.AddPolygon(p.X, p.Y, 100, rnd.Next(3, 8), rnd.NextDouble() * Math.PI, RandColor.GetKnownColor(), 2, RandColor.GetKnownColor());
break;
case 4:
can.AddRectangle(p.X, p.Y, 100, 100);
break;
case 5:
can.AddRectangle(p.X, p.Y, 100, 100, RandColor.GetKnownColor(), rnd.Next(1, 4), RandColor.GetKnownColor());
break;
default:
break;
}
System.Threading.Thread.Sleep(100);
}
can.Close();
can = new CDrawer(1000, 400, false);
//System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Reset();
watch.Start();
can.AddText("Random Bounding Box Ellipses : 2s", 28, 0, 0, can.ScaledWidth, can.ScaledHeight, Color.White);
can.AddText("Random Bounding Box Ellipses : 2s", 28, 2, 2, can.ScaledWidth + 2, can.ScaledHeight + 2, Color.Black);
while (watch.ElapsedMilliseconds < 2000)
{
Point p = new Point(rnd.Next(50, can.ScaledWidth - 50), rnd.Next(50, can.ScaledHeight - 50));
can.AddCenteredEllipse(p.X, p.Y, 100, 100, RandColor.GetKnownColor(), 2, Color.White);
can.AddCenteredEllipse(p.X, p.Y, 5, 5, RandColor.GetKnownColor(), 1, Color.Red);
System.Threading.Thread.Sleep(100);
}
can.Render();
System.Threading.Thread.Sleep(1000);
can.Close();
}
static void Background()
{
Console.WriteLine("Resource Picture");
Bitmap bm = new Bitmap(Properties.Resources.jupiter);
CDrawer dr = new CDrawer(bm.Width, bm.Height);
dr.ContinuousUpdate = false;
dr.SetBBPixel(bm.Width / 2, bm.Height / 2, Color.Wheat);
for (int y = 0; y < bm.Height; ++y)
for (int x = 0; x < bm.Width; ++x)
dr.SetBBPixel(x, y, bm.GetPixel(x, y));
dr.Render();
System.Threading.Thread.Sleep(1000);
dr.Close();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERLevel;
namespace ParentLoadSoftDelete.DataAccess.Sql.ERLevel
{
/// <summary>
/// DAL SQL Server implementation of <see cref="IE02_ContinentDal"/>
/// </summary>
public partial class E02_ContinentDal : IE02_ContinentDal
{
private E03_Continent_ChildDto _e03_Continent_Child = new E03_Continent_ChildDto();
private E03_Continent_ReChildDto _e03_Continent_ReChild = new E03_Continent_ReChildDto();
private List<E04_SubContinentDto> _e03_SubContinentColl = new List<E04_SubContinentDto>();
private List<E05_SubContinent_ChildDto> _e05_SubContinent_Child = new List<E05_SubContinent_ChildDto>();
private List<E05_SubContinent_ReChildDto> _e05_SubContinent_ReChild = new List<E05_SubContinent_ReChildDto>();
private List<E06_CountryDto> _e05_CountryColl = new List<E06_CountryDto>();
private List<E07_Country_ChildDto> _e07_Country_Child = new List<E07_Country_ChildDto>();
private List<E07_Country_ReChildDto> _e07_Country_ReChild = new List<E07_Country_ReChildDto>();
private List<E08_RegionDto> _e07_RegionColl = new List<E08_RegionDto>();
private List<E09_Region_ChildDto> _e09_Region_Child = new List<E09_Region_ChildDto>();
private List<E09_Region_ReChildDto> _e09_Region_ReChild = new List<E09_Region_ReChildDto>();
private List<E10_CityDto> _e09_CityColl = new List<E10_CityDto>();
private List<E11_City_ChildDto> _e11_City_Child = new List<E11_City_ChildDto>();
private List<E11_City_ReChildDto> _e11_City_ReChild = new List<E11_City_ReChildDto>();
private List<E12_CityRoadDto> _e11_CityRoadColl = new List<E12_CityRoadDto>();
/// <summary>
/// Gets the E03 Continent Single Object.
/// </summary>
/// <value>A <see cref="E03_Continent_ChildDto"/> object.</value>
public E03_Continent_ChildDto E03_Continent_Child
{
get { return _e03_Continent_Child; }
}
/// <summary>
/// Gets the E03 Continent ASingle Object.
/// </summary>
/// <value>A <see cref="E03_Continent_ReChildDto"/> object.</value>
public E03_Continent_ReChildDto E03_Continent_ReChild
{
get { return _e03_Continent_ReChild; }
}
/// <summary>
/// Gets the E03 SubContinent Objects.
/// </summary>
/// <value>A list of <see cref="E04_SubContinentDto"/>.</value>
public List<E04_SubContinentDto> E03_SubContinentColl
{
get { return _e03_SubContinentColl; }
}
/// <summary>
/// Gets the E05 SubContinent Single Object.
/// </summary>
/// <value>A list of <see cref="E05_SubContinent_ChildDto"/>.</value>
public List<E05_SubContinent_ChildDto> E05_SubContinent_Child
{
get { return _e05_SubContinent_Child; }
}
/// <summary>
/// Gets the E05 SubContinent ASingle Object.
/// </summary>
/// <value>A list of <see cref="E05_SubContinent_ReChildDto"/>.</value>
public List<E05_SubContinent_ReChildDto> E05_SubContinent_ReChild
{
get { return _e05_SubContinent_ReChild; }
}
/// <summary>
/// Gets the E05 Country Objects.
/// </summary>
/// <value>A list of <see cref="E06_CountryDto"/>.</value>
public List<E06_CountryDto> E05_CountryColl
{
get { return _e05_CountryColl; }
}
/// <summary>
/// Gets the E07 Country Single Object.
/// </summary>
/// <value>A list of <see cref="E07_Country_ChildDto"/>.</value>
public List<E07_Country_ChildDto> E07_Country_Child
{
get { return _e07_Country_Child; }
}
/// <summary>
/// Gets the E07 Country ASingle Object.
/// </summary>
/// <value>A list of <see cref="E07_Country_ReChildDto"/>.</value>
public List<E07_Country_ReChildDto> E07_Country_ReChild
{
get { return _e07_Country_ReChild; }
}
/// <summary>
/// Gets the E07 Region Objects.
/// </summary>
/// <value>A list of <see cref="E08_RegionDto"/>.</value>
public List<E08_RegionDto> E07_RegionColl
{
get { return _e07_RegionColl; }
}
/// <summary>
/// Gets the E09 Region Single Object.
/// </summary>
/// <value>A list of <see cref="E09_Region_ChildDto"/>.</value>
public List<E09_Region_ChildDto> E09_Region_Child
{
get { return _e09_Region_Child; }
}
/// <summary>
/// Gets the E09 Region ASingle Object.
/// </summary>
/// <value>A list of <see cref="E09_Region_ReChildDto"/>.</value>
public List<E09_Region_ReChildDto> E09_Region_ReChild
{
get { return _e09_Region_ReChild; }
}
/// <summary>
/// Gets the E09 City Objects.
/// </summary>
/// <value>A list of <see cref="E10_CityDto"/>.</value>
public List<E10_CityDto> E09_CityColl
{
get { return _e09_CityColl; }
}
/// <summary>
/// Gets the E11 City Single Object.
/// </summary>
/// <value>A list of <see cref="E11_City_ChildDto"/>.</value>
public List<E11_City_ChildDto> E11_City_Child
{
get { return _e11_City_Child; }
}
/// <summary>
/// Gets the E11 City ASingle Object.
/// </summary>
/// <value>A list of <see cref="E11_City_ReChildDto"/>.</value>
public List<E11_City_ReChildDto> E11_City_ReChild
{
get { return _e11_City_ReChild; }
}
/// <summary>
/// Gets the E11 CityRoad Objects.
/// </summary>
/// <value>A list of <see cref="E12_CityRoadDto"/>.</value>
public List<E12_CityRoadDto> E11_CityRoadColl
{
get { return _e11_CityRoadColl; }
}
/// <summary>
/// Loads a E02_Continent object from the database.
/// </summary>
/// <param name="continent_ID">The fetch criteria.</param>
/// <returns>A E02_ContinentDto object.</returns>
public E02_ContinentDto Fetch(int continent_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetE02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", continent_ID).DbType = DbType.Int32;
var dr = cmd.ExecuteReader();
return Fetch(dr);
}
}
}
private E02_ContinentDto Fetch(IDataReader data)
{
var e02_Continent = new E02_ContinentDto();
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
e02_Continent.Continent_ID = dr.GetInt32("Continent_ID");
e02_Continent.Continent_Name = dr.GetString("Continent_Name");
}
FetchChildren(dr);
}
return e02_Continent;
}
private void FetchChildren(SafeDataReader dr)
{
dr.NextResult();
if (dr.Read())
FetchE03_Continent_Child(dr);
dr.NextResult();
if (dr.Read())
FetchE03_Continent_ReChild(dr);
dr.NextResult();
while (dr.Read())
{
_e03_SubContinentColl.Add(FetchE04_SubContinent(dr));
}
dr.NextResult();
while (dr.Read())
{
_e05_SubContinent_Child.Add(FetchE05_SubContinent_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_e05_SubContinent_ReChild.Add(FetchE05_SubContinent_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_e05_CountryColl.Add(FetchE06_Country(dr));
}
dr.NextResult();
while (dr.Read())
{
_e07_Country_Child.Add(FetchE07_Country_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_e07_Country_ReChild.Add(FetchE07_Country_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_e07_RegionColl.Add(FetchE08_Region(dr));
}
dr.NextResult();
while (dr.Read())
{
_e09_Region_Child.Add(FetchE09_Region_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_e09_Region_ReChild.Add(FetchE09_Region_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_e09_CityColl.Add(FetchE10_City(dr));
}
dr.NextResult();
while (dr.Read())
{
_e11_City_Child.Add(FetchE11_City_Child(dr));
}
dr.NextResult();
while (dr.Read())
{
_e11_City_ReChild.Add(FetchE11_City_ReChild(dr));
}
dr.NextResult();
while (dr.Read())
{
_e11_CityRoadColl.Add(FetchE12_CityRoad(dr));
}
}
private void FetchE03_Continent_Child(SafeDataReader dr)
{
// Value properties
_e03_Continent_Child.Continent_Child_Name = dr.GetString("Continent_Child_Name");
}
private void FetchE03_Continent_ReChild(SafeDataReader dr)
{
// Value properties
_e03_Continent_ReChild.Continent_Child_Name = dr.GetString("Continent_Child_Name");
}
private E04_SubContinentDto FetchE04_SubContinent(SafeDataReader dr)
{
var e04_SubContinent = new E04_SubContinentDto();
// Value properties
e04_SubContinent.SubContinent_ID = dr.GetInt32("SubContinent_ID");
e04_SubContinent.SubContinent_Name = dr.GetString("SubContinent_Name");
return e04_SubContinent;
}
private E05_SubContinent_ChildDto FetchE05_SubContinent_Child(SafeDataReader dr)
{
var e05_SubContinent_Child = new E05_SubContinent_ChildDto();
// Value properties
e05_SubContinent_Child.SubContinent_Child_Name = dr.GetString("SubContinent_Child_Name");
e05_SubContinent_Child.RowVersion = dr.GetValue("RowVersion") as byte[];
// parent properties
e05_SubContinent_Child.Parent_SubContinent_ID = dr.GetInt32("SubContinent_ID1");
return e05_SubContinent_Child;
}
private E05_SubContinent_ReChildDto FetchE05_SubContinent_ReChild(SafeDataReader dr)
{
var e05_SubContinent_ReChild = new E05_SubContinent_ReChildDto();
// Value properties
e05_SubContinent_ReChild.SubContinent_Child_Name = dr.GetString("SubContinent_Child_Name");
e05_SubContinent_ReChild.RowVersion = dr.GetValue("RowVersion") as byte[];
// parent properties
e05_SubContinent_ReChild.Parent_SubContinent_ID = dr.GetInt32("SubContinent_ID2");
return e05_SubContinent_ReChild;
}
private E06_CountryDto FetchE06_Country(SafeDataReader dr)
{
var e06_Country = new E06_CountryDto();
// Value properties
e06_Country.Country_ID = dr.GetInt32("Country_ID");
e06_Country.Country_Name = dr.GetString("Country_Name");
e06_Country.ParentSubContinentID = dr.GetInt32("Parent_SubContinent_ID");
e06_Country.RowVersion = dr.GetValue("RowVersion") as byte[];
// parent properties
e06_Country.Parent_SubContinent_ID = dr.GetInt32("Parent_SubContinent_ID");
return e06_Country;
}
private E07_Country_ChildDto FetchE07_Country_Child(SafeDataReader dr)
{
var e07_Country_Child = new E07_Country_ChildDto();
// Value properties
e07_Country_Child.Country_Child_Name = dr.GetString("Country_Child_Name");
// parent properties
e07_Country_Child.Parent_Country_ID = dr.GetInt32("Country_ID1");
return e07_Country_Child;
}
private E07_Country_ReChildDto FetchE07_Country_ReChild(SafeDataReader dr)
{
var e07_Country_ReChild = new E07_Country_ReChildDto();
// Value properties
e07_Country_ReChild.Country_Child_Name = dr.GetString("Country_Child_Name");
// parent properties
e07_Country_ReChild.Parent_Country_ID = dr.GetInt32("Country_ID2");
return e07_Country_ReChild;
}
private E08_RegionDto FetchE08_Region(SafeDataReader dr)
{
var e08_Region = new E08_RegionDto();
// Value properties
e08_Region.Region_ID = dr.GetInt32("Region_ID");
e08_Region.Region_Name = dr.GetString("Region_Name");
// parent properties
e08_Region.Parent_Country_ID = dr.GetInt32("Parent_Country_ID");
return e08_Region;
}
private E09_Region_ChildDto FetchE09_Region_Child(SafeDataReader dr)
{
var e09_Region_Child = new E09_Region_ChildDto();
// Value properties
e09_Region_Child.Region_Child_Name = dr.GetString("Region_Child_Name");
// parent properties
e09_Region_Child.Parent_Region_ID = dr.GetInt32("Region_ID1");
return e09_Region_Child;
}
private E09_Region_ReChildDto FetchE09_Region_ReChild(SafeDataReader dr)
{
var e09_Region_ReChild = new E09_Region_ReChildDto();
// Value properties
e09_Region_ReChild.Region_Child_Name = dr.GetString("Region_Child_Name");
// parent properties
e09_Region_ReChild.Parent_Region_ID = dr.GetInt32("Region_ID2");
return e09_Region_ReChild;
}
private E10_CityDto FetchE10_City(SafeDataReader dr)
{
var e10_City = new E10_CityDto();
// Value properties
e10_City.City_ID = dr.GetInt32("City_ID");
e10_City.City_Name = dr.GetString("City_Name");
// parent properties
e10_City.Parent_Region_ID = dr.GetInt32("Parent_Region_ID");
return e10_City;
}
private E11_City_ChildDto FetchE11_City_Child(SafeDataReader dr)
{
var e11_City_Child = new E11_City_ChildDto();
// Value properties
e11_City_Child.City_Child_Name = dr.GetString("City_Child_Name");
// parent properties
e11_City_Child.Parent_City_ID = dr.GetInt32("City_ID1");
return e11_City_Child;
}
private E11_City_ReChildDto FetchE11_City_ReChild(SafeDataReader dr)
{
var e11_City_ReChild = new E11_City_ReChildDto();
// Value properties
e11_City_ReChild.City_Child_Name = dr.GetString("City_Child_Name");
// parent properties
e11_City_ReChild.Parent_City_ID = dr.GetInt32("City_ID2");
return e11_City_ReChild;
}
private E12_CityRoadDto FetchE12_CityRoad(SafeDataReader dr)
{
var e12_CityRoad = new E12_CityRoadDto();
// Value properties
e12_CityRoad.CityRoad_ID = dr.GetInt32("CityRoad_ID");
e12_CityRoad.CityRoad_Name = dr.GetString("CityRoad_Name");
// parent properties
e12_CityRoad.Parent_City_ID = dr.GetInt32("Parent_City_ID");
return e12_CityRoad;
}
/// <summary>
/// Inserts a new E02_Continent object in the database.
/// </summary>
/// <param name="e02_Continent">The E02 Continent DTO.</param>
/// <returns>The new <see cref="E02_ContinentDto"/>.</returns>
public E02_ContinentDto Insert(E02_ContinentDto e02_Continent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddE02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", e02_Continent.Continent_ID).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Continent_Name", e02_Continent.Continent_Name).DbType = DbType.String;
cmd.ExecuteNonQuery();
e02_Continent.Continent_ID = (int)cmd.Parameters["@Continent_ID"].Value;
}
}
return e02_Continent;
}
/// <summary>
/// Updates in the database all changes made to the E02_Continent object.
/// </summary>
/// <param name="e02_Continent">The E02 Continent DTO.</param>
/// <returns>The updated <see cref="E02_ContinentDto"/>.</returns>
public E02_ContinentDto Update(E02_ContinentDto e02_Continent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateE02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", e02_Continent.Continent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Continent_Name", e02_Continent.Continent_Name).DbType = DbType.String;
var rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 0)
throw new DataNotFoundException("E02_Continent");
}
}
return e02_Continent;
}
/// <summary>
/// Deletes the E02_Continent object from database.
/// </summary>
/// <param name="continent_ID">The delete criteria.</param>
public void Delete(int continent_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteE02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", continent_ID).DbType = DbType.Int32;
var rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 0)
throw new DataNotFoundException("E02_Continent");
}
}
}
}
}
| |
using System;
/// <summary>
/// ToInt64(System.Double)
/// </summary>
public class ConvertToInt64_5
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ToInt64(0<double<0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d >= 0.5);
long actual = Convert.ToInt64(d);
long expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt64(1>double>=0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d < 0.5);
long actual = Convert.ToInt64(d);
long expected = 1;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt64(0)");
try
{
double d = 0d;
long actual = Convert.ToInt64(d);
long expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt64(int64.max)");
try
{
long actual = Convert.ToInt64(Int64.MaxValue);
long expected = Int64.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt64(int64.min)");
try
{
long actual = Convert.ToInt64(Int64.MinValue);
long expected = Int64.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("005.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is thrown for value > Int64.MaxValue.");
try
{
double d = (double)Int64.MaxValue + 1;
long i = Convert.ToInt64(d);
TestLibrary.TestFramework.LogError("101.1", "OverflowException is thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is thrown for value < Int64.MinValue");
try
{
// with the length of the min value being around 17 digits and the double going out to 15 or 16 digits
// before rounding, then subtracting one simply isn't enough to force the value to be less than Int64.MaxValue.
// If it is possible that the last two or 3 digits can get dropped and rounding can occur on the thousands, then
// subtracting 10000 is safe bet to be lower
double d = (double)Int64.MinValue - 10000;
long i = Convert.ToInt64(d);
TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToInt64_5 test = new ConvertToInt64_5();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt64_5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Adaptation for high precision colors has been sponsored by
// Liberty Technology Systems, Inc., visit http://lib-sys.com
//
// Liberty Technology Systems, Inc. is the provider of
// PostScript and PDF technology for software developers.
//
//----------------------------------------------------------------------------
using System;
namespace MatterHackers.Agg.Image
{
public class blender_gray : IRecieveBlenderByte
{
public int NumPixelBits { get { return 8; } }
public const byte base_mask = 255;
private const int base_shift = 8;
private static int[] m_Saturate9BitToByte = new int[1 << 9];
private int bytesBetweenPixelsInclusive;
public blender_gray(int bytesBetweenPixelsInclusive)
{
this.bytesBetweenPixelsInclusive = bytesBetweenPixelsInclusive;
if (m_Saturate9BitToByte[2] == 0)
{
for (int i = 0; i < m_Saturate9BitToByte.Length; i++)
{
m_Saturate9BitToByte[i] = Math.Min(i, 255);
}
}
}
public Color PixelToColor(byte[] buffer, int bufferOffset)
{
int value = buffer[bufferOffset];
return new Color(value, value, value, 255);
}
public void CopyPixels(byte[] pDestBuffer, int bufferOffset, Color sourceColor, int count)
{
do
{
int y = (sourceColor.red * 77) + (sourceColor.green * 151) + (sourceColor.blue * 28);
int gray = (y >> 8);
pDestBuffer[bufferOffset] = (byte)gray;
bufferOffset += bytesBetweenPixelsInclusive;
}
while (--count != 0);
}
public void BlendPixel(byte[] pDestBuffer, int bufferOffset, Color sourceColor)
{
int OneOverAlpha = base_mask - sourceColor.alpha;
unchecked
{
int y = (sourceColor.red * 77) + (sourceColor.green * 151) + (sourceColor.blue * 28);
int gray = (y >> 8);
gray = (byte)((((gray - (int)(pDestBuffer[bufferOffset])) * sourceColor.alpha) + ((int)(pDestBuffer[bufferOffset]) << base_shift)) >> base_shift);
pDestBuffer[bufferOffset] = (byte)gray;
}
}
public void BlendPixels(byte[] destBuffer, int bufferOffset,
Color[] sourceColors, int sourceColorsOffset,
byte[] covers, int coversIndex, bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
do
{
BlendPixel(destBuffer, bufferOffset, sourceColors[sourceColorsOffset++]);
bufferOffset += bytesBetweenPixelsInclusive;
}
while (--count != 0);
}
else
{
do
{
sourceColors[sourceColorsOffset].alpha = (byte)((sourceColors[sourceColorsOffset].alpha * cover + 255) >> 8);
BlendPixel(destBuffer, bufferOffset, sourceColors[sourceColorsOffset]);
bufferOffset += bytesBetweenPixelsInclusive;
++sourceColorsOffset;
}
while (--count != 0);
}
}
else
{
do
{
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixel(destBuffer, bufferOffset, sourceColors[sourceColorsOffset]);
}
else
{
Color color = sourceColors[sourceColorsOffset];
color.alpha = (byte)((color.alpha * (cover) + 255) >> 8);
BlendPixel(destBuffer, bufferOffset, color);
}
bufferOffset += bytesBetweenPixelsInclusive;
++sourceColorsOffset;
}
while (--count != 0);
}
}
}
public class blenderGrayFromRed : IRecieveBlenderByte
{
public int NumPixelBits { get { return 8; } }
public const byte base_mask = 255;
private const int base_shift = 8;
private static int[] m_Saturate9BitToByte = new int[1 << 9];
private int bytesBetweenPixelsInclusive;
public blenderGrayFromRed(int bytesBetweenPixelsInclusive)
{
this.bytesBetweenPixelsInclusive = bytesBetweenPixelsInclusive;
if (m_Saturate9BitToByte[2] == 0)
{
for (int i = 0; i < m_Saturate9BitToByte.Length; i++)
{
m_Saturate9BitToByte[i] = Math.Min(i, 255);
}
}
}
public Color PixelToColor(byte[] buffer, int bufferOffset)
{
int value = buffer[bufferOffset];
return new Color(value, value, value, 255);
}
public void CopyPixels(byte[] pDestBuffer, int bufferOffset, Color sourceColor, int count)
{
do
{
pDestBuffer[bufferOffset] = sourceColor.red;
bufferOffset += bytesBetweenPixelsInclusive;
}
while (--count != 0);
}
public void BlendPixel(byte[] pDestBuffer, int bufferOffset, Color sourceColor)
{
int OneOverAlpha = base_mask - sourceColor.alpha;
unchecked
{
byte gray = (byte)((((sourceColor.red - (int)(pDestBuffer[bufferOffset])) * sourceColor.alpha) + ((int)(pDestBuffer[bufferOffset]) << base_shift)) >> base_shift);
pDestBuffer[bufferOffset] = (byte)gray;
}
}
public void BlendPixels(byte[] destBuffer, int bufferOffset,
Color[] sourceColors, int sourceColorsOffset,
byte[] covers, int coversIndex, bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
do
{
BlendPixel(destBuffer, bufferOffset, sourceColors[sourceColorsOffset++]);
bufferOffset += bytesBetweenPixelsInclusive;
}
while (--count != 0);
}
else
{
do
{
sourceColors[sourceColorsOffset].alpha = (byte)((sourceColors[sourceColorsOffset].alpha * cover + 255) >> 8);
BlendPixel(destBuffer, bufferOffset, sourceColors[sourceColorsOffset]);
bufferOffset += bytesBetweenPixelsInclusive;
++sourceColorsOffset;
}
while (--count != 0);
}
}
else
{
do
{
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixel(destBuffer, bufferOffset, sourceColors[sourceColorsOffset]);
}
else
{
Color color = sourceColors[sourceColorsOffset];
color.alpha = (byte)((color.alpha * (cover) + 255) >> 8);
BlendPixel(destBuffer, bufferOffset, color);
}
bufferOffset += bytesBetweenPixelsInclusive;
++sourceColorsOffset;
}
while (--count != 0);
}
}
}
public class blenderGrayClampedMax : IRecieveBlenderByte
{
public int NumPixelBits { get { return 8; } }
public const byte base_mask = 255;
private const int base_shift = 8;
private static int[] m_Saturate9BitToByte = new int[1 << 9];
private int bytesBetweenPixelsInclusive;
public blenderGrayClampedMax(int bytesBetweenPixelsInclusive)
{
this.bytesBetweenPixelsInclusive = bytesBetweenPixelsInclusive;
if (m_Saturate9BitToByte[2] == 0)
{
for (int i = 0; i < m_Saturate9BitToByte.Length; i++)
{
m_Saturate9BitToByte[i] = Math.Min(i, 255);
}
}
}
public Color PixelToColor(byte[] buffer, int bufferOffset)
{
int value = buffer[bufferOffset];
return new Color(value, value, value, 255);
}
public void CopyPixels(byte[] pDestBuffer, int bufferOffset, Color sourceColor, int count)
{
do
{
byte clampedMax = Math.Min(Math.Max(sourceColor.red, Math.Max(sourceColor.green, sourceColor.blue)), (byte)255);
pDestBuffer[bufferOffset] = clampedMax;
bufferOffset += bytesBetweenPixelsInclusive;
}
while (--count != 0);
}
public void BlendPixel(byte[] pDestBuffer, int bufferOffset, Color sourceColor)
{
int OneOverAlpha = base_mask - sourceColor.alpha;
unchecked
{
byte clampedMax = Math.Min(Math.Max(sourceColor.red, Math.Max(sourceColor.green, sourceColor.blue)), (byte)255);
byte gray = (byte)((((clampedMax - (int)(pDestBuffer[bufferOffset])) * sourceColor.alpha) + ((int)(pDestBuffer[bufferOffset]) << base_shift)) >> base_shift);
pDestBuffer[bufferOffset] = (byte)gray;
}
}
public void BlendPixels(byte[] destBuffer, int bufferOffset,
Color[] sourceColors, int sourceColorsOffset,
byte[] covers, int coversIndex, bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
do
{
BlendPixel(destBuffer, bufferOffset, sourceColors[sourceColorsOffset++]);
bufferOffset += bytesBetweenPixelsInclusive;
}
while (--count != 0);
}
else
{
do
{
sourceColors[sourceColorsOffset].alpha = (byte)((sourceColors[sourceColorsOffset].alpha * cover + 255) >> 8);
BlendPixel(destBuffer, bufferOffset, sourceColors[sourceColorsOffset]);
bufferOffset += bytesBetweenPixelsInclusive;
++sourceColorsOffset;
}
while (--count != 0);
}
}
else
{
do
{
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixel(destBuffer, bufferOffset, sourceColors[sourceColorsOffset]);
}
else
{
Color color = sourceColors[sourceColorsOffset];
color.alpha = (byte)((color.alpha * (cover) + 255) >> 8);
BlendPixel(destBuffer, bufferOffset, color);
}
bufferOffset += bytesBetweenPixelsInclusive;
++sourceColorsOffset;
}
while (--count != 0);
}
}
}
/*
//======================================================blender_gray_pre
//template<class ColorT>
struct blender_gray_pre
{
typedef ColorT color_type;
typedef typename color_type::value_type value_type;
typedef typename color_type::calc_type calc_type;
enum base_scale_e { base_shift = color_type::base_shift };
static void blend_pix(value_type* p, int cv,
int alpha, int cover)
{
alpha = color_type::base_mask - alpha;
cover = (cover + 1) << (base_shift - 8);
*p = (value_type)((*p * alpha + cv * cover) >> base_shift);
}
static void blend_pix(value_type* p, int cv,
int alpha)
{
*p = (value_type)(((*p * (color_type::base_mask - alpha)) >> base_shift) + cv);
}
};
//=====================================================apply_gamma_dir_gray
//template<class ColorT, class GammaLut>
class apply_gamma_dir_gray
{
public:
typedef typename ColorT::value_type value_type;
apply_gamma_dir_gray(GammaLut& gamma) : m_gamma(gamma) {}
void operator () (byte* p)
{
*p = m_gamma.dir(*p);
}
private:
GammaLut& m_gamma;
};
//=====================================================apply_gamma_inv_gray
//template<class ColorT, class GammaLut>
class apply_gamma_inv_gray
{
public:
typedef typename ColorT::value_type value_type;
apply_gamma_inv_gray(GammaLut& gamma) : m_gamma(gamma) {}
void operator () (byte* p)
{
*p = m_gamma.inv(*p);
}
private:
GammaLut& m_gamma;
};
*/
}
| |
/* Copyright (c) 2006-2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser [email protected]
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
using System;
using System.Collections;
using System.Text;
using System.Xml;
using Google.GData.Client;
using System.Globalization;
using System.Collections.Generic;
namespace Google.GData.Extensions {
/// <summary>
/// Extensible type used in many places.
/// </summary>
public abstract class ExtensionBase : IExtensionElementFactory, IVersionAware {
private string xmlName;
private string xmlPrefix;
private string xmlNamespace;
private List<XmlNode> unknownChildren;
/// <summary>
/// this holds the attribute list for an extension element
/// </summary>
private SortedList attributes;
private SortedList attributeNamespaces;
/// <summary>
/// constructor
/// </summary>
/// <param name="name">the xml name</param>
/// <param name="prefix">the xml prefix</param>
/// <param name="ns">the xml namespace</param>
protected ExtensionBase(string name, string prefix, string ns) {
this.xmlName = name;
this.xmlPrefix = prefix;
this.xmlNamespace = ns;
}
private VersionInformation versionInfo = new VersionInformation();
internal VersionInformation VersionInfo {
get {
return this.versionInfo;
}
}
/// <summary>
/// returns the major protocol version number this element
/// is working against.
/// </summary>
/// <returns></returns>
public int ProtocolMajor {
get {
return this.versionInfo.ProtocolMajor;
}
set {
this.versionInfo.ProtocolMajor = value;
this.VersionInfoChanged();
}
}
/// <summary>
/// returns the minor protocol version number this element
/// is working against.
/// </summary>
/// <returns></returns>
public int ProtocolMinor {
get {
return this.versionInfo.ProtocolMinor;
}
set {
this.versionInfo.ProtocolMinor = value;
this.VersionInfoChanged();
}
}
/// <summary>
/// virtual to be overloaded by subclasses which are interested in reacting on versioninformation
/// changes
/// </summary>
protected virtual void VersionInfoChanged() {
}
/// <summary>
/// method for subclasses who need to change a namespace for parsing/persistence during runtime
/// </summary>
/// <param name="ns"></param>
protected void SetXmlNamespace(string ns) {
this.xmlNamespace = ns;
}
/// <summary>accesses the Attribute list. The keys are the attribute names
/// the values the attribute values</summary>
/// <returns> </returns>
public SortedList Attributes {
get {
return getAttributes();
}
}
/// <summary>accesses the Attribute list. The keys are the attribute names
/// the values the attribute values</summary>
/// <returns> </returns>
public SortedList AttributeNamespaces {
get {
return getAttributeNamespaces();
}
}
/// <summary>
/// returns the attributes list
/// </summary>
/// <returns>SortedList</returns>
internal SortedList getAttributes() {
if (this.attributes == null) {
this.attributes = new SortedList();
}
return this.attributes;
}
/// <summary>
/// returns the attribute namespace list
/// </summary>
/// <returns>SortedList</returns>
internal SortedList getAttributeNamespaces() {
if (this.attributeNamespaces == null) {
this.attributeNamespaces = new SortedList();
}
return this.attributeNamespaces;
}
#region overloaded for persistence
/// <summary>Returns the constant representing this XML element.</summary>
public string XmlName {
get { return this.xmlName; }
}
/// <summary>Returns the constant representing this XML element.</summary>
public string XmlNameSpace {
get { return this.xmlNamespace; }
}
/// <summary>Returns the constant representing this XML element.</summary>
public string XmlPrefix {
get { return this.xmlPrefix; }
}
/// <summary>
/// debugging helper
/// </summary>
/// <returns></returns>
public override string ToString() {
return base.ToString() + " for: " + XmlNameSpace + "- " + XmlName;
}
/// <summary>
/// returns the list of childnodes that are unknown to the extension
/// used for example for the GD:ExtendedProperty
/// </summary>
/// <returns></returns>
public List<XmlNode> ChildNodes {
get {
if (this.unknownChildren == null) {
this.unknownChildren = new List<XmlNode>();
}
return this.unknownChildren;
}
}
/// <summary>Parses an xml node to create an instance of this object.</summary>
/// <param name="node">the xml parses node, can be NULL</param>
/// <param name="parser">the xml parser to use if we need to dive deeper</param>
/// <returns>the created IExtensionElement object</returns>
public virtual IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) {
Tracing.TraceCall();
ExtensionBase e = null;
if (node != null) {
object localname = node.LocalName;
if (!localname.Equals(this.XmlName) ||
!node.NamespaceURI.Equals(this.XmlNameSpace)) {
return null;
}
}
// memberwise close is fine here, as everything is identical beside the value
e = this.MemberwiseClone() as ExtensionBase;
e.InitInstance(this);
e.ProcessAttributes(node);
e.ProcessChildNodes(node, parser);
return e;
}
/// <summary>
/// used to copy the unknown childnodes for later saving
/// </summary>
public virtual void ProcessChildNodes(XmlNode node, AtomFeedParser parser) {
if (node != null && node.HasChildNodes) {
XmlNode childNode = node.FirstChild;
while (childNode != null) {
if (childNode.NodeType == XmlNodeType.Element) {
this.ChildNodes.Add(childNode);
}
childNode = childNode.NextSibling;
}
}
}
/// <summary>
/// used to copy the attribute lists over
/// </summary>
/// <param name="factory"></param>
protected void InitInstance(ExtensionBase factory) {
this.attributes = null;
this.attributeNamespaces = null;
this.unknownChildren = null;
for (int i = 0; i < factory.getAttributes().Count; i++) {
string name = factory.getAttributes().GetKey(i) as string;
string value = factory.getAttributes().GetByIndex(i) as string;
this.getAttributes().Add(name, value);
}
}
/// <summary>
/// default method override to handle attribute processing
/// the base implementation does process the attributes list
/// and reads all that are in there.
/// </summary>
/// <param name="node">XmlNode with attributes</param>
public virtual void ProcessAttributes(XmlNode node) {
if (node != null && node.Attributes != null) {
for (int i = 0; i < node.Attributes.Count; i++) {
this.getAttributes()[node.Attributes[i].LocalName] = node.Attributes[i].Value;
}
}
return;
}
/// <summary>
/// Persistence method for the EnumConstruct object
/// </summary>
/// <param name="writer">the xmlwriter to write into</param>
public virtual void Save(XmlWriter writer) {
writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace);
if (this.attributes != null) {
for (int i = 0; i < this.getAttributes().Count; i++) {
if (this.getAttributes().GetByIndex(i) != null) {
string name = this.getAttributes().GetKey(i) as string;
string value = Utilities.ConvertToXSDString(this.getAttributes().GetByIndex(i));
string ns = this.getAttributeNamespaces()[name] as string;
if (Utilities.IsPersistable(name) && Utilities.IsPersistable(value)) {
if (ns == null) {
writer.WriteAttributeString(name, value);
} else {
writer.WriteAttributeString(name, ns, value);
}
}
}
}
}
SaveInnerXml(writer);
foreach (XmlNode node in this.ChildNodes) {
if (node != null) {
node.WriteTo(writer);
}
}
writer.WriteEndElement();
}
/// <summary>
/// a subclass that want's to save addtional XML would need to overload this
/// the default implementation does nothing
/// </summary>
/// <param name="writer"></param>
public virtual void SaveInnerXml(XmlWriter writer) {
}
#endregion
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Navigation;
using System.Xml;
using ESRI.ArcLogistics.Services;
using ESRI.ArcLogistics.Utility;
using ESRI.ArcLogistics.Utility.ComponentModel;
namespace ESRI.ArcLogistics.App.Pages
{
/// <summary>
/// The model for the license activation on the license page.
/// </summary>
internal sealed class LicensingViewModel : LoginViewModelBase
{
#region constructors
/// <summary>
/// Initializes a new instance of the LicensingViewModel class.
/// </summary>
/// <param name="messenger">The messenger object to be used for
/// notifications.</param>
/// <param name="workingStatusController">The object to be used for
/// managing application working status.</param>
/// <param name="uriNavigator">The reference to the object to be used
/// for navigating to URI's.</param>
/// <param name="licenseManager">The reference to the license manager
/// object.</param>
public LicensingViewModel(
IMessenger messenger,
IWorkingStatusController workingStatusController,
IUriNavigator uriNavigator,
ILicenseManager licenseManager)
{
Debug.Assert(messenger != null);
Debug.Assert(workingStatusController != null);
Debug.Assert(uriNavigator != null);
Debug.Assert(licenseManager != null);
_licenseManager = licenseManager;
_licenseExpirationChecker = licenseManager.LicenseExpirationChecker;
_messenger = messenger;
_workingStatusController = workingStatusController;
_uriNavigator = uriNavigator;
_licensePageCommands = new LicensePageCommands()
{
CreateAccount = _CreateUrlNavigationCommand(
_licenseManager.LicenseComponent.CreateAccountURL,
_uriNavigator),
RecoverCredentials = _CreateUrlNavigationCommand(
_licenseManager.LicenseComponent.RecoverCredentialsURL,
_uriNavigator),
UpgradeLicense = _CreateUrlNavigationCommand(
_licenseManager.LicenseComponent.UpgradeLicenseURL,
_uriNavigator),
};
this.LicenseActivationStatus = _licenseManager.LicenseActivationStatus;
this.LicenseState = this.LicenseActivationStatus == LicenseActivationStatus.Activated ?
AgsServerState.Authorized : AgsServerState.Unauthorized;
_UpdateExpirationWarningDisplayState();
foreach (var item in EnumHelpers.GetValues<AgsServerState>())
{
this.RegisterHeader(
item,
_licenseManager.LicenseComponent.LoginPrompt);
}
_CreateLoginState();
_CreateConnectedState();
_CreateNotConnectedState();
this.LicensingNotes = _CreateLicensingNotes(
_licenseManager.LicenseComponent.LicensingNotes);
this.TroubleshootingNotes = _CreateTroubleshootingNotes(
_licenseManager.LicenseComponent.TroubleshootingNotes);
_stateFactories = new Dictionary<LicenseActivationStatus, Func<LicenseActivationViewState>>()
{
{
LicenseActivationStatus.None,
() => new LicenseActivationViewState
{
LoginViewState = this.LoginState,
InformationViewState = (object)null,
}
},
{
LicenseActivationStatus.Activated,
() => new LicenseActivationViewState
{
LoginViewState = this.ConnectedState,
InformationViewState = _CreateActivatedState(),
}
},
{
LicenseActivationStatus.Expired,
() => new LicenseActivationViewState
{
LoginViewState = this.LoginState,
InformationViewState = _CreateExpiredState(),
}
},
{
LicenseActivationStatus.WrongCredentials,
() => new LicenseActivationViewState
{
LoginViewState = this.LoginState,
InformationViewState = _CreateWrongCredentialsState(),
}
},
{
LicenseActivationStatus.NoSubscription,
() => new LicenseActivationViewState
{
LoginViewState = this.LoginState,
InformationViewState = _CreateNoSubscriptionState(),
}
},
{
LicenseActivationStatus.Failed,
() => new LicenseActivationViewState
{
LoginViewState = this.NotConnectedState,
InformationViewState = (object)null,
}
},
};
}
#endregion
#region public properties
/// <summary>
/// Gets a document with licensing notes.
/// </summary>
public FlowDocument LicensingNotes
{
get
{
return _licensingNotes;
}
private set
{
if (_licensingNotes != value)
{
_licensingNotes = value;
this.NotifyPropertyChanged(PROPERTY_NAME_LICENSING_NOTES);
}
}
}
/// <summary>
/// Gets a value indicating if the licensing notes document is present.
/// </summary>
[PropertyDependsOn(PROPERTY_NAME_LICENSING_NOTES)]
public bool ShowLicensingNotes
{
get
{
return this.LicensingNotes != null;
}
}
/// <summary>
/// Gets a document with troubleshooting notes.
/// </summary>
public FlowDocument TroubleshootingNotes
{
get
{
return _troubleshootingNotes;
}
private set
{
if (_troubleshootingNotes != value)
{
_troubleshootingNotes = value;
this.NotifyPropertyChanged(PROPERTY_NAME_TROUBLESHOOTING_NOTES);
}
}
}
/// <summary>
/// Gets a value indicating if the troubleshooting notes document is present.
/// </summary>
[PropertyDependsOn(PROPERTY_NAME_TROUBLESHOOTING_NOTES)]
[PropertyDependsOn(PROPERTY_NAME_LICENSE_ACTIVATION_STATUS)]
public bool ShowTroubleshootingNotes
{
get
{
return
this.TroubleshootingNotes != null &&
(this.LicenseActivationStatus == LicenseActivationStatus.WrongCredentials ||
this.LicenseActivationStatus == LicenseActivationStatus.NoSubscription);
}
}
/// <summary>
/// Gets or sets a value indicating license activation status.
/// </summary>
public LicenseActivationStatus LicenseActivationStatus
{
get
{
return _licenseActivationStatus;
}
private set
{
if (_licenseActivationStatus != value)
{
_licenseActivationStatus = value;
this.NotifyPropertyChanged(PROPERTY_NAME_LICENSE_ACTIVATION_STATUS);
}
}
}
/// <summary>
/// Gets a value indicating if the current license is restricted.
/// </summary>
[PropertyDependsOn(PROPERTY_NAME_LICENSE_ACTIVATION_STATUS)]
public bool IsRestricted
{
get
{
var license = _licenseManager.AppLicense;
var result =
license == null ||
license.IsRestricted;
return result;
}
}
/// <summary>
/// Gets reference to the current model for license activation status view.
/// </summary>
[PropertyDependsOn(PROPERTY_NAME_LICENSE_ACTIVATION_STATUS)]
public LicenseActivationViewState CurrentLicenseActivationState
{
get
{
LicenseActivationViewState result = null;
Func<LicenseActivationViewState> state;
if (_stateFactories.TryGetValue(this.LicenseActivationStatus, out state))
{
result = state();
}
return result;
}
}
/// <summary>
/// Gets a value indicating if license expiration warning should be shown
/// for an activated license state.
/// </summary>
[PropertyDependsOn(PROPERTY_NAME_LICENSE_ACTIVATION_STATUS)]
public bool ShowExpirationWarning
{
get
{
var result = _licenseExpirationChecker.LicenseIsExpiring(
_licenseManager.AppLicense,
_licenseManager.AppLicenseValidationDate);
return result;
}
}
/// <summary>
/// Gets a value indicating if the application should display license
/// expiration warning to the user.
/// </summary>
public bool RequiresExpirationWarning
{
get
{
return _requiresExpirationWarning;
}
private set
{
if (_requiresExpirationWarning != value)
{
_requiresExpirationWarning = value;
this.NotifyPropertyChanged(PROPERTY_NAME_REQUIRES_EXPIRATION_WARNING);
}
}
}
#endregion
#region private static methods
/// <summary>
/// Creates command for navigating to the specified URL.
/// </summary>
/// <param name="url">The url to navigate to with the resulting command.</param>
/// <param name="uriNavigator">The uri navigator to be used for navigating to
/// the specified URL.</param>
/// <returns>A new command object for navigating to the specified URL or null
/// if the <paramref name="url"/> is null or empty.</returns>
private static ICommand _CreateUrlNavigationCommand(
string url,
IUriNavigator uriNavigator)
{
if (string.IsNullOrEmpty(url))
{
return null;
}
return new DelegateCommand(_ => uriNavigator.NavigateToUri(url));
}
#endregion
#region private methods
/// <summary>
/// Creates view model for the login state.
/// </summary>
private void _CreateLoginState()
{
this.LoginState = new LoginStateViewModel(
_licensePageCommands,
_ExecuteLogin)
{
Username = _licenseManager.AuthorizedUserName,
};
}
/// <summary>
/// Creates view model for the connected state.
/// </summary>
private void _CreateConnectedState()
{
if (_licenseManager.AppLicense == null)
{
this.ConnectedState = null;
return;
}
var switchUserCommand = new DelegateCommand(_ =>
{
this.LicenseState = AgsServerState.Unauthorized;
this.LicenseActivationStatus = LicenseActivationStatus.None;
this.RequiresExpirationWarning = false;
});
if (!_licenseManager.AppLicense.IsRestricted)
{
switchUserCommand = null;
}
var licenseInfoText = _CreateLicenseInfoText()
.Select(block => ApplyStyle(new FlowDocument(block)))
.ToList();
this.ConnectedState = new ConnectedStateViewModel(
_licensePageCommands,
licenseInfoText)
{
SwitchUserCommand = switchUserCommand,
};
}
/// <summary>
/// Creates view model for the not connected state.
/// </summary>
private void _CreateNotConnectedState()
{
var connectionFailureInfo = new FlowDocument(
new Paragraph(
new Run(App.Current.FindString(
"ArcLogisticsLicenseServiceUnavailableText")
)
)
);
ApplyStyle(connectionFailureInfo);
this.NotConnectedState = new NotConnectedStateViewModel()
{
ConnectionFailureInfo = connectionFailureInfo,
};
}
/// <summary>
/// Creates view model for providing information about activated license.
/// </summary>
/// <returns>View model for the activated license state.</returns>
private ActivatedStateViewModel _CreateActivatedState()
{
var state = new ActivatedStateViewModel(
_licenseManager,
_licensePageCommands,
this.ShowExpirationWarning);
return state;
}
/// <summary>
/// Creates view model for providing information about expired license.
/// </summary>
/// <returns>View model for the expired license state.</returns>
private ExpiredStateViewModel _CreateExpiredState()
{
var state = new ExpiredStateViewModel(
_licenseManager,
_licensePageCommands,
_ExecuteSingleVehicleLogin);
return state;
}
/// <summary>
/// Creates view model for providing information about cases when license
/// activation credentials were incorrect.
/// </summary>
/// <returns>View model for the wrong license credentials state.</returns>
private WrongCredentialsStateViewModel _CreateWrongCredentialsState()
{
var state = new WrongCredentialsStateViewModel(
_licensePageCommands);
return state;
}
/// <summary>
/// Creates view model for providing information about cases when there is
/// no license subsription for current license activation credentials.
/// </summary>
/// <returns>View model for the no license subsription state.</returns>
private NoSubscriptionStateViewModel _CreateNoSubscriptionState()
{
var state = new NoSubscriptionStateViewModel(
_licensePageCommands);
return state;
}
/// <summary>
/// Executes license activation.
/// </summary>
/// <param name="username">The user name to be used for license activation.</param>
/// <param name="password">The password to be used for license activation.</param>
/// <param name="rememberCredentials">Indicates if credentials should be saved
/// and reused upon application startup.</param>
private void _ExecuteLogin(
string username,
string password,
bool rememberCredentials)
{
_ActivateLicense(() => _licenseManager.ActivateLicense(
username,
password,
rememberCredentials));
}
/// <summary>
/// Executes activation for the free single vehicle license.
/// </summary>
private void _ExecuteSingleVehicleLogin()
{
_ActivateLicense(_licenseManager.ActivateFreeLicense);
}
/// <summary>
/// Activates license with the specified license activator action.
/// </summary>
/// <param name="licenseActivator">The delegate performing license activation.</param>
private void _ActivateLicense(Action licenseActivator)
{
Debug.Assert(licenseActivator != null);
using (_workingStatusController.EnterBusyState(null))
{
try
{
licenseActivator();
_UpdateExpirationWarningDisplayState();
_CreateConnectedState();
this.LicenseState = AgsServerState.Authorized;
}
catch (LicenseException ex)
{
Logger.Error(ex);
this.LicenseState = AgsServerState.Unauthorized;
}
catch (CommunicationException ex)
{
Logger.Error(ex);
this.LicenseState = AgsServerState.Unavailable;
}
this.LicenseActivationStatus = _licenseManager.LicenseActivationStatus;
}
}
/// <summary>
/// Creates document with the licensing notes from the specified string.
/// </summary>
/// <param name="notes">The string value containing licensing notes document.</param>
/// <returns>A new document with the licensing notes.</returns>
private FlowDocument _CreateLicensingNotes(string notes)
{
var document = _GetDocumentFromString(notes);
if (document == null)
{
return null;
}
// add handlers to hyperlink RequesNavigate for open reques page in browser
Hyperlink subscription = document.FindName(HYPERLINK_NAME) as Hyperlink;
if (subscription != null)
{
subscription.RequestNavigate += _HyperlinkRequestNavigate;
}
return document;
}
/// <summary>
/// Creates document with the troubleshooting notes from the specified string.
/// </summary>
/// <param name="notes">The string value containing troubleshooting notes document.</param>
/// <returns>A new document with the troubleshooting notes.</returns>
private FlowDocument _CreateTroubleshootingNotes(string notes)
{
var document = _GetDocumentFromString(notes);
if (document == null)
{
return null;
}
// add handlers to hyperlink RequesNavigate for open reques page in browser
Hyperlink subscription = document.FindName(HYPERLINK_NAME) as Hyperlink;
if (subscription != null)
{
subscription.RequestNavigate += _HyperlinkRequestNavigate;
}
Hyperlink webaccounts = document.FindName(WEBACCOUNTS_HYPERLINK) as Hyperlink;
if (webaccounts != null)
{
webaccounts.RequestNavigate += _HyperlinkRequestNavigate;
}
Hyperlink purchase = document.FindName(PURCHASE_HUPERLINK) as Hyperlink;
if (purchase != null)
{
purchase.RequestNavigate += _HyperlinkRequestNavigate;
}
return document;
}
/// <summary>
/// Method converts string to Flow Document
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private FlowDocument _GetDocumentFromString(string str)
{
if (string.IsNullOrEmpty(str))
return null;
FlowDocument result = null;
XmlTextReader reader = default(XmlTextReader);
try
{
// Loading document from input string (in common case string can be empty)
reader = new XmlTextReader(new StringReader(str));
result = (FlowDocument)XamlReader.Load(reader);
}
catch (Exception)
{
// if we cannot convert string to FlowDocument and string isn't empty - add this string to document as text
// if string is empty - return nulls
if (result == null && !string.IsNullOrEmpty(str))
result = new FlowDocument(new Paragraph(new Run(str)));
}
finally
{
reader.Close();
}
if (result != null)
{
ApplyStyle(result);
}
return result;
}
/// <summary>
/// Method adds info string with stated values into inlines collection
/// </summary>
/// <returns></returns>
private void _AddInfoString(
string titleString,
string valueString,
ICollection<Inline> inlines)
{
// title's always white
Run title = new Run(titleString);
inlines.Add(title);
Bold value = new Bold(new Run(valueString));
inlines.Add(value);
}
/// <summary>
/// Method creates license info strings
/// </summary>
/// <returns></returns>
private List<Block> _CreateLicenseInfoText()
{
var blocks = new List<Block>();
var activatedLicense = _licenseManager.AppLicense;
// if user use services license
if (activatedLicense.IsRestricted)
{
var paragraph = new Paragraph();
_AddInfoString(
(string)App.Current.FindResource("CurrentArcLogisticsSubscriptionString") + GAP_STRING,
activatedLicense.ProductCode,
paragraph.Inlines);
blocks.Add(paragraph);
paragraph = new Paragraph();
_AddInfoString(
(string)App.Current.FindResource("MaximumNumberOfRoutes") + GAP_STRING,
activatedLicense.PermittedRouteNumber.ToString(),
paragraph.Inlines);
blocks.Add(paragraph);
paragraph = new Paragraph();
_AddInfoString(
(string)App.Current.FindResource("SubscriptionExpirationDate") + GAP_STRING,
((DateTime)activatedLicense.ExpirationDate).ToShortDateString(),
paragraph.Inlines);
blocks.Add(paragraph);
}
else // if user use Enterprise license
{
Run info = new Run(activatedLicense.Description);
var paragraph = new Paragraph(info);
blocks.Add(paragraph);
}
return blocks;
}
/// <summary>
/// Handles hyperlink navigation requests.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private void _HyperlinkRequestNavigate(object sender, RequestNavigateEventArgs e)
{
var link = (Hyperlink)sender;
_NavigateToUrl(link.NavigateUri.ToString());
e.Handled = true;
}
/// <summary>
/// Navigates to the specified url.
/// </summary>
/// <param name="url">The url to navigate to.</param>
private void _NavigateToUrl(string url)
{
_uriNavigator.NavigateToUri(url);
}
/// <summary>
/// Updates current value of the <see cref="P:RequiresExpirationWarning"/>
/// property.
/// </summary>
private void _UpdateExpirationWarningDisplayState()
{
var result = _licenseExpirationChecker.RequiresExpirationWarning(
_licenseManager.AuthorizedUserName,
_licenseManager.AppLicense,
_licenseManager.AppLicenseValidationDate);
this.RequiresExpirationWarning = result;
}
#endregion
#region private constants
private const string GAP_STRING = " ";
private const string HYPERLINK_NAME = "hyperlink";
private const string WEBACCOUNTS_HYPERLINK = "webaccounts_hyperlink";
private const string PURCHASE_HUPERLINK = "purchase_hyperlink";
/// <summary>
/// Name of the LicensingNotes property.
/// </summary>
private const string PROPERTY_NAME_LICENSING_NOTES = "LicensingNotes";
/// <summary>
/// Name of the TroubleshootingNotes property.
/// </summary>
private const string PROPERTY_NAME_TROUBLESHOOTING_NOTES = "TroubleshootingNotes";
/// <summary>
/// Name of the LicenseActivationStatus property.
/// </summary>
private const string PROPERTY_NAME_LICENSE_ACTIVATION_STATUS = "LicenseActivationStatus";
/// <summary>
/// Name of the RequiresExpirationWarning property.
/// </summary>
private const string PROPERTY_NAME_REQUIRES_EXPIRATION_WARNING =
"RequiresExpirationWarning";
#endregion
#region private fields
/// <summary>
/// The reference to the license manager object.
/// </summary>
private ILicenseManager _licenseManager;
/// <summary>
/// The messenger object to be used for notifications.
/// </summary>
private IMessenger _messenger;
/// <summary>
/// The object to be used for managing application working status.
/// </summary>
private IWorkingStatusController _workingStatusController;
/// <summary>
/// The reference to the object to be used for navigating to URI's.
/// </summary>
private IUriNavigator _uriNavigator;
/// <summary>
/// The reference to the license expiration checker object.
/// </summary>
private ILicenseExpirationChecker _licenseExpirationChecker;
/// <summary>
/// The reference to the license page commands object.
/// </summary>
private ILicensePageCommands _licensePageCommands;
/// <summary>
/// Stores a document with licensing notes.
/// </summary>
private FlowDocument _licensingNotes;
/// <summary>
/// Stores a document with troubleshooting notes.
/// </summary>
private FlowDocument _troubleshootingNotes;
/// <summary>
/// Stores license activation status value.
/// </summary>
private LicenseActivationStatus _licenseActivationStatus;
/// <summary>
/// The dictionary mapping license activation status into factory function
/// for creation of the corresponding view model.
/// </summary>
private Dictionary<LicenseActivationStatus, Func<LicenseActivationViewState>> _stateFactories;
/// <summary>
/// Stores value of the RequiresExpirationWarning property.
/// </summary>
private bool _requiresExpirationWarning;
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
namespace osu.Game.Input.Bindings
{
public class GlobalActionContainer : DatabasedKeyBindingContainer<GlobalAction>, IHandleGlobalKeyboardInput
{
private readonly Drawable handler;
private InputManager parentInputManager;
public GlobalActionContainer(OsuGameBase game)
: base(matchingMode: KeyCombinationMatchingMode.Modifiers)
{
if (game is IKeyBindingHandler<GlobalAction>)
handler = game;
}
protected override void LoadComplete()
{
base.LoadComplete();
parentInputManager = GetContainingInputManager();
}
public override IEnumerable<IKeyBinding> DefaultKeyBindings => GlobalKeyBindings
.Concat(EditorKeyBindings)
.Concat(InGameKeyBindings)
.Concat(SongSelectKeyBindings)
.Concat(AudioControlKeyBindings);
public IEnumerable<KeyBinding> GlobalKeyBindings => new[]
{
new KeyBinding(InputKey.F6, GlobalAction.ToggleNowPlaying),
new KeyBinding(InputKey.F8, GlobalAction.ToggleChat),
new KeyBinding(InputKey.F9, GlobalAction.ToggleSocial),
new KeyBinding(InputKey.F10, GlobalAction.ToggleGameplayMouseButtons),
new KeyBinding(InputKey.F12, GlobalAction.TakeScreenshot),
new KeyBinding(new[] { InputKey.Control, InputKey.Alt, InputKey.R }, GlobalAction.ResetInputSettings),
new KeyBinding(new[] { InputKey.Control, InputKey.T }, GlobalAction.ToggleToolbar),
new KeyBinding(new[] { InputKey.Control, InputKey.O }, GlobalAction.ToggleSettings),
new KeyBinding(new[] { InputKey.Control, InputKey.D }, GlobalAction.ToggleBeatmapListing),
new KeyBinding(new[] { InputKey.Control, InputKey.N }, GlobalAction.ToggleNotifications),
new KeyBinding(new[] { InputKey.Control, InputKey.Shift, InputKey.S }, GlobalAction.ToggleSkinEditor),
new KeyBinding(InputKey.Escape, GlobalAction.Back),
new KeyBinding(InputKey.ExtraMouseButton1, GlobalAction.Back),
new KeyBinding(new[] { InputKey.Alt, InputKey.Home }, GlobalAction.Home),
new KeyBinding(InputKey.Up, GlobalAction.SelectPrevious),
new KeyBinding(InputKey.Down, GlobalAction.SelectNext),
new KeyBinding(InputKey.Space, GlobalAction.Select),
new KeyBinding(InputKey.Enter, GlobalAction.Select),
new KeyBinding(InputKey.KeypadEnter, GlobalAction.Select),
new KeyBinding(new[] { InputKey.Control, InputKey.Shift, InputKey.R }, GlobalAction.RandomSkin),
};
public IEnumerable<KeyBinding> EditorKeyBindings => new[]
{
new KeyBinding(new[] { InputKey.F1 }, GlobalAction.EditorComposeMode),
new KeyBinding(new[] { InputKey.F2 }, GlobalAction.EditorDesignMode),
new KeyBinding(new[] { InputKey.F3 }, GlobalAction.EditorTimingMode),
new KeyBinding(new[] { InputKey.F4 }, GlobalAction.EditorSetupMode),
new KeyBinding(new[] { InputKey.Control, InputKey.Shift, InputKey.A }, GlobalAction.EditorVerifyMode),
new KeyBinding(new[] { InputKey.J }, GlobalAction.EditorNudgeLeft),
new KeyBinding(new[] { InputKey.K }, GlobalAction.EditorNudgeRight),
};
public IEnumerable<KeyBinding> InGameKeyBindings => new[]
{
new KeyBinding(InputKey.Space, GlobalAction.SkipCutscene),
new KeyBinding(InputKey.ExtraMouseButton2, GlobalAction.SkipCutscene),
new KeyBinding(InputKey.Tilde, GlobalAction.QuickRetry),
new KeyBinding(new[] { InputKey.Control, InputKey.Tilde }, GlobalAction.QuickExit),
new KeyBinding(new[] { InputKey.Control, InputKey.Plus }, GlobalAction.IncreaseScrollSpeed),
new KeyBinding(new[] { InputKey.Control, InputKey.Minus }, GlobalAction.DecreaseScrollSpeed),
new KeyBinding(new[] { InputKey.Shift, InputKey.Tab }, GlobalAction.ToggleInGameInterface),
new KeyBinding(InputKey.MouseMiddle, GlobalAction.PauseGameplay),
new KeyBinding(InputKey.Space, GlobalAction.TogglePauseReplay),
new KeyBinding(InputKey.Control, GlobalAction.HoldForHUD),
};
public IEnumerable<KeyBinding> SongSelectKeyBindings => new[]
{
new KeyBinding(InputKey.F1, GlobalAction.ToggleModSelection),
new KeyBinding(InputKey.F2, GlobalAction.SelectNextRandom),
new KeyBinding(new[] { InputKey.Shift, InputKey.F2 }, GlobalAction.SelectPreviousRandom),
new KeyBinding(InputKey.F3, GlobalAction.ToggleBeatmapOptions)
};
public IEnumerable<KeyBinding> AudioControlKeyBindings => new[]
{
new KeyBinding(new[] { InputKey.Alt, InputKey.Up }, GlobalAction.IncreaseVolume),
new KeyBinding(new[] { InputKey.Alt, InputKey.Down }, GlobalAction.DecreaseVolume),
new KeyBinding(new[] { InputKey.Control, InputKey.F4 }, GlobalAction.ToggleMute),
new KeyBinding(InputKey.TrackPrevious, GlobalAction.MusicPrev),
new KeyBinding(InputKey.F1, GlobalAction.MusicPrev),
new KeyBinding(InputKey.TrackNext, GlobalAction.MusicNext),
new KeyBinding(InputKey.F5, GlobalAction.MusicNext),
new KeyBinding(InputKey.PlayPause, GlobalAction.MusicPlay),
new KeyBinding(InputKey.F3, GlobalAction.MusicPlay)
};
protected override IEnumerable<Drawable> KeyBindingInputQueue
{
get
{
// To ensure the global actions are handled with priority, this GlobalActionContainer is actually placed after game content.
// It does not contain children as expected, so we need to forward the NonPositionalInputQueue from the parent input manager to correctly
// allow the whole game to handle these actions.
// An eventual solution to this hack is to create localised action containers for individual components like SongSelect, but this will take some rearranging.
var inputQueue = parentInputManager?.NonPositionalInputQueue ?? base.KeyBindingInputQueue;
return handler != null ? inputQueue.Prepend(handler) : inputQueue;
}
}
}
public enum GlobalAction
{
[Description("Toggle chat overlay")]
ToggleChat,
[Description("Toggle social overlay")]
ToggleSocial,
[Description("Reset input settings")]
ResetInputSettings,
[Description("Toggle toolbar")]
ToggleToolbar,
[Description("Toggle settings")]
ToggleSettings,
[Description("Toggle beatmap listing")]
ToggleBeatmapListing,
[Description("Increase volume")]
IncreaseVolume,
[Description("Decrease volume")]
DecreaseVolume,
[Description("Toggle mute")]
ToggleMute,
// In-Game Keybindings
[Description("Skip cutscene")]
SkipCutscene,
[Description("Quick retry (hold)")]
QuickRetry,
[Description("Take screenshot")]
TakeScreenshot,
[Description("Toggle gameplay mouse buttons")]
ToggleGameplayMouseButtons,
[Description("Back")]
Back,
[Description("Increase scroll speed")]
IncreaseScrollSpeed,
[Description("Decrease scroll speed")]
DecreaseScrollSpeed,
[Description("Select")]
Select,
[Description("Quick exit (hold)")]
QuickExit,
// Game-wide beatmap music controller keybindings
[Description("Next track")]
MusicNext,
[Description("Previous track")]
MusicPrev,
[Description("Play / pause")]
MusicPlay,
[Description("Toggle now playing overlay")]
ToggleNowPlaying,
[Description("Previous selection")]
SelectPrevious,
[Description("Next selection")]
SelectNext,
[Description("Home")]
Home,
[Description("Toggle notifications")]
ToggleNotifications,
[Description("Pause gameplay")]
PauseGameplay,
// Editor
[Description("Setup mode")]
EditorSetupMode,
[Description("Compose mode")]
EditorComposeMode,
[Description("Design mode")]
EditorDesignMode,
[Description("Timing mode")]
EditorTimingMode,
[Description("Hold for HUD")]
HoldForHUD,
[Description("Random skin")]
RandomSkin,
[Description("Pause / resume replay")]
TogglePauseReplay,
[Description("Toggle in-game interface")]
ToggleInGameInterface,
// Song select keybindings
[Description("Toggle Mod Select")]
ToggleModSelection,
[Description("Random")]
SelectNextRandom,
[Description("Rewind")]
SelectPreviousRandom,
[Description("Beatmap Options")]
ToggleBeatmapOptions,
[Description("Verify mode")]
EditorVerifyMode,
[Description("Nudge selection left")]
EditorNudgeLeft,
[Description("Nudge selection right")]
EditorNudgeRight,
[Description("Toggle skin editor")]
ToggleSkinEditor,
}
}
| |
using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;
namespace ytd.PlayList
{
/// <summary>
/// Class to parse and display RSS Feeds
/// </summary>
internal class RssManager : IDisposable
{
#region Variables
private string _feedTitle;
private List<VideoItem> _rssItems = new List<VideoItem>();
private bool _IsDisposed;
#endregion Variables
#region Constructors
/// <summary>
/// Empty constructor, allowing us to
/// instantiate our class and set our
/// _url variable to an empty string
/// </summary>
public RssManager()
{
Url = string.Empty;
}
/// <summary>
/// Constructor allowing us to instantiate our class
/// and set the _url variable to a value
/// </summary>
/// <param name="feedUrl">The URL of the Rss feed</param>
public RssManager(string feedUrl)
{
Url = feedUrl;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets or sets the URL of the RSS feed to parse.
/// </summary>
public string Url { get; set; }
/// <summary>
/// Gets all the items in the RSS feed.
/// </summary>
public IList<VideoItem> RssItems
{
get { return _rssItems; }
}
/// <summary>
/// Gets the title of the RSS feed.
/// </summary>
public string Title
{
get { return _feedTitle; }
}
#endregion Properties
#region Methods
/// <summary>
/// Retrieves the remote RSS feed and parses it.
/// </summary>
public IList<VideoItem> GetFeed()
{
//check to see if the FeedURL is empty
if ( String.IsNullOrEmpty(Url) )
//throw an exception if not provided
throw new ArgumentException("You must provide a feed URL");
//start the parsing process
#if TEST_RSS
using ( StreamReader sr = new StreamReader("debug_feed.xml"))
using ( XmlReader reader = XmlReader.Create(sr) )
#else
using ( XmlReader reader = XmlReader.Create(Url) )
#endif
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
//#if !TEST_RSS
// xmlDoc.Save("debug_feed.xml");
//#endif
//parse the items of the feed
SetNameSpaceMngr(xmlDoc);
GetFeedTitle(xmlDoc);
_rssItems.AddRange(ParseRssItems(xmlDoc));
string rel = GetRelatedFeed(xmlDoc);
while ( !string.IsNullOrEmpty(rel) )
{
using ( XmlReader relReader = XmlReader.Create(rel) )
{
XmlDocument xmlRelDoc = new XmlDocument();
xmlRelDoc.Load(relReader);
_rssItems.AddRange(ParseRssItems(xmlRelDoc));
rel = GetRelatedFeed(xmlRelDoc);
}
}
//return the feed items
return _rssItems;
}
}
private string GetRelatedFeed(XmlDocument xmlDoc)
{
string feedRelation = null;
XmlNode relationNode = xmlDoc.SelectSingleNode("/default:feed/default:link[@rel='next']", _nmsmngr);
if ( relationNode != null )
{
XmlAttribute hrefAttrib = relationNode.Attributes["href"];
if ( hrefAttrib != null )
{
feedRelation = hrefAttrib.InnerText;
}
}
return feedRelation;
}
private void GetFeedTitle(XmlDocument xmlDoc)
{
XmlNode feedNode = xmlDoc.SelectSingleNode("/default:feed", _nmsmngr);
ParseDocElements(feedNode, "default:title", ref _feedTitle);
}
/// <summary>
/// Parses the xml document in order to retrieve the RSS items.
/// </summary>
private List<VideoItem> ParseRssItems(XmlDocument xmlDoc)
{
List<VideoItem> rssItems = new List<VideoItem>();
XmlNodeList nodes = xmlDoc.SelectNodes("/default:feed/default:entry", _nmsmngr);
foreach ( XmlNode node in nodes )
{
VideoItem item = new VideoItem();
ParseDocElements(node, "default:title", ref item.Title);
ParseDocElements(node, "default:content", ref item.Description);
ParseDocElements(node, "default:author/default:name", ref item.Author);
XmlNode videoLinkNode = node.SelectSingleNode("default:link[@rel='alternate']", _nmsmngr);
if ( videoLinkNode != null )
{
XmlAttribute hrefAttrib = videoLinkNode.Attributes["href"];
if ( hrefAttrib != null )
{
// Clean the video link from other parameters
var urlBuilder = new UriBuilder(hrefAttrib.InnerText);
var values = HttpUtility.ParseQueryString(urlBuilder.Query);
string videoParam = values["v"];
item.Link = string.Concat(urlBuilder.Scheme, "://", urlBuilder.Host, urlBuilder.Path, "?v=", videoParam);
}
}
string date = null;
ParseDocElements(node, "default:published", ref date);
DateTime.TryParse(date, out item.Date);
rssItems.Add(item);
}
return rssItems;
}
private XmlNamespaceManager _nmsmngr;
private void SetNameSpaceMngr(XmlDocument xmlDoc)
{
_nmsmngr = new XmlNamespaceManager(xmlDoc.NameTable);
_nmsmngr.AddNamespace(string.Empty, "http://www.w3.org/2005/Atom");
_nmsmngr.AddNamespace("media", "http://search.yahoo.com/mrss/");
_nmsmngr.AddNamespace("openSearch", "http://a9.com/-/spec/opensearchrss/1.0/");
_nmsmngr.AddNamespace("gd", "http://schemas.google.com/g/2005");
_nmsmngr.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007");
_nmsmngr.AddNamespace("default", "http://www.w3.org/2005/Atom");
}
/// <summary>
/// Parses the XmlNode with the specified XPath query
/// and assigns the value to the property parameter.
/// </summary>
private void ParseDocElements(XmlNode parent, string xPath, ref string property)
{
if ( parent != null )
{
XmlNode node = parent.SelectSingleNode(xPath, _nmsmngr);
if ( node != null )
property = node.InnerText;
}
}
#endregion Methods
#region IDisposable Members
/// <summary>
/// Performs the disposal.
/// </summary>
private void Dispose(bool disposing)
{
if ( disposing && !_IsDisposed )
{
_rssItems.Clear();
Url = null;
_feedTitle = null;
}
_IsDisposed = true;
}
/// <summary>
/// Releases the object to the garbage collector
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion IDisposable Members
}
}
| |
//
// Julian.cs
//
// This class encapsulates a Julian date system where the day starts at noon.
// Some Julian dates:
// 01/01/1990 00:00 UTC - 2447892.5
// 01/01/1990 12:00 UTC - 2447893.0
// 01/01/2000 00:00 UTC - 2451544.5
// 01/01/2001 00:00 UTC - 2451910.5
//
// The Julian day begins at noon, which allows astronomers to have the
// same date in a single observing session.
//
// References:
// "Astronomical Formulae for Calculators", Jean Meeus, 4th Edition
// "Satellite Communications", Dennis Roddy, 2nd Edition, 1995.
// "Spacecraft Attitude Determination and Control", James R. Wertz, 1984
//
// Copyright (c) 2003-2012 Michael F. Henry
// Version 05/2012
//
using System;
namespace OrbitTools
{
/// <summary>
/// Encapsulates a Julian date.
/// </summary>
public class Julian
{
private const double EPOCH_JAN0_12H_1900 = 2415020.0; // Dec 31.5 1899 = Dec 31 1899 12h UTC
private const double EPOCH_JAN1_00H_1900 = 2415020.5; // Jan 1.0 1900 = Jan 1 1900 00h UTC
private const double EPOCH_JAN1_12H_1900 = 2415021.0; // Jan 1.5 1900 = Jan 1 1900 12h UTC
private const double EPOCH_JAN1_12H_2000 = 2451545.0; // Jan 1.5 2000 = Jan 1 2000 12h UTC
private double m_Date; // Julian date
private int m_Year; // Year including century
private double m_Day; // Day of year, 1.0 = Jan 1 00h
#region Construction
/// <summary>
/// Create a Julian date object from a DateTime object. The time
/// contained in the DateTime object is assumed to be UTC.
/// </summary>
/// <param name="utc">The UTC time to convert.</param>
public Julian(DateTime utc)
{
double day = utc.DayOfYear +
(utc.Hour +
((utc.Minute +
((utc.Second + (utc.Millisecond / 1000.0)) / 60.0)) / 60.0)) / 24.0;
Initialize(utc.Year, day);
}
/// <summary>
/// Create a Julian date object given a year and day-of-year.
/// </summary>
/// <param name="year">The year, including the century (i.e., 2012).</param>
/// <param name="doy">Day of year (1 means January 1, etc.).</param>
/// <remarks>
/// The fractional part of the day value is the fractional portion of
/// the day.
/// Examples:
/// day = 1.0 Jan 1 00h
/// day = 1.5 Jan 1 12h
/// day = 2.0 Jan 2 00h
/// </remarks>
public Julian(int year, double doy)
{
Initialize(year, doy);
}
#endregion
#region Properties
public double Date { get { return m_Date; } }
public double FromJan0_12h_1900() { return m_Date - EPOCH_JAN0_12H_1900; }
public double FromJan1_00h_1900() { return m_Date - EPOCH_JAN1_00H_1900; }
public double FromJan1_12h_1900() { return m_Date - EPOCH_JAN1_12H_1900; }
public double FromJan1_12h_2000() { return m_Date - EPOCH_JAN1_12H_2000; }
#endregion
/// <summary>
/// Calculates the time difference between two Julian dates.
/// </summary>
/// <param name="date">Julian date.</param>
/// <returns>
/// A TimeSpan representing the time difference between the two dates.
/// </returns>
public TimeSpan Diff(Julian date)
{
const double TICKS_PER_DAY = 8.64e11; // 1 tick = 100 nanoseconds
return new TimeSpan((long)((m_Date - date.m_Date) * TICKS_PER_DAY));
}
/// <summary>
/// Initialize the Julian date object.
/// </summary>
/// <param name="year">The year, including the century.</param>
/// <param name="doy">Day of year (1 means January 1, etc.)</param>
/// <remarks>
/// The first day of the year, Jan 1, is day 1.0. Noon on Jan 1 is
/// represented by the day value of 1.5, etc.
/// </remarks>
protected void Initialize(int year, double doy)
{
// Arbitrary years used for error checking
if (year < 1900 || year > 2100)
{
throw new ArgumentOutOfRangeException("year");
}
// The last day of a leap year is day 366
if (doy < 1.0 || doy >= 367.0)
{
throw new ArgumentOutOfRangeException("doy");
}
m_Year = year;
m_Day = doy;
// Now calculate Julian date
// Ref: "Astronomical Formulae for Calculators", Jean Meeus, pages 23-25
year--;
// Centuries are not leap years unless they divide by 400
int A = (year / 100);
int B = 2 - A + (A / 4);
double NewYears = (int)(365.25 * year) +
(int)(30.6001 * 14) +
1720994.5 + B;
m_Date = NewYears + doy;
}
/// <summary>
/// Calculate Greenwich Mean Sidereal Time for the Julian date.
/// </summary>
/// <returns>
/// The angle, in radians, measuring eastward from the Vernal Equinox to
/// the prime meridian. This angle is also referred to as "ThetaG"
/// (Theta GMST).
/// </returns>
public double ToGmst()
{
// References:
// The 1992 Astronomical Almanac, page B6.
// Explanatory Supplement to the Astronomical Almanac, page 50.
// Orbital Coordinate Systems, Part III, Dr. T.S. Kelso,
// Satellite Times, Nov/Dec 1995
double UT = (m_Date + 0.5) % 1.0;
double TU = (FromJan1_12h_2000() - UT) / 36525.0;
double GMST = 24110.54841 + TU *
(8640184.812866 + TU * (0.093104 - TU * 6.2e-06));
GMST = (GMST + Globals.SecPerDay * Globals.OmegaE * UT) % Globals.SecPerDay;
if (GMST < 0.0)
{
GMST += Globals.SecPerDay; // "wrap" negative modulo value
}
return (Globals.TwoPi * (GMST / Globals.SecPerDay));
}
/// <summary>
/// Calculate Local Mean Sidereal Time for this Julian date at the given
/// longitude.
/// </summary>
/// <param name="lon">The longitude, in radians, measured west from Greenwich.</param>
/// <returns>
/// The angle, in radians, measuring eastward from the Vernal Equinox to
/// the given longitude.
/// </returns>
public double ToLmst(double lon)
{
return (ToGmst() + lon) % Globals.TwoPi;
}
/// <summary>
/// Returns a UTC DateTime object that corresponds to this Julian date.
/// </summary>
/// <returns>A DateTime object in UTC.</returns>
public DateTime ToTime()
{
// Jan 1
DateTime dt = new DateTime(m_Year, 1, 1);
// m_Day = 1 = Jan1
dt = dt.AddDays(m_Day - 1.0);
return dt;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneModDifficultyAdjustSettings : OsuManualInputManagerTestScene
{
private OsuModDifficultyAdjust modDifficultyAdjust;
[SetUpSteps]
public void SetUpSteps()
{
AddStep("create control", () =>
{
modDifficultyAdjust = new OsuModDifficultyAdjust();
Child = new Container
{
Size = new Vector2(300),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
ChildrenEnumerable = modDifficultyAdjust.CreateSettingsControls(),
},
}
};
});
}
[Test]
public void TestFollowsBeatmapDefaultsVisually()
{
setBeatmapWithDifficultyParameters(5);
checkSliderAtValue("Circle Size", 5);
checkBindableAtValue("Circle Size", null);
setBeatmapWithDifficultyParameters(8);
checkSliderAtValue("Circle Size", 8);
checkBindableAtValue("Circle Size", null);
}
[Test]
public void TestOutOfRangeValueStillApplied()
{
AddStep("set override cs to 11", () => modDifficultyAdjust.CircleSize.Value = 11);
checkSliderAtValue("Circle Size", 11);
checkBindableAtValue("Circle Size", 11);
// this is a no-op, just showing that it won't reset the value during deserialisation.
setExtendedLimits(false);
checkSliderAtValue("Circle Size", 11);
checkBindableAtValue("Circle Size", 11);
// setting extended limits will reset the serialisation exception.
// this should be fine as the goal is to allow, at most, the value of extended limits.
setExtendedLimits(true);
checkSliderAtValue("Circle Size", 11);
checkBindableAtValue("Circle Size", 11);
}
[Test]
public void TestExtendedLimits()
{
setSliderValue("Circle Size", 99);
checkSliderAtValue("Circle Size", 10);
checkBindableAtValue("Circle Size", 10);
setExtendedLimits(true);
checkSliderAtValue("Circle Size", 10);
checkBindableAtValue("Circle Size", 10);
setSliderValue("Circle Size", 99);
checkSliderAtValue("Circle Size", 11);
checkBindableAtValue("Circle Size", 11);
setExtendedLimits(false);
checkSliderAtValue("Circle Size", 10);
checkBindableAtValue("Circle Size", 10);
}
[Test]
public void TestUserOverrideMaintainedOnBeatmapChange()
{
setSliderValue("Circle Size", 9);
setBeatmapWithDifficultyParameters(2);
checkSliderAtValue("Circle Size", 9);
checkBindableAtValue("Circle Size", 9);
}
[Test]
public void TestResetToDefault()
{
setBeatmapWithDifficultyParameters(2);
setSliderValue("Circle Size", 9);
checkSliderAtValue("Circle Size", 9);
checkBindableAtValue("Circle Size", 9);
resetToDefault("Circle Size");
checkSliderAtValue("Circle Size", 2);
checkBindableAtValue("Circle Size", null);
}
[Test]
public void TestUserOverrideMaintainedOnMatchingBeatmapValue()
{
setBeatmapWithDifficultyParameters(3);
checkSliderAtValue("Circle Size", 3);
checkBindableAtValue("Circle Size", null);
// need to initially change it away from the current beatmap value to trigger an override.
setSliderValue("Circle Size", 4);
setSliderValue("Circle Size", 3);
checkSliderAtValue("Circle Size", 3);
checkBindableAtValue("Circle Size", 3);
setBeatmapWithDifficultyParameters(4);
checkSliderAtValue("Circle Size", 3);
checkBindableAtValue("Circle Size", 3);
}
[Test]
public void TestResetToDefaults()
{
setBeatmapWithDifficultyParameters(5);
setSliderValue("Circle Size", 3);
setExtendedLimits(true);
checkSliderAtValue("Circle Size", 3);
checkBindableAtValue("Circle Size", 3);
AddStep("reset mod settings", () => modDifficultyAdjust.ResetSettingsToDefaults());
checkSliderAtValue("Circle Size", 5);
checkBindableAtValue("Circle Size", null);
}
[Test]
public void TestModSettingChangeTracker()
{
ModSettingChangeTracker tracker = null;
Queue<Mod> settingsChangedQueue = null;
setBeatmapWithDifficultyParameters(5);
AddStep("add mod settings change tracker", () =>
{
settingsChangedQueue = new Queue<Mod>();
tracker = new ModSettingChangeTracker(modDifficultyAdjust.Yield())
{
SettingChanged = settingsChangedQueue.Enqueue
};
});
AddAssert("no settings changed", () => settingsChangedQueue.Count == 0);
setSliderValue("Circle Size", 3);
settingsChangedFired();
setSliderValue("Circle Size", 5);
checkBindableAtValue("Circle Size", 5);
settingsChangedFired();
AddStep("reset mod settings", () => modDifficultyAdjust.CircleSize.SetDefault());
checkBindableAtValue("Circle Size", null);
settingsChangedFired();
setExtendedLimits(true);
settingsChangedFired();
AddStep("dispose tracker", () =>
{
tracker.Dispose();
tracker = null;
});
void settingsChangedFired()
{
AddAssert("setting changed event fired", () =>
{
settingsChangedQueue.Dequeue();
return settingsChangedQueue.Count == 0;
});
}
}
private void resetToDefault(string name)
{
AddStep($"Reset {name} to default", () =>
this.ChildrenOfType<DifficultyAdjustSettingsControl>().First(c => c.LabelText == name)
.Current.SetDefault());
}
private void setExtendedLimits(bool status) =>
AddStep($"Set extended limits {status}", () => modDifficultyAdjust.ExtendedLimits.Value = status);
private void setSliderValue(string name, float value)
{
AddStep($"Set {name} slider to {value}", () =>
this.ChildrenOfType<DifficultyAdjustSettingsControl>().First(c => c.LabelText == name)
.ChildrenOfType<SettingsSlider<float>>().First().Current.Value = value);
}
private void checkBindableAtValue(string name, float? expectedValue)
{
AddAssert($"Bindable {name} is {(expectedValue?.ToString() ?? "null")}", () =>
this.ChildrenOfType<DifficultyAdjustSettingsControl>().First(c => c.LabelText == name)
.Current.Value == expectedValue);
}
private void checkSliderAtValue(string name, float expectedValue)
{
AddAssert($"Slider {name} at {expectedValue}", () =>
this.ChildrenOfType<DifficultyAdjustSettingsControl>().First(c => c.LabelText == name)
.ChildrenOfType<SettingsSlider<float>>().First().Current.Value == expectedValue);
}
private void setBeatmapWithDifficultyParameters(float value)
{
AddStep($"set beatmap with all {value}", () => Beatmap.Value = CreateWorkingBeatmap(new Beatmap
{
BeatmapInfo = new BeatmapInfo
{
BaseDifficulty = new BeatmapDifficulty
{
OverallDifficulty = value,
CircleSize = value,
DrainRate = value,
ApproachRate = value,
}
}
}));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using Tibia.Objects;
namespace Tibia.Constants
{
public static class TileLists
{
#region Up
public static List<uint> Up = new List<uint>
{
Tiles.Up.Stairs,
Tiles.Up.Ramp,
Tiles.Up.Ramp1,
Tiles.Up.Ramp2,
Tiles.Up.Ramp3,
Tiles.Up.WoodenStairs,
Tiles.Up.Ramp4,
Tiles.Up.Ramp5,
Tiles.Up.Ramp6,
Tiles.Up.Ramp7,
Tiles.Up.Ramp8,
Tiles.Up.Ramp9,
Tiles.Up.Ramp10,
Tiles.Up.Ramp11,
Tiles.Up.Ramp12,
Tiles.Up.Ramp13,
Tiles.Up.Ramp14,
Tiles.Up.Ramp15,
Tiles.Up.StoneStairs,
Tiles.Up.StoneStairs1,
Tiles.Up.Stairs1,
Tiles.Up.Stairs2,
Tiles.Up.Stairs3,
Tiles.Up.Ramp16,
Tiles.Up.Ramp17,
Tiles.Up.Ramp18,
Tiles.Up.Ramp19,
Tiles.Up.StoneStairs2,
Tiles.Up.StoneStairs3,
Tiles.Up.Ramp20,
Tiles.Up.Ramp21,
Tiles.Up.Ramp22,
Tiles.Up.Ramp23,
Tiles.Up.WoodenStairs1,
Tiles.Up.Ramp24,
Tiles.Up.StoneStairs4,
Tiles.Up.Roof,
Tiles.Up.Roof1,
Tiles.Up.Roof2,
Tiles.Up.Roof3,
Tiles.Up.CorkscrewStairs,
Tiles.Up.Ramp25,
Tiles.Up.Ramp26,
};
#endregion
#region Down
public static List<uint> Down = new List<uint>
{
Tiles.Down.Grass,
Tiles.Down.Pitfall,
Tiles.Down.Trapdoor,
Tiles.Down.Trapdoor1,
Tiles.Down.Hole,
Tiles.Down.Hole1,
Tiles.Down.Trapdoor2,
Tiles.Down.Trapdoor3,
Tiles.Down.Stairs4,
Tiles.Down.Stairs5,
Tiles.Down.Stairs6,
Tiles.Down.Trapdoor4,
Tiles.Down.Ladder,
Tiles.Down.Trapdoor5,
Tiles.Down.Stairs7,
Tiles.Down.Stairs8,
Tiles.Down.Stairs9,
Tiles.Down.OpenTrapdoor,
Tiles.Down.Hole2,
Tiles.Down.Hole3,
Tiles.Down.Hole4,
Tiles.Down.Hole5,
Tiles.Down.Hole6,
Tiles.Down.Hole7,
Tiles.Down.Hole8,
Tiles.Down.Hole9,
Tiles.Down.Hole10,
Tiles.Down.Hole11,
Tiles.Down.Trapdoor6,
Tiles.Down.Ladder1,
Tiles.Down.Ladder2,
Tiles.Down.Trapdoor7,
Tiles.Down.Stairway,
Tiles.Down.Stairs10,
Tiles.Down.Stairs11,
Tiles.Down.Pitfall1,
Tiles.Down.Pitfall2,
Tiles.Down.EarthHole,
Tiles.Down.Stairs12,
Tiles.Down.Stairs13,
Tiles.Down.Stairs14,
Tiles.Down.Stairs15,
Tiles.Down.Stairs16,
Tiles.Down.Trapdoor8,
Tiles.Down.Trapdoor9,
Tiles.Down.Hole12,
Tiles.Down.Trapdoor10,
Tiles.Down.Ramp27,
Tiles.Down.Ramp28,
Tiles.Down.Ramp29,
Tiles.Down.Ramp30,
Tiles.Down.Trapdoor11,
Tiles.Down.Trapdoor12,
Tiles.Down.IceHut,
Tiles.Down.IceHut1,
Tiles.Down.IceHut2,
Tiles.Down.Ramp31,
Tiles.Down.Ramp32,
Tiles.Down.Ramp33,
Tiles.Down.Ramp34,
Tiles.Down.Ramp35,
Tiles.Down.Ramp36,
Tiles.Down.Ramp37,
Tiles.Down.Ramp38,
Tiles.Down.Trapdoor13,
Tiles.Down.WoodenCoffin,
Tiles.Down.WoodenCoffin1,
Tiles.Down.LargeHole,
Tiles.Down.Hole13,
Tiles.Down.LargeHole1,
Tiles.Down.Stairs17,
Tiles.Down.CaveEntrance,
Tiles.Down.CaveEntrance1,
Tiles.Down.CaveEntrance2,
Tiles.Down.CaveEntrance3,
Tiles.Down.CaveEntrance4,
Tiles.Down.CaveEntrance5,
Tiles.Down.Hole14,
Tiles.Down.Hole15,
Tiles.Down.Hole16,
Tiles.Down.Hole17,
Tiles.Down.SomethingCrawling,
Tiles.Down.Hole18,
Tiles.Down.Hole19,
Tiles.Down.LargeHole2,
Tiles.Down.Trapdoor14,
Tiles.Down.Trapdoor15,
Tiles.Down.Trapdoor16,
Tiles.Down.Trapdoor17,
Tiles.Down.Trapdoor18,
Tiles.Down.Stairs18,
Tiles.Down.Stairs19,
Tiles.Down.Trapdoor19,
Tiles.Down.Trapdoor20,
Tiles.Down.Trapdoor21,
Tiles.Down.Hole20,
Tiles.Down.TunnelEntrance,
Tiles.Down.Ramp39,
Tiles.Down.Ramp40,
Tiles.Down.Ramp41,
Tiles.Down.Ramp42,
Tiles.Down.Ramp43,
Tiles.Down.Ramp44,
Tiles.Down.Ramp45,
Tiles.Down.Ramp46,
Tiles.Down.Hole21,
Tiles.Down.Hole22,
Tiles.Down.Trapdoor22,
Tiles.Down.Trapdoor23,
Tiles.Down.WaterVortex,
Tiles.Down.LargeHole3,
Tiles.Down.CorkscrewStairs1,
Tiles.Down.Stairs20,
Tiles.Down.OpenTrapdoor1,
Tiles.Down.CorkscrewStairs2,
};
#endregion
#region UpUse
public static List<uint> UpUse = new List<uint>
{
Tiles.UpUse.Ladder3,
Tiles.UpUse.Ladder4,
Tiles.UpUse.RopeLadder,
Tiles.UpUse.Ladder5,
Tiles.UpUse.Ladder6,
};
#endregion
#region Rope
public static List<uint> Rope = new List<uint>
{
Tiles.Rope.DirtFloor,
Tiles.Rope.StoneTile,
Tiles.Rope.DirtFloor1,
Tiles.Rope.DirtFloor2,
};
#endregion
#region DownUse
public static List<uint> DownUse = new List<uint>
{
Tiles.DownUse.SewerGrate,
Tiles.DownUse.SewerGrate1,
};
#endregion
#region Shovel
public static List<uint> Shovel = new List<uint>
{
Tiles.Shovel.StonePile,
Tiles.Shovel.LooseStonePile,
Tiles.Shovel.LooseIcePile,
Tiles.Shovel.LooseStonePile1,
Tiles.Shovel.Hole23,
};
#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.
//---------------------------------------------------------------------------
//
//
//
// Description: Definition of readonly character memory buffer
//
//
//
//
//
//
//---------------------------------------------------------------------------
using System;
using System.Windows;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Runtime.InteropServices;
using System.Security;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace MS.Internal
{
/// <summary>
/// Abstraction of a readonly character buffer
/// </summary>
internal abstract class CharacterBuffer : IList<char>
{
/// <summary>
/// Get fixed address of the character buffer
/// </summary>
public abstract unsafe char* GetCharacterPointer();
/// <summary>
/// Get fixed address of the character buffer and Pin if necessary.
/// Note: This call should only be used when we know that we are not pinning
/// memory for a long time so as not to fragment the heap.
/// </summary>
public abstract IntPtr PinAndGetCharacterPointer(int offset, out GCHandle gcHandle);
/// <summary>
/// This is a matching call for PinAndGetCharacterPointer to unpin the memory.
/// </summary>
public abstract void UnpinCharacterPointer(GCHandle gcHandle);
/// <summary>
/// Add character buffer's content to a StringBuilder
/// </summary>
/// <param name="stringBuilder">string builder to add content to</param>
/// <param name="characterOffset">character offset to first character to append</param>
/// <param name="length">number of character appending</param>
/// <returns>string builder</returns>
public abstract void AppendToStringBuilder(
StringBuilder stringBuilder,
int characterOffset,
int length
);
#region IList<char> Members
public int IndexOf(char item)
{
for (int i = 0; i < Count; ++i)
{
if (item == this[i])
return i;
}
return -1;
}
public void Insert(int index, char item)
{
// CharacterBuffer is read only.
throw new NotSupportedException();
}
public abstract char this[int index]
{
get;
set;
}
public void RemoveAt(int index)
{
// CharacterBuffer is read only.
throw new NotSupportedException();
}
#endregion
#region ICollection<char> Members
public void Add(char item)
{
// CharacterBuffer is read only.
throw new NotSupportedException();
}
public void Clear()
{
// CharacterBuffer is read only.
throw new NotSupportedException();
}
public bool Contains(char item)
{
return IndexOf(item) != -1;
}
public void CopyTo(char[] array, int arrayIndex)
{
for (int i = 0; i < Count; ++i)
{
array[arrayIndex + i] = this[i];
}
}
public abstract int Count
{
get;
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(char item)
{
// CharacterBuffer is read only.
throw new NotSupportedException();
}
#endregion
#region IEnumerable<char> Members
IEnumerator<char> IEnumerable<char>.GetEnumerator()
{
for (int i = 0; i < Count; ++i)
yield return this[i];
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<char>)this).GetEnumerator();
}
#endregion
}
/// <summary>
/// Character memory buffer implemented by managed character array
/// </summary>
internal sealed class CharArrayCharacterBuffer : CharacterBuffer
{
private char[] _characterArray;
/// <summary>
/// Creating a character memory buffer from character array
/// </summary>
/// <param name="characterArray">character array</param>
public CharArrayCharacterBuffer(
char[] characterArray
)
{
if (characterArray == null)
{
throw new ArgumentNullException("characterArray");
}
_characterArray = characterArray;
}
/// <summary>
/// Read a character from buffer at the specified character index
/// </summary>
public override char this[int characterOffset]
{
get { return _characterArray[characterOffset]; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Buffer character length
/// </summary>
public override int Count
{
get { return _characterArray.Length; }
}
/// <summary>
/// Get fixed address of the character buffer
/// </summary>
public override unsafe char* GetCharacterPointer()
{
// Even though we could allocate GCHandle for this purpose, we would need
// to manage how to release them appropriately. It is even worse if we
// consider performance implication of doing so. In typical UI scenario,
// there are so many string objects running around in GC heap. Getting
// GCHandle for every one of them is very expensive and demote GC's ability
// to compact its heap.
return null;
}
/// <summary>
/// Get fixed address of the character buffer and Pin if necessary.
/// Note: This call should only be used when we know that we are not pinning
/// memory for a long time so as not to fragment the heap.
public unsafe override IntPtr PinAndGetCharacterPointer(int offset, out GCHandle gcHandle)
{
gcHandle = GCHandle.Alloc(_characterArray, GCHandleType.Pinned);
return new IntPtr(((char*)gcHandle.AddrOfPinnedObject().ToPointer()) + offset);
}
/// <summary>
/// This is a matching call for PinAndGetCharacterPointer to unpin the memory.
/// </summary>
public override void UnpinCharacterPointer(GCHandle gcHandle)
{
gcHandle.Free();
}
/// <summary>
/// Add character buffer's content to a StringBuilder
/// </summary>
/// <param name="stringBuilder">string builder to add content to</param>
/// <param name="characterOffset">index to first character in the buffer to append</param>
/// <param name="characterLength">number of character appending</param>
public override void AppendToStringBuilder(
StringBuilder stringBuilder,
int characterOffset,
int characterLength
)
{
Debug.Assert(characterOffset >= 0 && characterOffset < _characterArray.Length, "Invalid character index");
if ( characterLength < 0
|| characterOffset + characterLength > _characterArray.Length)
{
characterLength = _characterArray.Length - characterOffset;
}
stringBuilder.Append(_characterArray, characterOffset, characterLength);
}
}
/// <summary>
/// Character buffer implemented by string
/// </summary>
internal sealed class StringCharacterBuffer : CharacterBuffer
{
private string _string;
/// <summary>
/// Creating a character buffer from string
/// </summary>
/// <param name="characterString">character string</param>
public StringCharacterBuffer(
string characterString
)
{
if (characterString == null)
{
throw new ArgumentNullException("characterString");
}
_string = characterString;
}
/// <summary>
/// Read a character from buffer at the specified character index
/// </summary>
public override char this[int characterOffset]
{
get { return _string[characterOffset]; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Buffer character length
/// </summary>
public override int Count
{
get { return _string.Length; }
}
/// <summary>
/// Get fixed address of the character buffer
/// </summary>
public override unsafe char* GetCharacterPointer()
{
// Even though we could allocate GCHandle for this purpose, we would need
// to manage how to release them appropriately. It is even worse if we
// consider performance implication of doing so. In typical UI scenario,
// there are so many string objects running around in GC heap. Getting
// GCHandle for every one of them is very expensive and demote GC's ability
// to compact its heap.
return null;
}
/// <summary>
/// Get fixed address of the character buffer and Pin if necessary.
/// Note: This call should only be used when we know that we are not pinning
/// memory for a long time so as not to fragment the heap.
public unsafe override IntPtr PinAndGetCharacterPointer(int offset, out GCHandle gcHandle)
{
gcHandle = GCHandle.Alloc(_string, GCHandleType.Pinned);
return new IntPtr(((char*)gcHandle.AddrOfPinnedObject().ToPointer()) + offset);
}
/// <summary>
/// This is a matching call for PinAndGetCharacterPointer to unpin the memory.
/// </summary>
public override void UnpinCharacterPointer(GCHandle gcHandle)
{
gcHandle.Free();
}
/// <summary>
/// Add character buffer's content to a StringBuilder
/// </summary>
/// <param name="stringBuilder">string builder to add content to</param>
/// <param name="characterOffset">index to first character in the buffer to append</param>
/// <param name="characterLength">number of character appending</param>
public override void AppendToStringBuilder(
StringBuilder stringBuilder,
int characterOffset,
int characterLength
)
{
Debug.Assert(characterOffset >= 0 && characterOffset < _string.Length, "Invalid character index");
if ( characterLength < 0
|| characterOffset + characterLength > _string.Length)
{
characterLength = _string.Length - characterOffset;
}
stringBuilder.Append(_string, characterOffset, characterLength);
}
}
/// <summary>
/// Character buffer implemented as unsafe pointer to character string
/// </summary>
internal sealed unsafe class UnsafeStringCharacterBuffer : CharacterBuffer
{
private char* _unsafeString;
private int _length;
/// <summary>
/// Creating a character buffer from an unsafe pointer to character string
/// </summary>
/// <param name="characterString">unsafe pointer to character string</param>
/// <param name="length">number of valid characters referenced by the unsafe pointer</param>
public UnsafeStringCharacterBuffer(
char* characterString,
int length
)
{
if (characterString == null)
{
throw new ArgumentNullException("characterString");
}
if (length <= 0)
{
throw new ArgumentOutOfRangeException("length", SR.Get(SRID.ParameterValueMustBeGreaterThanZero));
}
_unsafeString = characterString;
_length = length;
}
/// <summary>
/// Read a character from buffer at the specified character index
/// </summary>
public override char this[int characterOffset]
{
get {
if (characterOffset >= _length || characterOffset < 0)
throw new ArgumentOutOfRangeException("characterOffset", SR.Get(SRID.ParameterMustBeBetween,0,_length));
return _unsafeString[characterOffset];
}
set { throw new NotSupportedException(); }
}
/// <summary>
/// Buffer character length
/// </summary>
public override int Count
{
get { return _length; }
}
/// <summary>
/// Get fixed address of the character buffer
/// </summary>
public override unsafe char* GetCharacterPointer()
{
return _unsafeString;
}
/// <summary>
/// Get fixed address of the character buffer and Pin if necessary.
/// Note: This call should only be used when we know that we are not pinning
/// memory for a long time so as not to fragment the heap.
public override IntPtr PinAndGetCharacterPointer(int offset, out GCHandle gcHandle)
{
gcHandle = new GCHandle();
return new IntPtr(_unsafeString + offset);
}
/// <summary>
/// This is a matching call for PinAndGetCharacterPointer to unpin the memory.
/// </summary>
public override void UnpinCharacterPointer(GCHandle gcHandle)
{
}
/// <summary>
/// Add character buffer's content to a StringBuilder
/// </summary>
/// <param name="stringBuilder">string builder to add content to</param>
/// <param name="characterOffset">index to first character in the buffer to append</param>
/// <param name="characterLength">number of character appending</param>
public override void AppendToStringBuilder(
StringBuilder stringBuilder,
int characterOffset,
int characterLength
)
{
if (characterOffset >= _length || characterOffset < 0)
{
throw new ArgumentOutOfRangeException("characterOffset", SR.Get(SRID.ParameterMustBeBetween,0,_length));
}
if (characterLength < 0 || characterOffset + characterLength > _length)
{
throw new ArgumentOutOfRangeException("characterLength", SR.Get(SRID.ParameterMustBeBetween,0, _length - characterOffset));
}
stringBuilder.Append(new string(_unsafeString, characterOffset, characterLength));
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Game.Beatmaps;
using osu.Game.IO;
using osu.Game.IO.Legacy;
using osu.Game.Overlays.Notifications;
namespace osu.Game.Collections
{
/// <summary>
/// Handles user-defined collections of beatmaps.
/// </summary>
/// <remarks>
/// This is currently reading and writing from the osu-stable file format. This is a temporary arrangement until we refactor the
/// database backing the game. Going forward writing should be done in a similar way to other model stores.
/// </remarks>
public class CollectionManager : Component
{
/// <summary>
/// Database version in stable-compatible YYYYMMDD format.
/// </summary>
private const int database_version = 30000000;
private const string database_name = "collection.db";
private const string database_backup_name = "collection.db.bak";
public readonly BindableList<BeatmapCollection> Collections = new BindableList<BeatmapCollection>();
[Resolved]
private GameHost host { get; set; }
[Resolved]
private BeatmapManager beatmaps { get; set; }
private readonly Storage storage;
public CollectionManager(Storage storage)
{
this.storage = storage;
}
[BackgroundDependencyLoader]
private void load()
{
Collections.CollectionChanged += collectionsChanged;
if (storage.Exists(database_backup_name))
{
// If a backup file exists, it means the previous write operation didn't run to completion.
// Always prefer the backup file in such a case as it's the most recent copy that is guaranteed to not be malformed.
//
// The database is saved 100ms after any change, and again when the game is closed, so there shouldn't be a large diff between the two files in the worst case.
if (storage.Exists(database_name))
storage.Delete(database_name);
File.Copy(storage.GetFullPath(database_backup_name), storage.GetFullPath(database_name));
}
if (storage.Exists(database_name))
{
List<BeatmapCollection> beatmapCollections;
using (var stream = storage.GetStream(database_name))
beatmapCollections = readCollections(stream);
// intentionally fire-and-forget async.
importCollections(beatmapCollections);
}
}
private void collectionsChanged(object sender, NotifyCollectionChangedEventArgs e) => Schedule(() =>
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (var c in e.NewItems.Cast<BeatmapCollection>())
c.Changed += backgroundSave;
break;
case NotifyCollectionChangedAction.Remove:
foreach (var c in e.OldItems.Cast<BeatmapCollection>())
c.Changed -= backgroundSave;
break;
case NotifyCollectionChangedAction.Replace:
foreach (var c in e.OldItems.Cast<BeatmapCollection>())
c.Changed -= backgroundSave;
foreach (var c in e.NewItems.Cast<BeatmapCollection>())
c.Changed += backgroundSave;
break;
}
backgroundSave();
});
/// <summary>
/// Set an endpoint for notifications to be posted to.
/// </summary>
public Action<Notification> PostNotification { protected get; set; }
/// <summary>
/// This is a temporary method and will likely be replaced by a full-fledged (and more correctly placed) migration process in the future.
/// </summary>
public Task ImportFromStableAsync(StableStorage stableStorage)
{
if (!stableStorage.Exists(database_name))
{
// This handles situations like when the user does not have a collections.db file
Logger.Log($"No {database_name} available in osu!stable installation", LoggingTarget.Information, LogLevel.Error);
return Task.CompletedTask;
}
return Task.Run(async () =>
{
using (var stream = stableStorage.GetStream(database_name))
await Import(stream).ConfigureAwait(false);
});
}
public async Task Import(Stream stream)
{
var notification = new ProgressNotification
{
State = ProgressNotificationState.Active,
Text = "Collections import is initialising..."
};
PostNotification?.Invoke(notification);
var collections = readCollections(stream, notification);
await importCollections(collections).ConfigureAwait(false);
notification.CompletionText = $"Imported {collections.Count} collections";
notification.State = ProgressNotificationState.Completed;
}
private Task importCollections(List<BeatmapCollection> newCollections)
{
var tcs = new TaskCompletionSource<bool>();
Schedule(() =>
{
try
{
foreach (var newCol in newCollections)
{
var existing = Collections.FirstOrDefault(c => c.Name.Value == newCol.Name.Value);
if (existing == null)
Collections.Add(existing = new BeatmapCollection { Name = { Value = newCol.Name.Value } });
foreach (var newBeatmap in newCol.Beatmaps)
{
if (!existing.Beatmaps.Contains(newBeatmap))
existing.Beatmaps.Add(newBeatmap);
}
}
tcs.SetResult(true);
}
catch (Exception e)
{
Logger.Error(e, "Failed to import collection.");
tcs.SetException(e);
}
});
return tcs.Task;
}
private List<BeatmapCollection> readCollections(Stream stream, ProgressNotification notification = null)
{
if (notification != null)
{
notification.Text = "Reading collections...";
notification.Progress = 0;
}
var result = new List<BeatmapCollection>();
try
{
using (var sr = new SerializationReader(stream))
{
sr.ReadInt32(); // Version
int collectionCount = sr.ReadInt32();
result.Capacity = collectionCount;
for (int i = 0; i < collectionCount; i++)
{
if (notification?.CancellationToken.IsCancellationRequested == true)
return result;
var collection = new BeatmapCollection { Name = { Value = sr.ReadString() } };
int mapCount = sr.ReadInt32();
for (int j = 0; j < mapCount; j++)
{
if (notification?.CancellationToken.IsCancellationRequested == true)
return result;
string checksum = sr.ReadString();
var beatmap = beatmaps.QueryBeatmap(b => b.MD5Hash == checksum);
if (beatmap != null)
collection.Beatmaps.Add(beatmap);
}
if (notification != null)
{
notification.Text = $"Imported {i + 1} of {collectionCount} collections";
notification.Progress = (float)(i + 1) / collectionCount;
}
result.Add(collection);
}
}
}
catch (Exception e)
{
Logger.Error(e, "Failed to read collection database.");
}
return result;
}
public void DeleteAll()
{
Collections.Clear();
PostNotification?.Invoke(new ProgressCompletionNotification { Text = "Deleted all collections!" });
}
private readonly object saveLock = new object();
private int lastSave;
private int saveFailures;
/// <summary>
/// Perform a save with debounce.
/// </summary>
private void backgroundSave()
{
var current = Interlocked.Increment(ref lastSave);
Task.Delay(100).ContinueWith(task =>
{
if (current != lastSave)
return;
if (!save())
backgroundSave();
});
}
private bool save()
{
lock (saveLock)
{
Interlocked.Increment(ref lastSave);
// This is NOT thread-safe!!
try
{
var tempPath = Path.GetTempFileName();
using (var ms = new MemoryStream())
{
using (var sw = new SerializationWriter(ms, true))
{
sw.Write(database_version);
var collectionsCopy = Collections.ToArray();
sw.Write(collectionsCopy.Length);
foreach (var c in collectionsCopy)
{
sw.Write(c.Name.Value);
var beatmapsCopy = c.Beatmaps.ToArray();
sw.Write(beatmapsCopy.Length);
foreach (var b in beatmapsCopy)
sw.Write(b.MD5Hash);
}
}
using (var fs = File.OpenWrite(tempPath))
ms.WriteTo(fs);
var databasePath = storage.GetFullPath(database_name);
var databaseBackupPath = storage.GetFullPath(database_backup_name);
// Back up the existing database, clearing any existing backup.
if (File.Exists(databaseBackupPath))
File.Delete(databaseBackupPath);
if (File.Exists(databasePath))
File.Move(databasePath, databaseBackupPath);
// Move the new database in-place of the existing one.
File.Move(tempPath, databasePath);
// If everything succeeded up to this point, remove the backup file.
if (File.Exists(databaseBackupPath))
File.Delete(databaseBackupPath);
}
if (saveFailures < 10)
saveFailures = 0;
return true;
}
catch (Exception e)
{
// Since this code is not thread-safe, we may run into random exceptions (such as collection enumeration or out of range indexing).
// Failures are thus only alerted if they exceed a threshold (once) to indicate "actual" errors having occurred.
if (++saveFailures == 10)
Logger.Error(e, "Failed to save collection database!");
}
return false;
}
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
save();
}
}
}
| |
/* ====================================================================
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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace NPOI.HPSF
{
using System;
using System.IO;
using System.Collections;
using System.Text;
using NPOI.Util;
using NPOI.HPSF.Wellknown;
using NPOI.POIFS.FileSystem;
/// <summary>
/// Represents a property Set in the Horrible Property Set Format
/// (HPSF). These are usually metadata of a Microsoft Office
/// document.
/// An application that wants To access these metadata should Create
/// an instance of this class or one of its subclasses by calling the
/// factory method {@link PropertySetFactory#Create} and then retrieve
/// the information its needs by calling appropriate methods.
/// {@link PropertySetFactory#Create} does its work by calling one
/// of the constructors {@link PropertySet#PropertySet(InputStream)} or
/// {@link PropertySet#PropertySet(byte[])}. If the constructor's
/// argument is not in the Horrible Property Set Format, i.e. not a
/// property Set stream, or if any other error occurs, an appropriate
/// exception is thrown.
/// A {@link PropertySet} has a list of {@link Section}s, and each
/// {@link Section} has a {@link Property} array. Use {@link
/// #GetSections} To retrieve the {@link Section}s, then call {@link
/// Section#GetProperties} for each {@link Section} To Get hold of the
/// {@link Property} arrays. Since the vast majority of {@link
/// PropertySet}s Contains only a single {@link Section}, the
/// convenience method {@link #GetProperties} returns the properties of
/// a {@link PropertySet}'s {@link Section} (throwing a {@link
/// NoSingleSectionException} if the {@link PropertySet} Contains more
/// (or less) than exactly one {@link Section}).
/// @author Rainer Klute
/// <a href="mailto:[email protected]"><[email protected]></a>
/// @author Drew Varner (Drew.Varner hanginIn sc.edu)
/// @since 2002-02-09
/// </summary>
[Serializable]
internal class PropertySet
{
/**
* The "byteOrder" field must equal this value.
*/
protected static byte[] BYTE_ORDER_ASSERTION =
new byte[] { (byte)0xFE, (byte)0xFF };
/**
* Specifies this {@link PropertySet}'s byte order. See the
* HPFS documentation for details!
*/
protected int byteOrder;
/// <summary>
/// Gets or sets the property Set stream's low-level "byte order"
/// field. It is always <c>0xFFFE</c>
/// </summary>
/// <value>The property Set stream's low-level "byte order" field..</value>
public virtual int ByteOrder
{
get { return byteOrder; }
set { byteOrder = value; }
}
/**
* The "format" field must equal this value.
*/
protected static byte[] FORMAT_ASSERTION =
new byte[] { (byte)0x00, (byte)0x00 };
/**
* Specifies this {@link PropertySet}'s format. See the HPFS
* documentation for details!
*/
protected int format;
/// <summary>
/// Gets or sets the property Set stream's low-level "format"
/// field. It is always <c>0x0000</c>
/// </summary>
/// <value>The property Set stream's low-level "format" field.</value>
public virtual int Format
{
get { return format; }
set { format = value; }
}
/**
* Specifies the version of the operating system that Created
* this {@link PropertySet}. See the HPFS documentation for
* details!
*/
protected int osVersion;
/**
* If the OS version field holds this value the property Set stream Was
* Created on a 16-bit Windows system.
*/
public const int OS_WIN16 = 0x0000;
/**
* If the OS version field holds this value the property Set stream Was
* Created on a Macintosh system.
*/
public const int OS_MACINTOSH = 0x0001;
/**
* If the OS version field holds this value the property Set stream Was
* Created on a 32-bit Windows system.
*/
public const int OS_WIN32 = 0x0002;
/// <summary>
/// Returns the property Set stream's low-level "OS version"
/// field.
/// </summary>
/// <value>The property Set stream's low-level "OS version" field.</value>
public virtual int OSVersion
{
get { return osVersion; }
set { osVersion = value; }
}
/**
* Specifies this {@link PropertySet}'s "classID" field. See
* the HPFS documentation for details!
*/
[NonSerialized]
protected ClassID classID;
/// <summary>
/// Gets or sets the property Set stream's low-level "class ID"
/// </summary>
/// <value>The property Set stream's low-level "class ID" field.</value>
public virtual ClassID ClassID
{
get { return classID; }
set { classID = value; }
}
/// <summary>
/// Returns the number of {@link Section}s in the property
/// Set.
/// </summary>
/// <value>The number of {@link Section}s in the property Set.</value>
public virtual int SectionCount
{
get { return sections.Count; }
}
/**
* The sections in this {@link PropertySet}.
*/
protected IList sections;
/// <summary>
/// Returns the {@link Section}s in the property Set.
/// </summary>
/// <value>{@link Section}s in the property Set.</value>
public virtual IList Sections
{
get { return sections; }
}
/// <summary>
/// Creates an empty (uninitialized) {@link PropertySet}
/// Please note: For the time being this
/// constructor is protected since it is used for internal purposes
/// only, but expect it To become public once the property Set's
/// writing functionality is implemented.
/// </summary>
protected PropertySet()
{ }
/// <summary>
/// Creates a {@link PropertySet} instance from an {@link
/// InputStream} in the Horrible Property Set Format.
/// The constructor Reads the first few bytes from the stream
/// and determines whether it is really a property Set stream. If
/// it Is, it parses the rest of the stream. If it is not, it
/// Resets the stream To its beginning in order To let other
/// components mess around with the data and throws an
/// exception.
/// </summary>
/// <param name="stream">Holds the data making out the property Set
/// stream.</param>
public PropertySet(Stream stream)
{
if (IsPropertySetStream(stream))
{
int avail = (stream as ByteArrayInputStream).Available(); ;
byte[] buffer = new byte[avail];
stream.Read(buffer, 0, buffer.Length);
init(buffer, 0, buffer.Length);
}
else
throw new NoPropertySetStreamException("this stream may not be a valid property set stream");
}
/// <summary>
/// Creates a {@link PropertySet} instance from a byte array
/// that represents a stream in the Horrible Property Set
/// Format.
/// </summary>
/// <param name="stream">The byte array holding the stream data.</param>
/// <param name="offset">The offset in stream where the stream data begin.
/// If the stream data begin with the first byte in the
/// array, the offset is 0.</param>
/// <param name="Length"> The Length of the stream data.</param>
public PropertySet(byte[] stream, int offset, int Length)
{
if (IsPropertySetStream(stream, offset, Length))
init(stream, offset, Length);
else
throw new NoPropertySetStreamException();
}
/// <summary>
/// Creates a {@link PropertySet} instance from a byte array
/// that represents a stream in the Horrible Property Set
/// Format.
/// </summary>
/// <param name="stream">The byte array holding the stream data. The
/// complete byte array contents is the stream data.</param>
public PropertySet(byte[] stream):this(stream, 0, stream.Length)
{
}
/// <summary>
/// Checks whether an {@link InputStream} is in the Horrible
/// Property Set Format.
/// </summary>
/// <param name="stream">The {@link InputStream} To check. In order To
/// perform the check, the method Reads the first bytes from the
/// stream. After Reading, the stream is Reset To the position it
/// had before Reading. The {@link InputStream} must support the
/// {@link InputStream#mark} method.</param>
/// <returns>
/// <c>true</c> if the stream is a property Set
/// stream; otherwise, <c>false</c>.
/// </returns>
public static bool IsPropertySetStream(Stream stream)
{
ByteArrayInputStream dis = stream as ByteArrayInputStream;
/*
* Read at most this many bytes.
*/
int BUFFER_SIZE = 50;
/*
* Mark the current position in the stream so that we can
* Reset To this position if the stream does not contain a
* property Set.
*/
if (dis == null || !dis.MarkSupported())
throw new MarkUnsupportedException(stream.GetType().Name);
dis.Mark(BUFFER_SIZE);
/*
* Read a couple of bytes from the stream.
*/
byte[] buffer = new byte[BUFFER_SIZE];
int bytes =
stream.Read(buffer, 0,
(int)Math.Min(buffer.Length, dis.Available()));
bool isPropertySetStream =
IsPropertySetStream(buffer, 0, bytes);
stream.Seek(0, SeekOrigin.Begin);
dis.Reset();
return isPropertySetStream;
}
/// <summary>
/// Checks whether a byte array is in the Horrible Property Set
/// Format.
/// </summary>
/// <param name="src">The byte array To check.</param>
/// <param name="offset">The offset in the byte array.</param>
/// <param name="Length">The significant number of bytes in the byte
/// array. Only this number of bytes will be checked.</param>
/// <returns>
/// <c>true</c> if the byte array is a property Set
/// stream; otherwise, <c>false</c>.
/// </returns>
public static bool IsPropertySetStream(byte[] src,
int offset,
int Length)
{
/* FIXME (3): Ensure that at most "Length" bytes are Read. */
/*
* Read the header fields of the stream. They must always be
* there.
*/
int o = offset;
int byteOrder = LittleEndian.GetUShort(src, o);
o += LittleEndianConsts.SHORT_SIZE;
byte[] temp = new byte[LittleEndianConsts.SHORT_SIZE];
LittleEndian.PutShort(temp, (short)byteOrder);
if (!Arrays.Equals(temp, BYTE_ORDER_ASSERTION))
return false;
int format = LittleEndian.GetUShort(src, o);
o += LittleEndianConsts.SHORT_SIZE;
temp = new byte[LittleEndianConsts.SHORT_SIZE];
LittleEndian.PutShort(temp, (short)format);
if (!Arrays.Equals(temp, FORMAT_ASSERTION))
return false;
long osVersion = LittleEndian.GetUInt(src, offset);
o += LittleEndianConsts.INT_SIZE;
ClassID classID = new ClassID(src, offset);
o += ClassID.LENGTH;
long sectionCount = LittleEndian.GetUInt(src, o);
o += LittleEndianConsts.INT_SIZE;
if (sectionCount < 0)
return false;
return true;
}
/// <summary>
/// Initializes this {@link PropertySet} instance from a byte
/// array. The method assumes that it has been checked alReady that
/// the byte array indeed represents a property Set stream. It does
/// no more checks on its own.
/// </summary>
/// <param name="src">Byte array containing the property Set stream</param>
/// <param name="offset">The property Set stream starts at this offset</param>
/// <param name="Length">Length of the property Set stream.</param>
private void init(byte[] src, int offset, int Length)
{
/* FIXME (3): Ensure that at most "Length" bytes are Read. */
/*
* Read the stream's header fields.
*/
int o = offset;
byteOrder = LittleEndian.GetUShort(src, o);
o += LittleEndianConsts.SHORT_SIZE;
format = LittleEndian.GetUShort(src, o);
o += LittleEndianConsts.SHORT_SIZE;
osVersion = (int)LittleEndian.GetUInt(src, o);
o += LittleEndianConsts.INT_SIZE;
classID = new ClassID(src, o);
o += ClassID.LENGTH;
int sectionCount = LittleEndian.GetInt(src, o);
o += LittleEndianConsts.INT_SIZE;
if (sectionCount < 0)
throw new HPSFRuntimeException("Section count " + sectionCount +
" is negative.");
/*
* Read the sections, which are following the header. They
* start with an array of section descriptions. Each one
* consists of a format ID telling what the section Contains
* and an offset telling how many bytes from the start of the
* stream the section begins.
*/
/*
* Most property Sets have only one section. The Document
* Summary Information stream has 2. Everything else is a rare
* exception and is no longer fostered by Microsoft.
*/
sections = new ArrayList(sectionCount);
/*
* Loop over the section descriptor array. Each descriptor
* consists of a ClassID and a DWord, and we have To increment
* "offset" accordingly.
*/
for (int i = 0; i < sectionCount; i++)
{
Section s = new Section(src, o);
o += ClassID.Length + LittleEndianConsts.INT_SIZE;
sections.Add(s);
}
}
/// <summary>
/// Checks whether this {@link PropertySet} represents a Summary
/// Information.
/// </summary>
/// <value>
/// <c>true</c> Checks whether this {@link PropertySet} represents a Summary
/// Information; otherwise, <c>false</c>.
/// </value>
public virtual bool IsSummaryInformation
{
get
{
if (sections.Count <= 0)
return false;
return Arrays.Equals(((Section)sections[0]).FormatID.Bytes,
SectionIDMap.SUMMARY_INFORMATION_ID);
}
}
/// <summary>
/// Gets a value indicating whether this instance is document summary information.
/// </summary>
/// <value>
/// <c>true</c> if this instance is document summary information; otherwise, <c>false</c>.
/// </value>
/// Checks whether this {@link PropertySet} is a Document
/// Summary Information.
/// @return
/// <c>true</c>
/// if this {@link PropertySet}
/// represents a Document Summary Information, else
/// <c>false</c>
public virtual bool IsDocumentSummaryInformation
{
get
{
if (sections.Count <= 0)
return false;
return Arrays.Equals(((Section)sections[0]).FormatID.Bytes,
SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID1);
}
}
/// <summary>
/// Convenience method returning the {@link Property} array
/// contained in this property Set. It is a shortcut for Getting
/// the {@link PropertySet}'s {@link Section}s list and then
/// Getting the {@link Property} array from the first {@link
/// Section}.
/// </summary>
/// <value>The properties of the only {@link Section} of this
/// {@link PropertySet}.</value>
public virtual Property[] Properties
{
get { return FirstSection.Properties; }
}
/// <summary>
/// Convenience method returning the value of the property with
/// the specified ID. If the property is not available,
/// <c>null</c> is returned and a subsequent call To {@link
/// #WasNull} will return <c>true</c> .
/// </summary>
/// <param name="id">The property ID</param>
/// <returns>The property value</returns>
public virtual Object GetProperty(int id)
{
return FirstSection.GetProperty(id);
}
/// <summary>
/// Convenience method returning the value of a bool property
/// with the specified ID. If the property is not available,
/// <c>false</c> is returned. A subsequent call To {@link
/// #WasNull} will return <c>true</c> To let the caller
/// distinguish that case from a real property value of
/// <c>false</c>.
/// </summary>
/// <param name="id">The property ID</param>
/// <returns>The property value</returns>
public virtual bool GetPropertyBooleanValue(int id)
{
return FirstSection.GetPropertyBooleanValue(id);
}
/// <summary>
/// Convenience method returning the value of the numeric
/// property with the specified ID. If the property is not
/// available, 0 is returned. A subsequent call To {@link #WasNull}
/// will return <c>true</c> To let the caller distinguish
/// that case from a real property value of 0.
/// </summary>
/// <param name="id">The property ID</param>
/// <returns>The propertyIntValue value</returns>
public virtual int GetPropertyIntValue(int id)
{
return FirstSection.GetPropertyIntValue(id);
}
/// <summary>
/// Checks whether the property which the last call To {@link
/// #GetPropertyIntValue} or {@link #GetProperty} tried To access
/// Was available or not. This information might be important for
/// callers of {@link #GetPropertyIntValue} since the latter
/// returns 0 if the property does not exist. Using {@link
/// #WasNull}, the caller can distiguish this case from a
/// property's real value of 0.
/// </summary>
/// <value><c>true</c> if the last call To {@link
/// #GetPropertyIntValue} or {@link #GetProperty} tried To access a
/// property that Was not available; otherwise, <c>false</c>.</value>
public virtual bool WasNull
{
get { return FirstSection.WasNull; }
}
/// <summary>
/// Gets the first section.
/// </summary>
/// <value>The first section.</value>
public virtual Section FirstSection
{
get
{
if (SectionCount< 1)
throw new MissingSectionException("Property Set does not contain any sections.");
return ((Section)sections[0]);
}
}
/// <summary>
/// If the {@link PropertySet} has only a single section this
/// method returns it.
/// </summary>
/// <value>The singleSection value</value>
public Section SingleSection
{
get
{
int sectionCount = SectionCount;
if (sectionCount != 1)
throw new NoSingleSectionException
("Property Set Contains " + sectionCount + " sections.");
return ((Section)sections[0]);
}
}
/// <summary>
/// Returns <c>true</c> if the <c>PropertySet</c> is equal
/// To the specified parameter, else <c>false</c>.
/// </summary>
/// <param name="o">the object To Compare this
/// <c>PropertySet</c>
/// with</param>
/// <returns><c>true</c>
/// if the objects are equal,
/// <c>false</c>
/// if not</returns>
public override bool Equals(Object o)
{
if (o == null || !(o is PropertySet))
return false;
PropertySet ps = (PropertySet)o;
int byteOrder1 = ps.ByteOrder;
int byteOrder2 = ByteOrder;
ClassID classID1 = ps.ClassID;
ClassID classID2 = ClassID;
int format1 = ps.Format;
int format2 = Format;
int osVersion1 = ps.OSVersion;
int osVersion2 = OSVersion;
int sectionCount1 = ps.SectionCount;
int sectionCount2 = SectionCount;
if (byteOrder1 != byteOrder2 ||
!classID1.Equals(classID2) ||
format1 != format2 ||
osVersion1 != osVersion2 ||
sectionCount1 != sectionCount2)
return false;
/* Compare the sections: */
return Util.AreEqual(Sections, ps.Sections);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
throw new InvalidOperationException("FIXME: Not yet implemented.");
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
StringBuilder b = new StringBuilder();
int sectionCount = SectionCount;
b.Append(GetType().Name);
b.Append('[');
b.Append("byteOrder: ");
b.Append(ByteOrder);
b.Append(", classID: ");
b.Append(ClassID);
b.Append(", format: ");
b.Append(Format);
b.Append(", OSVersion: ");
b.Append(OSVersion);
b.Append(", sectionCount: ");
b.Append(sectionCount);
b.Append(", sections: [\n");
IList sections = Sections;
for (int i = 0; i < sectionCount; i++)
b.Append(((Section)sections[i]).ToString());
b.Append(']');
b.Append(']');
return b.ToString();
}
}
}
| |
/*
Copyright 2006-2017 Cryptany, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using Cryptany.Core.ConfigOM;
using System.Messaging;
using Cryptany.Core.Interaction;
using Cryptany.Core.Management;
using Cryptany.Core.MsmqLog;
using Cryptany.Core.Services.Management;
using Cryptany.Common.Utils;
using Cryptany.Common.Logging;
using Cryptany.Core.DPO;
using Cryptany.Core.MacrosProcessors;
using System.ServiceModel;
namespace Cryptany.Core
{
public static class ActionExecuter
{
public static bool ExecuteActions(Message msg, object objectId, List<OutputMessage> sendList)
{
bool res = true;
Cryptany.Core.DPO.PersistentStorage ps = ChannelConfiguration.DefaultPs;
GeneralObject generalObject = ps.GetEntityById<GeneralObject>(objectId);
if (generalObject == null)
return true;
bool ok = RuleChecker.CheckObjectRules(generalObject, msg);
if (!ok)
return true;
foreach ( Rule action in generalObject.Actions )
res &= ExecuteAction(action, generalObject, msg, sendList);
return res;
}
private static bool ExecuteAction(Rule action, GeneralObject generalObj, Message msg, List<OutputMessage> sendList)
{
bool res = true;
if (action.Mode == RuleType.Expression)
{
if (RuleChecker.CheckObjectRules(generalObj, msg))
{
if (RuleChecker.CheckRuleStatement(action.Statement1, msg))
{
if (action.Rule1 != null)
return ExecuteAction(action.Rule1, generalObj, msg, sendList);
}
else
{
if (action.Rule2 != null)
return ExecuteAction(action.Rule2, generalObj, msg, sendList);
}
return true;
// If none of the nested actions has been executed, then no error occured, so return a positive result
}
}
else
{
if (res &= PerformAction(action, generalObj, msg, sendList))
{
if (action.Rule1 != null)
res &= ExecuteAction(action.Rule1, generalObj, msg, sendList);
}
else
{
if (action.Rule2 != null)
res &= ExecuteAction(action.Rule2, generalObj, msg, sendList);
}
if (res)
foreach (Rule a in action.Actions)
res &= ExecuteAction(a, action.Object, msg, sendList);
}
return res;
}
private static bool PerformAction(Rule rule, GeneralObject generalObj, Message msg, List<OutputMessage> sendList)
{
bool res = true;
if ( RuleChecker.CheckObjectRules(rule.Object, msg) )
{
foreach ( Statement statement in rule.Statements )
{
switch (statement.Parameter.Name.ToUpper())
{
case "MTCLUB":
res &= SetSubscription(statement, generalObj.ConcreteObject, msg);
break;
case "SENDMESSAGE":
//res &= MessageSender.SendMessages(statement, generalObj, msg, sendList);
break;
case "SENDCHAIN":
{
ParameterValue val = statement.ParameterValues[0];
res &= SendMessageChain(msg, new Guid(val.Value));
break;
}
case "SENDCHAIN2":
{
ParameterValue val = statement.ParameterValues[0];
res &= SendMessageChain_2(msg, new Guid(val.Value));
// res &= SendMessageChain_3(msg, new Guid(val.Value),generalObj.ConcreteObject, sendList);
break;
}
case "SENDANSWERMAP":
foreach ( ParameterValue val in statement.ParameterValues )
{
try
{
Guid id = new Guid(val.Value);
PersistentStorage ps = ChannelConfiguration.DefaultPs;//ClassFactory.CreatePersistentStorage(ChannelConfiguration.Ds);
AnswerMap am = (AnswerMap)ps.GetEntityById(typeof(AnswerMap), id);
res &= MessageSender.SendAnswerMap(am, msg,sendList);
}
catch ( Exception ex )
{
res = false;
throw new ApplicationException(string.Format("ActionExecutor: Unable to perform 'SEND-ANSWERMAP' (ID = '{0}') ", val.Value), ex);
}
}
break;
case "SENDANSWERBLOCK":
foreach ( ParameterValue val in statement.ParameterValues )
{
try
{
Guid id = new Guid(val.Value);
PersistentStorage ps = ChannelConfiguration.DefaultPs;//ClassFactory.CreatePersistentStorage(ChannelConfiguration.Ds);
AnswerBlock block = (AnswerBlock)ps.GetEntityById(typeof(AnswerBlock), id);
res &= MessageSender.SendAnswerBlock(block, msg, sendList);
}
catch ( Exception ex )
{
res = false;
throw new ApplicationException(
string.Format("ActionExecutor: Unable to perform 'SEND-ANSWERBLOCK' (ID = '{0}'): {1} ", val.Value, ex.ToString()));
}
}
break;
case "SENDANSWER":
foreach ( ParameterValue val in statement.ParameterValues )
{
try
{
Guid id = new Guid(val.Value);
PersistentStorage ps = ChannelConfiguration.DefaultPs;//ClassFactory.CreatePersistentStorage(ChannelConfiguration.Ds);
Answer ans = (Answer)ps.GetEntityById(typeof(Answer), id);
res &= MessageSender.SendAnswer(ans, msg, sendList);
}
catch ( Exception ex )
{
res = false;
throw new ApplicationException(string.Format("ActionExecutor: Unable to perform 'SEND-ANSWER' (ID = '{0}') ", val.Value), ex);
}
}
break;
}
}
}
return res;
}
private static bool SendMessageChain(Message msg, Guid chainId)
{
try
{
Abonent ab = Abonent.GetByMSISDN(msg.MSISDN);
using (SqlConnection conn = Database.Connection)
{
using (SqlCommand comm = new SqlCommand("kernel.DistributeChain", conn))
{
comm.CommandType = System.Data.CommandType.StoredProcedure;
comm.Parameters.AddWithValue("@inboxId", msg.InboxId);
comm.Parameters.AddWithValue("@chainId", chainId);
comm.Parameters.AddWithValue("@abonentId", ab.DatabaseId);
comm.ExecuteNonQuery();
}
}
return true;
}
catch(SqlException ex)
{
throw new ApplicationException("Error sending message chain.", ex);
}
}
private static bool SendMessageChain_2(Message msg, Guid chainId)
{
Chains chain = (Chains)ChannelConfiguration.DefaultPs.GetEntityById(typeof(Chains), chainId);
if (string.IsNullOrEmpty(chain.Text1)||chain.TariffId1==Guid.Empty)
throw new ApplicationException("Error sending message chain. Wrong data. ChainId= "+chainId.ToString() );
string errText;
var factory = new ChannelFactory<ISMSSender>("TM_Endpoint");
ISMSSender tm = factory.CreateChannel();
Dictionary<string, object> addParams = new Dictionary<string, object>();
addParams.Add("inboxId", msg.InboxId);
addParams.Add("messagePriority", (int)Cryptany.Core.Interaction.MessagePriority.High);
Guid outBoxId = tm.SendSMS(chain.TariffId1, msg.MSISDN, chain.Text1, new Guid("C935B842-1230-DF11-9845-0030488B09DC"), addParams, out errText);
factory.Close();
if (!(outBoxId == Guid.Empty))
{
try
{
Abonent ab = Abonent.GetByMSISDN(msg.MSISDN);
MSMQLogEntry mle = new MSMQLogEntry();
mle.CommandText = "services.DistributeChain";
mle.Parameters.Add("@inboxId", msg.InboxId);
mle.Parameters.Add("@chainId", chainId);
mle.Parameters.Add("@abonentId", ab.DatabaseId);
mle.Parameters.Add("@outboxId", outBoxId);
using (MessageQueue _MSMQLoggerInputQueue = ServiceManager.MSMQLoggerInputQueue)
{
_MSMQLoggerInputQueue.Send(mle);
}
return true;
}
catch (SqlException ex)
{
throw new ApplicationException("Error sending message chain.", ex);
}
}
throw new ApplicationException("Error sending message chain. ChainId= "+chainId.ToString() + " " + errText);
}
private static bool SetSubscription(Statement statement, EntityBase obj, Message msg)
{
DateTime dt1 = DateTime.Now;
Abonent ab = Abonent.GetByMSISDN(msg.MSISDN);
SubscriptionMessage sm = new SubscriptionMessage();
sm.abonentId = ab.DatabaseId;
sm.MSISDN = msg.MSISDN;
Trace.WriteLine("Router: getting resource by channel id");
AnswerMap map = obj as AnswerMap;
if (map == null)
{
AnswerBlock anb = obj as AnswerBlock;
if (anb != null)
map = anb.Map;
}
if (map==null) return false;
ContragentResource resource = GetChannelContragentResource(map.Channel);
if ( resource == null )
{
throw new ApplicationException(string.Format("ActionExecuter: Unable to find ContragentResource for the channel (id='{0},Name='{1}').", map.Channel.ID.ToString(), map.Channel.Name));
}
sm.resourceId = (Guid)resource.ID;
Trace.WriteLine("Router: got resource by channel id: " + sm.resourceId);
sm.smsId = msg.InboxId;
sm.actionTime = DateTime.Now;
switch (statement.CheckAction.Predicate)
{
case CheckActionPredicate.In:
sm.actionType = SubscriptionActionType.Subscribe;
break;
case CheckActionPredicate.NotIn:
sm.actionType = SubscriptionActionType.Unsubscribe;
break;
case CheckActionPredicate.IsEqual:
sm.actionType = SubscriptionActionType.UnsubscribeAll;
break;
}
foreach ( ParameterValue val in statement.ParameterValues )
{
Guid clubId = new Guid(val.Value);
sm.clubs.Add(clubId);
}
using (MessageQueue mq = ServicesConfigurationManager.SubscriptionQueue)
{
mq.Send(sm);
}
DateTime dt2 = DateTime.Now;
TimeSpan ts = dt2-dt1;
Trace.WriteLine(string.Format("SETSUBSCRIPTION: Time: {0} ms", ts.TotalMilliseconds));
return true;
}
private static bool ProcessMacros(IDictionary<string,MacrosProcessor> processors, OutputMessage omsg, ref string errorText)
{
List<Macros> macroses = Macros.GetMacroses(((TextContent)omsg.Content).MsgText);
for(int i=macroses.Count-1;i>=0;i--)
{
Macros m = macroses[i];
MacrosProcessor mp = processors[m.Name];
if (mp!=null)
{
string replaceString = mp.Execute(omsg,m.Parameters);
((TextContent)omsg.Content).MsgText = ((TextContent)omsg.Content).MsgText.Replace(m.Text, replaceString);
}
}
return true;
}
public static bool ProcessMacros(OutputMessage outMsg, ContragentResource cr, ref string errorText)
{
Dictionary<string, MacrosProcessor> processors = new Dictionary<string, MacrosProcessor>();
ContentProcessor cpn = new ContentProcessor(cr);
processors.Add(cpn.MacrosName, cpn);
ServiceNumberProcessor snp = new ServiceNumberProcessor();
processors.Add(snp.MacrosName, snp);
HelpDeskProcessor hdp = new HelpDeskProcessor();
processors.Add(hdp.MacrosName,hdp);
return ProcessMacros(processors, outMsg, ref errorText);
}
internal static ContragentResource GetChannelContragentResource(Channel channel)
{
ContragentResource res = null;
PersistentStorage ps = ChannelConfiguration.DefaultPs;
if (channel!=null && channel.ContragentResource != null)
res = channel.ContragentResource;
if (res == null && channel != null)
{
foreach (ServiceSetting ss in channel.Service.ServiceSettings)
{
if (ss.Name == "SubscriptionContragentResourceName")
{
//Guid id = new Guid(ss.Value);
try
{
res = ps.GetEntitiesByFieldValue(typeof(ContragentResource), "Name", ss.Value)[0] as ContragentResource;
}
catch (Exception ex)
{
throw new Exception(string.Format("Unable to find the contragent resource by it's name, Name = {0}", ss.Value), ex);
}
//if (id != null && id != Guid.Empty)
//{
// res = ps.GetEntityById(typeof(ContragentResource), id) as ContragentResource;
//}
break;
}
}
}
if (res == null)
{
List<EntityBase> l = ps.GetEntitiesByFieldValue(typeof(ContragentResource), "Name", "TV services");
if (l.Count > 0)
res = l[0] as ContragentResource;
}
return res;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.