context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// DataColumnCollectionTest.cs - NUnit Test Cases for System.Data.DataColumnCollection
//
// Authors:
// Franklin Wise <gracenote@earthlink.net>
// Ville Palo <vi64pa@kolumbus.fi>
// Martin Willemoes Hansen <mwh@sysrq.dk>
//
// (C) Copyright 2002 Franklin Wise
// (C) Copyright 2003 Ville Palo
// (C) Copyright 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 NUnit.Framework;
using System;
using System.Data;
using System.Xml;
namespace MonoTests.System.Data
{
[TestFixture]
public class DataColumnCollectionTest : Assertion
{
private DataTable _tbl;
[SetUp]
public void GetReady ()
{
_tbl = new DataTable();
}
//TODO
[Test]
public void AddValidationExceptions()
{
//Set DefaultValue and AutoIncr == true
//And get an exception
}
[Test]
public void Add ()
{
DataTable Table = new DataTable ("test_table");
DataColumnCollection Cols = Table.Columns;
DataColumn C = null;
Cols.Add ();
Cols.Add ();
C = Cols [0];
AssertEquals ("test#01", true, C.AllowDBNull);
AssertEquals ("test#02", false, C.AutoIncrement);
AssertEquals ("test#03", 0L, C.AutoIncrementSeed);
AssertEquals ("test#04", 1L, C.AutoIncrementStep);
AssertEquals ("test#05", "Column1", C.Caption);
AssertEquals ("test#06", "Element", C.ColumnMapping.ToString ());
AssertEquals ("test#07", "Column1", C.ColumnName);
AssertEquals ("test#08", true, C.Container == null);
AssertEquals ("test#09", typeof (string), C.DataType);
AssertEquals ("test#10", DBNull.Value, C.DefaultValue);
AssertEquals ("test#11", false, C.DesignMode);
AssertEquals ("test#12", "", C.Expression);
AssertEquals ("test#13", 0, C.ExtendedProperties.Count);
AssertEquals ("test#14", -1, C.MaxLength);
AssertEquals ("test#15", "", C.Namespace);
AssertEquals ("test#16", 0, C.Ordinal);
AssertEquals ("test#17", "", C.Prefix);
AssertEquals ("test#18", false, C.ReadOnly);
AssertEquals ("test#19", null, C.Site);
AssertEquals ("test#20", "test_table", C.Table.TableName);
AssertEquals ("test#21", "Column1", C.ToString ());
AssertEquals ("test#22", false, C.Unique);
C = Cols [1];
AssertEquals ("test#23", true, C.AllowDBNull);
AssertEquals ("test#24", false, C.AutoIncrement);
AssertEquals ("test#25", 0L, C.AutoIncrementSeed);
AssertEquals ("test#26", 1L, C.AutoIncrementStep);
AssertEquals ("test#27", "Column2", C.Caption);
AssertEquals ("test#28", "Element", C.ColumnMapping.ToString ());
AssertEquals ("test#29", "Column2", C.ColumnName);
AssertEquals ("test#30", true, C.Container == null);
AssertEquals ("test#31", typeof (string), C.DataType);
AssertEquals ("test#32", DBNull.Value, C.DefaultValue);
AssertEquals ("test#33", false, C.DesignMode);
AssertEquals ("test#34", "", C.Expression);
AssertEquals ("test#35", 0, C.ExtendedProperties.Count);
AssertEquals ("test#36", -1, C.MaxLength);
AssertEquals ("test#37", "", C.Namespace);
AssertEquals ("test#38", 1, C.Ordinal);
AssertEquals ("test#39", "", C.Prefix);
AssertEquals ("test#40", false, C.ReadOnly);
AssertEquals ("test#41", null, C.Site);
AssertEquals ("test#42", "test_table", C.Table.TableName);
AssertEquals ("test#43", "Column2", C.ToString ());
AssertEquals ("test#44", false, C.Unique);
Cols.Add ("test1", typeof (int), "");
Cols.Add ("test2", typeof (string), "Column1 + Column2");
C = Cols [2];
AssertEquals ("test#45", true, C.AllowDBNull);
AssertEquals ("test#46", false, C.AutoIncrement);
AssertEquals ("test#47", 0L, C.AutoIncrementSeed);
AssertEquals ("test#48", 1L, C.AutoIncrementStep);
AssertEquals ("test#49", "test1", C.Caption);
AssertEquals ("test#50", "Element", C.ColumnMapping.ToString ());
AssertEquals ("test#51", "test1", C.ColumnName);
AssertEquals ("test#52", true, C.Container == null);
AssertEquals ("test#53", typeof (int), C.DataType);
AssertEquals ("test#54", DBNull.Value, C.DefaultValue);
AssertEquals ("test#55", false, C.DesignMode);
AssertEquals ("test#56", "", C.Expression);
AssertEquals ("test#57", 0, C.ExtendedProperties.Count);
AssertEquals ("test#58", -1, C.MaxLength);
AssertEquals ("test#59", "", C.Namespace);
AssertEquals ("test#60", 2, C.Ordinal);
AssertEquals ("test#61", "", C.Prefix);
AssertEquals ("test#62", false, C.ReadOnly);
AssertEquals ("test#63", null, C.Site);
AssertEquals ("test#64", "test_table", C.Table.TableName);
AssertEquals ("test#65", "test1", C.ToString ());
AssertEquals ("test#66", false, C.Unique);
C = Cols [3];
AssertEquals ("test#67", true, C.AllowDBNull);
AssertEquals ("test#68", false, C.AutoIncrement);
AssertEquals ("test#69", 0L, C.AutoIncrementSeed);
AssertEquals ("test#70", 1L, C.AutoIncrementStep);
AssertEquals ("test#71", "test2", C.Caption);
AssertEquals ("test#72", "Element", C.ColumnMapping.ToString ());
AssertEquals ("test#73", "test2", C.ColumnName);
AssertEquals ("test#74", true, C.Container == null);
AssertEquals ("test#75", typeof (string), C.DataType);
AssertEquals ("test#76", DBNull.Value, C.DefaultValue);
AssertEquals ("test#77", false, C.DesignMode);
AssertEquals ("test#78", "Column1 + Column2", C.Expression);
AssertEquals ("test#79", 0, C.ExtendedProperties.Count);
AssertEquals ("test#80", -1, C.MaxLength);
AssertEquals ("test#81", "", C.Namespace);
AssertEquals ("test#82", 3, C.Ordinal);
AssertEquals ("test#83", "", C.Prefix);
AssertEquals ("test#84", true, C.ReadOnly);
AssertEquals ("test#85", null, C.Site);
AssertEquals ("test#86", "test_table", C.Table.TableName);
AssertEquals ("test#87", "test2 + Column1 + Column2", C.ToString ());
AssertEquals ("test#88", false, C.Unique);
C = new DataColumn ("test3", typeof (int));
Cols.Add (C);
C = Cols [4];
AssertEquals ("test#89", true, C.AllowDBNull);
AssertEquals ("test#90", false, C.AutoIncrement);
AssertEquals ("test#91", 0L, C.AutoIncrementSeed);
AssertEquals ("test#92", 1L, C.AutoIncrementStep);
AssertEquals ("test#93", "test3", C.Caption);
AssertEquals ("test#94", "Element", C.ColumnMapping.ToString ());
AssertEquals ("test#95", "test3", C.ColumnName);
AssertEquals ("test#96", true, C.Container == null);
AssertEquals ("test#97", typeof (int), C.DataType);
AssertEquals ("test#98", DBNull.Value, C.DefaultValue);
AssertEquals ("test#99", false, C.DesignMode);
AssertEquals ("test#100", "", C.Expression);
AssertEquals ("test#101", 0, C.ExtendedProperties.Count);
AssertEquals ("test#102", -1, C.MaxLength);
AssertEquals ("test#103", "", C.Namespace);
AssertEquals ("test#104", 4, C.Ordinal);
AssertEquals ("test#105", "", C.Prefix);
AssertEquals ("test#106", false, C.ReadOnly);
AssertEquals ("test#107", null, C.Site);
AssertEquals ("test#108", "test_table", C.Table.TableName);
AssertEquals ("test#109", "test3", C.ToString ());
AssertEquals ("test#110", false, C.Unique);
}
[Test]
public void AddExceptions ()
{
DataTable Table = new DataTable ("test_table");
DataTable Table2 = new DataTable ("test_table2");
DataColumnCollection Cols = Table.Columns;
DataColumn C = null;
try {
Cols.Add (C);
Fail ("test#01");
} catch (Exception e) {
AssertEquals ("test#02", typeof (ArgumentNullException), e.GetType ());
}
C = new DataColumn ("test");
Cols.Add (C);
try {
Cols.Add (C);
Fail ("test#04");
} catch (ArgumentException e) {
// AssertEquals ("test#05", typeof (ArgumentException), e.GetType ());
// AssertEquals ("test#06", "Column 'test' already belongs to this or another DataTable.", e.Message);
}
try {
Table2.Columns.Add (C);
Fail ("test#07");
} catch (ArgumentException e) {
// AssertEquals ("test#08", typeof (ArgumentException), e.GetType ());
// AssertEquals ("test#09", "Column 'test' already belongs to this or another DataTable.", e.Message);
}
DataColumn C2 = new DataColumn ("test");
try {
Cols.Add (C2);
Fail ("test#10");
} catch (DuplicateNameException e) {
// AssertEquals ("test#11", typeof (DuplicateNameException), e.GetType ());
// AssertEquals ("test#12", "A DataColumn named 'test' already belongs to this DataTable.", e.Message);
}
try {
Cols.Add ("test2", typeof (string), "substring ('fdsafewq', 2)");
Fail ("test#13");
} catch (InvalidExpressionException e) {
// AssertEquals ("test#14", true, e is InvalidExpressionException);
// AssertEquals ("test#15", "Expression 'substring ('fdsafewq', 2)' is invalid.", e.Message);
}
}
[Test]
public void AddRange ()
{
DataTable Table = new DataTable ("test_table");
DataTable Table2 = new DataTable ("test_table2");
DataColumnCollection Cols = Table.Columns;
DataColumn C = null;
DataColumn [] ColArray = new DataColumn [2];
C = new DataColumn ("test1");
ColArray [0] = C;
C = new DataColumn ("test2");
C.AllowDBNull = false;
C.Caption = "Test_caption";
C.DataType = typeof (XmlReader);
ColArray [1] = C;
Cols.AddRange (ColArray);
C = Cols [0];
AssertEquals ("test#01", true, C.AllowDBNull);
AssertEquals ("test#02", false, C.AutoIncrement);
AssertEquals ("test#03", 0L, C.AutoIncrementSeed);
AssertEquals ("test#04", 1L, C.AutoIncrementStep);
AssertEquals ("test#05", "test1", C.Caption);
AssertEquals ("test#06", "Element", C.ColumnMapping.ToString ());
AssertEquals ("test#07", "test1", C.ColumnName);
AssertEquals ("test#08", true, C.Container == null);
AssertEquals ("test#09", typeof (string), C.DataType);
AssertEquals ("test#10", DBNull.Value, C.DefaultValue);
AssertEquals ("test#11", false, C.DesignMode);
AssertEquals ("test#12", "", C.Expression);
AssertEquals ("test#13", 0, C.ExtendedProperties.Count);
AssertEquals ("test#14", -1, C.MaxLength);
AssertEquals ("test#15", "", C.Namespace);
AssertEquals ("test#16", 0, C.Ordinal);
AssertEquals ("test#17", "", C.Prefix);
AssertEquals ("test#18", false, C.ReadOnly);
AssertEquals ("test#19", null, C.Site);
AssertEquals ("test#20", "test_table", C.Table.TableName);
AssertEquals ("test#21", "test1", C.ToString ());
AssertEquals ("test#22", false, C.Unique);
C = Cols [1];
AssertEquals ("test#01", false, C.AllowDBNull);
AssertEquals ("test#02", false, C.AutoIncrement);
AssertEquals ("test#03", 0L, C.AutoIncrementSeed);
AssertEquals ("test#04", 1L, C.AutoIncrementStep);
AssertEquals ("test#05", "Test_caption", C.Caption);
AssertEquals ("test#06", "Element", C.ColumnMapping.ToString ());
AssertEquals ("test#07", "test2", C.ColumnName);
AssertEquals ("test#08", true, C.Container == null);
AssertEquals ("test#09", typeof (XmlReader), C.DataType);
AssertEquals ("test#10", DBNull.Value, C.DefaultValue);
AssertEquals ("test#11", false, C.DesignMode);
AssertEquals ("test#12", "", C.Expression);
AssertEquals ("test#13", 0, C.ExtendedProperties.Count);
AssertEquals ("test#14", -1, C.MaxLength);
AssertEquals ("test#15", "", C.Namespace);
AssertEquals ("test#16", 1, C.Ordinal);
AssertEquals ("test#17", "", C.Prefix);
AssertEquals ("test#18", false, C.ReadOnly);
AssertEquals ("test#19", null, C.Site);
AssertEquals ("test#20", "test_table", C.Table.TableName);
AssertEquals ("test#21", "test2", C.ToString ());
AssertEquals ("test#22", false, C.Unique);
}
[Test]
public void CanRemove ()
{
DataTable Table = new DataTable ("test_table");
DataTable Table2 = new DataTable ("test_table_2");
DataColumnCollection Cols = Table.Columns;
DataColumn C = new DataColumn ("test1");
Cols.Add ();
// LAMESPEC: MSDN says that if C doesn't belong to Cols
// Exception is thrown.
AssertEquals ("test#01", false, Cols.CanRemove (C));
Cols.Add (C);
AssertEquals ("test#02", true, Cols.CanRemove (C));
C = new DataColumn ();
C.Expression = "test1 + 2";
Cols.Add (C);
C = Cols ["test2"];
AssertEquals ("test#03", false, Cols.CanRemove (C));
C = new DataColumn ("t");
Table2.Columns.Add (C);
DataColumnCollection Cols2 = Table2.Columns;
AssertEquals ("test#04", true, Cols2.CanRemove (C));
DataRelation Rel = new DataRelation ("Rel", Table.Columns [0], Table2.Columns [0]);
DataSet Set = new DataSet ();
Set.Tables.Add (Table);
Set.Tables.Add (Table2);
Set.Relations.Add (Rel);
AssertEquals ("test#05", false, Cols2.CanRemove (C));
AssertEquals ("test#06", false, Cols.CanRemove (null));
}
[Test]
public void Clear ()
{
DataTable Table = new DataTable ("test_table");
DataTable Table2 = new DataTable ("test_table2");
DataSet Set = new DataSet ();
Set.Tables.Add (Table);
Set.Tables.Add (Table2);
DataColumnCollection Cols = Table.Columns;
DataColumnCollection Cols2 = Table2.Columns;
Cols.Add ();
Cols.Add ("testi");
Cols.Clear ();
AssertEquals ("test#01", 0, Cols.Count);
Cols.Add ();
Cols.Add ("testi");
Cols2.Add ();
Cols2.Add ();
DataRelation Rel = new DataRelation ("Rel", Cols [0], Cols2 [0]);
Set.Relations.Add (Rel);
try {
Cols.Clear ();
Fail ("test#02");
} catch (Exception e) {
AssertEquals ("test#03", typeof (ArgumentException), e.GetType ());
AssertEquals ("test#04", "Cannot remove this column, because it is part of the parent key for relationship Rel.", e.Message);
}
}
[Test]
public void Contains ()
{
DataTable Table = new DataTable ("test_table");
DataColumnCollection Cols = Table.Columns;
Cols.Add ("test");
Cols.Add ("tesT2");
AssertEquals ("test#01", true, Cols.Contains ("test"));
AssertEquals ("test#02", false, Cols.Contains ("_test"));
AssertEquals ("test#03", true, Cols.Contains ("TEST"));
Table.CaseSensitive = true;
AssertEquals ("test#04", true, Cols.Contains ("TEST"));
AssertEquals ("test#05", true, Cols.Contains ("test2"));
AssertEquals ("test#06", false, Cols.Contains ("_test2"));
AssertEquals ("test#07", true, Cols.Contains ("TEST2"));
}
[Test]
public void CopyTo ()
{
DataTable Table = new DataTable ("test_table");
DataColumnCollection Cols = Table.Columns;
Cols.Add ("test");
Cols.Add ("test2");
Cols.Add ("test3");
Cols.Add ("test4");
DataColumn [] array = new DataColumn [4];
Cols.CopyTo (array, 0);
AssertEquals ("test#01", 4, array.Length);
AssertEquals ("test#02", "test", array [0].ColumnName);
AssertEquals ("test#03", "test2", array [1].ColumnName);
AssertEquals ("test#04", "test3", array [2].ColumnName);
AssertEquals ("test#05", "test4", array [3].ColumnName);
array = new DataColumn [6];
Cols.CopyTo (array, 2);
AssertEquals ("test#06", 6, array.Length);
AssertEquals ("test#07", "test", array [2].ColumnName);
AssertEquals ("test#08", "test2", array [3].ColumnName);
AssertEquals ("test#09", "test3", array [4].ColumnName);
AssertEquals ("test#10", "test4", array [5].ColumnName);
AssertEquals ("test#11", null, array [0]);
AssertEquals ("test#12", null, array [1]);
}
[Test]
public void Equals ()
{
DataTable Table = new DataTable ("test_table");
DataTable Table2 = new DataTable ("test_table");
DataColumnCollection Cols = Table.Columns;
DataColumnCollection Cols2 = Table2.Columns;
AssertEquals ("test#01", false, Cols.Equals (Cols2));
AssertEquals ("test#02", false, Cols2.Equals (Cols));
AssertEquals ("test#03", false, Object.Equals (Cols, Cols2));
AssertEquals ("test#04", true, Cols.Equals (Cols));
AssertEquals ("test#05", true, Cols2.Equals (Cols2));
AssertEquals ("test#06", true, Object.Equals (Cols2, Cols2));
}
[Test]
public void IndexOf ()
{
DataTable Table = new DataTable ("test_table");
DataColumnCollection Cols = Table.Columns;
Cols.Add ("test");
Cols.Add ("test2");
Cols.Add ("test3");
Cols.Add ("test4");
AssertEquals ("test#01", 0, Cols.IndexOf ("test"));
AssertEquals ("test#02", 1, Cols.IndexOf ("TEST2"));
Table.CaseSensitive = true;
AssertEquals ("test#03", 1, Cols.IndexOf ("TEST2"));
AssertEquals ("test#04", 3, Cols.IndexOf (Cols [3]));
DataColumn C = new DataColumn ("error");
AssertEquals ("test#05", -1, Cols.IndexOf (C));
AssertEquals ("test#06", -1, Cols.IndexOf ("_error_"));
}
[Test]
public void Remove ()
{
DataTable Table = new DataTable ("test_table");
DataColumnCollection Cols = Table.Columns;
Cols.Add ("test");
Cols.Add ("test2");
Cols.Add ("test3");
Cols.Add ("test4");
AssertEquals ("test#01", 4, Cols.Count);
Cols.Remove ("test2");
AssertEquals ("test#02", 3, Cols.Count);
Cols.Remove ("TEST3");
AssertEquals ("test#03", 2, Cols.Count);
try {
Cols.Remove ("_test_");
Fail ("test#04");
} catch (Exception e) {
AssertEquals ("test#05", typeof (ArgumentException), e.GetType ());
AssertEquals ("test#06", "Column '_test_' does not belong to table test_table.", e.Message);
}
Cols.Add ();
Cols.Add ();
Cols.Add ();
Cols.Add ();
AssertEquals ("test#07", 6, Cols.Count);
Cols.Remove (Cols [0]);
Cols.Remove (Cols [0]);
AssertEquals ("test#08", 4, Cols.Count);
AssertEquals ("test#09", "Column1", Cols [0].ColumnName);
try {
Cols.Remove (new DataColumn ("Column10"));
Fail ("test#10");
} catch (Exception e) {
AssertEquals ("test#11", typeof (ArgumentException), e.GetType ());
AssertEquals ("test#12", "Cannot remove a column that doesn't belong to this table.", e.Message);
}
Cols.Add ();
Cols.Add ();
Cols.Add ();
Cols.Add ();
AssertEquals ("test#13", 8, Cols.Count);
Cols.RemoveAt (7);
Cols.RemoveAt (1);
Cols.RemoveAt (0);
Cols.RemoveAt (0);
AssertEquals ("test#14", 4, Cols.Count);
AssertEquals ("test#15", "Column4", Cols [0].ColumnName);
AssertEquals ("test#16", "Column5", Cols [1].ColumnName);
try {
Cols.RemoveAt (10);
Fail ("test#17");
} catch (Exception e) {
AssertEquals ("test#18", typeof (IndexOutOfRangeException), e.GetType ());
AssertEquals ("test#19", "Cannot find column 10.", e.Message);
}
}
[Test]
public void ToStringTest ()
{
DataTable Table = new DataTable ("test_table");
DataColumnCollection Cols = Table.Columns;
Cols.Add ("test");
Cols.Add ("test2");
Cols.Add ("test3");
AssertEquals ("test#01", "System.Data.DataColumnCollection", Cols.ToString ());
}
}
}
| |
//Copyright (C) 2005 Richard J. Northedge
//
// 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 program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the OnePassDataIndexer.java source file found in the
//original java implementation of MaxEnt. That source file contains the following header:
// Copyright (C) 2001 Jason Baldridge and Gann Bierner
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser 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.
using System;
using System.Collections.Generic;
namespace SharpEntropy
{
/// <summary>
/// An indexer for maxent model data which handles cutoffs for uncommon
/// contextual predicates and provides a unique integer index for each of the
/// predicates. The data structures built in the constructor of this class are
/// used by the GIS trainer.
/// </summary>
/// <author>
/// Jason Baldridge
/// </author>
/// <author>
/// Richard J. Northedge
/// </author>
/// <version>
/// based on OnePassDataIndexer.java, $Revision: 1.1 $, $Date: 2003/12/13 16:41:29 $
/// </version>
public class OnePassDataIndexer : AbstractDataIndexer
{
/// <summary>
/// One argument constructor for OnePassDataIndexer which calls the two argument
/// constructor assuming no cutoff.
/// </summary>
/// <param name="eventReader">
/// An ITrainingEventReader which contains the a list of all the Events
/// seen in the training data.
/// </param>
public OnePassDataIndexer(ITrainingEventReader eventReader) : this(eventReader, 0)
{
}
/// <summary>
/// Two argument constructor for OnePassDataIndexer.
/// </summary>
/// <param name="eventReader">
/// An ITrainingEventReader which contains the a list of all the Events
/// seen in the training data.
/// </param>
/// <param name="cutoff">
/// The minimum number of times a predicate must have been
/// observed in order to be included in the model.
/// </param>
public OnePassDataIndexer(ITrainingEventReader eventReader, int cutoff)
{
Dictionary<string, int> predicateIndex;
List<TrainingEvent> events;
List<ComparableEvent> eventsToCompare;
predicateIndex = new Dictionary<string, int>();
//NotifyProgress("Indexing events using cutoff of " + cutoff + "\n");
//NotifyProgress("\tComputing event counts... ");
events = ComputeEventCounts(eventReader, predicateIndex, cutoff);
//NotifyProgress("done. " + events.Count + " events");
//NotifyProgress("\tIndexing... ");
eventsToCompare = Index(events, predicateIndex);
//NotifyProgress("done.");
//NotifyProgress("Sorting and merging oEvents... ");
SortAndMerge(eventsToCompare);
//NotifyProgress("Done indexing.");
}
/// <summary>
/// Reads events from <tt>eventReader</tt> into a List<TrainingEvent>. The
/// predicates associated with each event are counted and any which
/// occur at least <tt>cutoff</tt> times are added to the
/// <tt>predicatesInOut</tt> dictionary along with a unique integer index.
/// </summary>
/// <param name="eventReader">
/// an <code>ITrainingEventReader</code> value
/// </param>
/// <param name="predicatesInOut">
/// a <code>Dictionary</code> value
/// </param>
/// <param name="cutoff">
/// an <code>int</code> value
/// </param>
/// <returns>
/// an <code>List of TrainingEvents</code> value
/// </returns>
private List<TrainingEvent> ComputeEventCounts(ITrainingEventReader eventReader, Dictionary<string, int> predicatesInOut, int cutoff)
{
var counter = new Dictionary<string, int>();
var events = new List<TrainingEvent>();
int predicateIndex = 0;
while (eventReader.HasNext())
{
TrainingEvent trainingEvent = eventReader.ReadNextEvent();
events.Add(trainingEvent);
string[] eventContext = trainingEvent.Context;
for (int currentEventContext = 0; currentEventContext < eventContext.Length; currentEventContext++)
{
if (!predicatesInOut.ContainsKey(eventContext[currentEventContext]))
{
if (counter.ContainsKey(eventContext[currentEventContext]))
{
counter[eventContext[currentEventContext]]++;
}
else
{
counter.Add(eventContext[currentEventContext], 1);
}
if (counter[eventContext[currentEventContext]] >= cutoff)
{
predicatesInOut.Add(eventContext[currentEventContext], predicateIndex++);
counter.Remove(eventContext[currentEventContext]);
}
}
}
}
return events;
}
private List<ComparableEvent> Index(List<TrainingEvent> events, Dictionary<string, int> predicateIndex)
{
var map = new Dictionary<string, int>();
int eventCount = events.Count;
int outcomeCount = 0;
var eventsToCompare = new List<ComparableEvent>(eventCount);
var indexedContext = new List<int>();
for (int eventIndex = 0; eventIndex < eventCount; eventIndex++)
{
TrainingEvent currentTrainingEvent = events[eventIndex];
string[] eventContext = currentTrainingEvent.Context;
ComparableEvent comparableEvent;
int outcomeIndex;
string outcome = currentTrainingEvent.Outcome;
if (map.ContainsKey(outcome))
{
outcomeIndex = map[outcome];
}
else
{
outcomeIndex = outcomeCount++;
map.Add(outcome, outcomeIndex);
}
for (int currentEventContext = 0; currentEventContext < eventContext.Length; currentEventContext++)
{
string predicate = eventContext[currentEventContext];
if (predicateIndex.ContainsKey(predicate))
{
indexedContext.Add(predicateIndex[predicate]);
}
}
// drop events with no active features
if (indexedContext.Count > 0)
{
comparableEvent = new ComparableEvent(outcomeIndex, indexedContext.ToArray());
eventsToCompare.Add(comparableEvent);
}
else
{
//"Dropped event " + oEvent.Outcome + ":" + oEvent.Context);
}
// recycle the list
indexedContext.Clear();
}
SetOutcomeLabels(ToIndexedStringArray(map));
SetPredicateLabels(ToIndexedStringArray(predicateIndex));
return eventsToCompare;
}
}
}
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class FContainer : FNode
{
protected List<FNode> _childNodes = new List<FNode>(5);
private int _oldChildNodesHash = 0;
private bool _shouldSortByZ = false; //don't turn this on unless you really need it, it'll do a sort every redraw
public FContainer () : base()
{
}
override public void Redraw(bool shouldForceDirty, bool shouldUpdateDepth)
{
bool wasMatrixDirty = _isMatrixDirty;
bool wasAlphaDirty = _isAlphaDirty;
UpdateDepthMatrixAlpha(shouldForceDirty, shouldUpdateDepth);
int childCount = _childNodes.Count;
for(int c = 0; c<childCount; c++)
{
_childNodes[c].Redraw(shouldForceDirty || wasMatrixDirty || wasAlphaDirty, shouldUpdateDepth); //if the matrix was dirty or we're supposed to force it, do it!
}
}
override public void HandleAddedToStage()
{
if(!_isOnStage)
{
_isOnStage = true;
int childCount = _childNodes.Count;
for(int c = 0; c<childCount; c++)
{
FNode childNode = _childNodes[c];
childNode.stage = _stage;
childNode.HandleAddedToStage();
}
if(_shouldSortByZ)
{
Futile.instance.SignalUpdate += HandleUpdateAndSort;
}
}
}
override public void HandleRemovedFromStage()
{
if(_isOnStage)
{
_isOnStage = false;
int childCount = _childNodes.Count;
for(int c = 0; c<childCount; c++)
{
FNode childNode = _childNodes[c];
childNode.HandleRemovedFromStage();
childNode.stage = null;
}
if(_shouldSortByZ)
{
Futile.instance.SignalUpdate -= HandleUpdateAndSort;
}
}
}
private void HandleUpdateAndSort()
{
bool didChildOrderChangeAfterSort = SortByZ();
if(didChildOrderChangeAfterSort) //sort the order, and then if the child order was changed, repopulate the renderlayer
{
if(_isOnStage) _stage.HandleFacetsChanged();
}
}
public void AddChild(FNode node)
{
int nodeIndex = _childNodes.IndexOf(node);
if(nodeIndex == -1) //add it if it's not a child
{
node.HandleAddedToContainer(this);
_childNodes.Add(node);
if(_isOnStage)
{
node.stage = _stage;
node.HandleAddedToStage();
}
}
else if(nodeIndex != _childNodes.Count-1) //if node is already a child, put it at the top of the children if it's not already
{
_childNodes.RemoveAt(nodeIndex);
_childNodes.Add(node);
if(_isOnStage) _stage.HandleFacetsChanged();
}
}
public void AddChildAtIndex(FNode node, int newIndex)
{
int nodeIndex = _childNodes.IndexOf(node);
if(newIndex > _childNodes.Count) //if it's past the end, make it at the end
{
newIndex = _childNodes.Count;
}
if(nodeIndex == newIndex) return; //if it's already at the right index, just leave it there
if(nodeIndex == -1) //add it if it's not a child
{
node.HandleAddedToContainer(this);
_childNodes.Insert(newIndex, node);
if(_isOnStage)
{
node.stage = _stage;
node.HandleAddedToStage();
}
}
else //if node is already a child, move it to the desired index
{
_childNodes.RemoveAt(nodeIndex);
if(nodeIndex < newIndex)
{
_childNodes.Insert(newIndex-1, node); //gotta subtract 1 to account for it moving in the order
}
else
{
_childNodes.Insert(newIndex, node);
}
if(_isOnStage) _stage.HandleFacetsChanged();
}
}
public void RemoveChild(FNode node)
{
if(node.container != this) return; //I ain't your daddy
node.HandleRemovedFromContainer();
if(_isOnStage)
{
node.HandleRemovedFromStage();
node.stage = null;
}
_childNodes.Remove(node);
}
public void RemoveAllChildren()
{
int childCount = _childNodes.Count;
for(int c = 0; c<childCount; c++)
{
FNode node = _childNodes[c];
node.HandleRemovedFromContainer();
if(_isOnStage)
{
node.HandleRemovedFromStage();
node.stage = null;
}
}
_childNodes.Clear();
}
public int GetChildCount()
{
return _childNodes.Count;
}
public FNode GetChildAt(int childIndex)
{
return _childNodes[childIndex];
}
public bool shouldSortByZ
{
get {return _shouldSortByZ;}
set
{
if(_shouldSortByZ != value)
{
_shouldSortByZ = value;
if(_shouldSortByZ)
{
if(_isOnStage)
{
Futile.instance.SignalUpdate += HandleUpdateAndSort;
}
}
else
{
if(_isOnStage)
{
Futile.instance.SignalUpdate -= HandleUpdateAndSort;
}
}
}
}
}
private static int ZComparison(FNode a, FNode b)
{
float delta = a.sortZ - b.sortZ;
if(delta < 0) return -1;
if(delta > 0) return 1;
return 0;
}
private bool SortByZ() //returns true if the childNodes changed, false if they didn't
{
//using InsertionSort because it's stable (meaning equal values keep the same order)
//this is unlike List.Sort, which is unstable, so things would constantly shift if equal.
_childNodes.InsertionSort(ZComparison);
//check if the order has changed, and if it has, update the quads/depth order
//http://stackoverflow.com/questions/3030759/arrays-lists-and-computing-hashvalues-vb-c
int hash = 269;
unchecked //don't throw int overflow exceptions
{
int childCount = _childNodes.Count;
for(int c = 0; c<childCount; c++)
{
hash = (hash * 17) + _childNodes[c].GetHashCode();
}
}
if(hash != _oldChildNodesHash)
{
_oldChildNodesHash = hash;
return true; //order has changed
}
return false; //order hasn't changed
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Communication;
using Apache.Ignite.Core.Communication.Tcp;
using Apache.Ignite.Core.DataStructures.Configuration;
using Apache.Ignite.Core.Discovery;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.SwapSpace;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.SwapSpace;
using Apache.Ignite.Core.Transactions;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter;
/// <summary>
/// Grid configuration.
/// </summary>
public class IgniteConfiguration
{
/// <summary>
/// Default initial JVM memory in megabytes.
/// </summary>
public const int DefaultJvmInitMem = -1;
/// <summary>
/// Default maximum JVM memory in megabytes.
/// </summary>
public const int DefaultJvmMaxMem = -1;
/// <summary>
/// Default metrics expire time.
/// </summary>
public static readonly TimeSpan DefaultMetricsExpireTime = TimeSpan.MaxValue;
/// <summary>
/// Default metrics history size.
/// </summary>
public const int DefaultMetricsHistorySize = 10000;
/// <summary>
/// Default metrics log frequency.
/// </summary>
public static readonly TimeSpan DefaultMetricsLogFrequency = TimeSpan.FromMilliseconds(60000);
/// <summary>
/// Default metrics update frequency.
/// </summary>
public static readonly TimeSpan DefaultMetricsUpdateFrequency = TimeSpan.FromMilliseconds(2000);
/// <summary>
/// Default network timeout.
/// </summary>
public static readonly TimeSpan DefaultNetworkTimeout = TimeSpan.FromMilliseconds(5000);
/// <summary>
/// Default network retry delay.
/// </summary>
public static readonly TimeSpan DefaultNetworkSendRetryDelay = TimeSpan.FromMilliseconds(1000);
/// <summary>
/// Default failure detection timeout.
/// </summary>
public static readonly TimeSpan DefaultFailureDetectionTimeout = TimeSpan.FromSeconds(10);
/** */
private TimeSpan? _metricsExpireTime;
/** */
private int? _metricsHistorySize;
/** */
private TimeSpan? _metricsLogFrequency;
/** */
private TimeSpan? _metricsUpdateFrequency;
/** */
private int? _networkSendRetryCount;
/** */
private TimeSpan? _networkSendRetryDelay;
/** */
private TimeSpan? _networkTimeout;
/** */
private bool? _isDaemon;
/** */
private bool? _isLateAffinityAssignment;
/** */
private bool? _clientMode;
/** */
private TimeSpan? _failureDetectionTimeout;
/// <summary>
/// Default network retry count.
/// </summary>
public const int DefaultNetworkSendRetryCount = 3;
/// <summary>
/// Default late affinity assignment mode.
/// </summary>
public const bool DefaultIsLateAffinityAssignment = true;
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration"/> class.
/// </summary>
public IgniteConfiguration()
{
JvmInitialMemoryMb = DefaultJvmInitMem;
JvmMaxMemoryMb = DefaultJvmMaxMem;
}
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration"/> class.
/// </summary>
/// <param name="configuration">The configuration to copy.</param>
public IgniteConfiguration(IgniteConfiguration configuration)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var marsh = new Marshaller(configuration.BinaryConfiguration);
configuration.Write(marsh.StartMarshal(stream));
stream.SynchronizeOutput();
stream.Seek(0, SeekOrigin.Begin);
ReadCore(marsh.StartUnmarshal(stream));
}
CopyLocalProperties(configuration);
}
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration"/> class from a reader.
/// </summary>
/// <param name="binaryReader">The binary reader.</param>
internal IgniteConfiguration(BinaryReader binaryReader)
{
Read(binaryReader);
}
/// <summary>
/// Writes this instance to a writer.
/// </summary>
/// <param name="writer">The writer.</param>
internal void Write(BinaryWriter writer)
{
Debug.Assert(writer != null);
// Simple properties
writer.WriteBooleanNullable(_clientMode);
writer.WriteIntArray(IncludedEventTypes == null ? null : IncludedEventTypes.ToArray());
writer.WriteTimeSpanAsLongNullable(_metricsExpireTime);
writer.WriteIntNullable(_metricsHistorySize);
writer.WriteTimeSpanAsLongNullable(_metricsLogFrequency);
writer.WriteTimeSpanAsLongNullable(_metricsUpdateFrequency);
writer.WriteIntNullable(_networkSendRetryCount);
writer.WriteTimeSpanAsLongNullable(_networkSendRetryDelay);
writer.WriteTimeSpanAsLongNullable(_networkTimeout);
writer.WriteString(WorkDirectory);
writer.WriteString(Localhost);
writer.WriteBooleanNullable(_isDaemon);
writer.WriteBooleanNullable(_isLateAffinityAssignment);
writer.WriteTimeSpanAsLongNullable(_failureDetectionTimeout);
// Cache config
var caches = CacheConfiguration;
if (caches == null)
writer.WriteInt(0);
else
{
writer.WriteInt(caches.Count);
foreach (var cache in caches)
cache.Write(writer);
}
// Discovery config
var disco = DiscoverySpi;
if (disco != null)
{
writer.WriteBoolean(true);
var tcpDisco = disco as TcpDiscoverySpi;
if (tcpDisco == null)
throw new InvalidOperationException("Unsupported discovery SPI: " + disco.GetType());
tcpDisco.Write(writer);
}
else
writer.WriteBoolean(false);
// Communication config
var comm = CommunicationSpi;
if (comm != null)
{
writer.WriteBoolean(true);
var tcpComm = comm as TcpCommunicationSpi;
if (tcpComm == null)
throw new InvalidOperationException("Unsupported communication SPI: " + comm.GetType());
tcpComm.Write(writer);
}
else
writer.WriteBoolean(false);
// Binary config
if (BinaryConfiguration != null)
{
writer.WriteBoolean(true);
if (BinaryConfiguration.CompactFooterInternal != null)
{
writer.WriteBoolean(true);
writer.WriteBoolean(BinaryConfiguration.CompactFooter);
}
else
{
writer.WriteBoolean(false);
}
// Send only descriptors with non-null EqualityComparer to preserve old behavior where
// remote nodes can have no BinaryConfiguration.
var types = writer.Marshaller.GetUserTypeDescriptors().Where(x => x.EqualityComparer != null).ToList();
writer.WriteInt(types.Count);
foreach (var type in types)
{
writer.WriteString(BinaryUtils.SimpleTypeName(type.TypeName));
writer.WriteBoolean(type.IsEnum);
BinaryEqualityComparerSerializer.Write(writer, type.EqualityComparer);
}
}
else
{
writer.WriteBoolean(false);
}
// User attributes
var attrs = UserAttributes;
if (attrs == null)
writer.WriteInt(0);
else
{
writer.WriteInt(attrs.Count);
foreach (var pair in attrs)
{
writer.WriteString(pair.Key);
writer.Write(pair.Value);
}
}
// Atomic
if (AtomicConfiguration != null)
{
writer.WriteBoolean(true);
writer.WriteInt(AtomicConfiguration.AtomicSequenceReserveSize);
writer.WriteInt(AtomicConfiguration.Backups);
writer.WriteInt((int) AtomicConfiguration.CacheMode);
}
else
writer.WriteBoolean(false);
// Tx
if (TransactionConfiguration != null)
{
writer.WriteBoolean(true);
writer.WriteInt(TransactionConfiguration.PessimisticTransactionLogSize);
writer.WriteInt((int) TransactionConfiguration.DefaultTransactionConcurrency);
writer.WriteInt((int) TransactionConfiguration.DefaultTransactionIsolation);
writer.WriteLong((long) TransactionConfiguration.DefaultTimeout.TotalMilliseconds);
writer.WriteInt((int) TransactionConfiguration.PessimisticTransactionLogLinger.TotalMilliseconds);
}
else
writer.WriteBoolean(false);
// Swap space
SwapSpaceSerializer.Write(writer, SwapSpaceSpi);
}
/// <summary>
/// Validates this instance and outputs information to the log, if necessary.
/// </summary>
internal void Validate(ILogger log)
{
Debug.Assert(log != null);
var ccfg = CacheConfiguration;
if (ccfg != null)
{
foreach (var cfg in ccfg)
cfg.Validate(log);
}
}
/// <summary>
/// Reads data from specified reader into current instance.
/// </summary>
/// <param name="r">The binary reader.</param>
private void ReadCore(BinaryReader r)
{
// Simple properties
_clientMode = r.ReadBooleanNullable();
IncludedEventTypes = r.ReadIntArray();
_metricsExpireTime = r.ReadTimeSpanNullable();
_metricsHistorySize = r.ReadIntNullable();
_metricsLogFrequency = r.ReadTimeSpanNullable();
_metricsUpdateFrequency = r.ReadTimeSpanNullable();
_networkSendRetryCount = r.ReadIntNullable();
_networkSendRetryDelay = r.ReadTimeSpanNullable();
_networkTimeout = r.ReadTimeSpanNullable();
WorkDirectory = r.ReadString();
Localhost = r.ReadString();
_isDaemon = r.ReadBooleanNullable();
_isLateAffinityAssignment = r.ReadBooleanNullable();
_failureDetectionTimeout = r.ReadTimeSpanNullable();
// Cache config
var cacheCfgCount = r.ReadInt();
CacheConfiguration = new List<CacheConfiguration>(cacheCfgCount);
for (int i = 0; i < cacheCfgCount; i++)
CacheConfiguration.Add(new CacheConfiguration(r));
// Discovery config
DiscoverySpi = r.ReadBoolean() ? new TcpDiscoverySpi(r) : null;
// Communication config
CommunicationSpi = r.ReadBoolean() ? new TcpCommunicationSpi(r) : null;
// Binary config
if (r.ReadBoolean())
{
BinaryConfiguration = BinaryConfiguration ?? new BinaryConfiguration();
if (r.ReadBoolean())
BinaryConfiguration.CompactFooter = r.ReadBoolean();
var typeCount = r.ReadInt();
if (typeCount > 0)
{
var types = new List<BinaryTypeConfiguration>(typeCount);
for (var i = 0; i < typeCount; i++)
{
types.Add(new BinaryTypeConfiguration
{
TypeName = r.ReadString(),
IsEnum = r.ReadBoolean(),
EqualityComparer = BinaryEqualityComparerSerializer.Read(r)
});
}
BinaryConfiguration.TypeConfigurations = types;
}
}
// User attributes
UserAttributes = Enumerable.Range(0, r.ReadInt())
.ToDictionary(x => r.ReadString(), x => r.ReadObject<object>());
// Atomic
if (r.ReadBoolean())
{
AtomicConfiguration = new AtomicConfiguration
{
AtomicSequenceReserveSize = r.ReadInt(),
Backups = r.ReadInt(),
CacheMode = (CacheMode) r.ReadInt()
};
}
// Tx
if (r.ReadBoolean())
{
TransactionConfiguration = new TransactionConfiguration
{
PessimisticTransactionLogSize = r.ReadInt(),
DefaultTransactionConcurrency = (TransactionConcurrency) r.ReadInt(),
DefaultTransactionIsolation = (TransactionIsolation) r.ReadInt(),
DefaultTimeout = TimeSpan.FromMilliseconds(r.ReadLong()),
PessimisticTransactionLogLinger = TimeSpan.FromMilliseconds(r.ReadInt())
};
}
// Swap
SwapSpaceSpi = SwapSpaceSerializer.Read(r);
}
/// <summary>
/// Reads data from specified reader into current instance.
/// </summary>
/// <param name="binaryReader">The binary reader.</param>
private void Read(BinaryReader binaryReader)
{
ReadCore(binaryReader);
CopyLocalProperties(binaryReader.Marshaller.Ignite.Configuration);
// Misc
IgniteHome = binaryReader.ReadString();
JvmInitialMemoryMb = (int) (binaryReader.ReadLong()/1024/2014);
JvmMaxMemoryMb = (int) (binaryReader.ReadLong()/1024/2014);
// Local data (not from reader)
JvmDllPath = Process.GetCurrentProcess().Modules.OfType<ProcessModule>()
.Single(x => string.Equals(x.ModuleName, IgniteUtils.FileJvmDll, StringComparison.OrdinalIgnoreCase))
.FileName;
}
/// <summary>
/// Copies the local properties (properties that are not written in Write method).
/// </summary>
private void CopyLocalProperties(IgniteConfiguration cfg)
{
GridName = cfg.GridName;
if (BinaryConfiguration != null && cfg.BinaryConfiguration != null)
{
BinaryConfiguration.MergeTypes(cfg.BinaryConfiguration);
}
else if (cfg.BinaryConfiguration != null)
{
BinaryConfiguration = new BinaryConfiguration(cfg.BinaryConfiguration);
}
JvmClasspath = cfg.JvmClasspath;
JvmOptions = cfg.JvmOptions;
Assemblies = cfg.Assemblies;
SuppressWarnings = cfg.SuppressWarnings;
LifecycleBeans = cfg.LifecycleBeans;
Logger = cfg.Logger;
JvmInitialMemoryMb = cfg.JvmInitialMemoryMb;
JvmMaxMemoryMb = cfg.JvmMaxMemoryMb;
}
/// <summary>
/// Grid name which is used if not provided in configuration file.
/// </summary>
public string GridName { get; set; }
/// <summary>
/// Gets or sets the binary configuration.
/// </summary>
/// <value>
/// The binary configuration.
/// </value>
public BinaryConfiguration BinaryConfiguration { get; set; }
/// <summary>
/// Gets or sets the cache configuration.
/// </summary>
/// <value>
/// The cache configuration.
/// </value>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<CacheConfiguration> CacheConfiguration { get; set; }
/// <summary>
/// URL to Spring configuration file.
/// <para />
/// Spring configuration is loaded first, then <see cref="IgniteConfiguration"/> properties are applied.
/// Null property values do not override Spring values.
/// Value-typed properties are tracked internally: if setter was not called, Spring value won't be overwritten.
/// <para />
/// This merging happens on the top level only; e. g. if there are cache configurations defined in Spring
/// and in .NET, .NET caches will overwrite Spring caches.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
public string SpringConfigUrl { get; set; }
/// <summary>
/// Path jvm.dll file. If not set, it's location will be determined
/// using JAVA_HOME environment variable.
/// If path is neither set nor determined automatically, an exception
/// will be thrown.
/// </summary>
public string JvmDllPath { get; set; }
/// <summary>
/// Path to Ignite home. If not set environment variable IGNITE_HOME will be used.
/// </summary>
public string IgniteHome { get; set; }
/// <summary>
/// Classpath used by JVM on Ignite start.
/// </summary>
public string JvmClasspath { get; set; }
/// <summary>
/// Collection of options passed to JVM on Ignite start.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<string> JvmOptions { get; set; }
/// <summary>
/// List of additional .Net assemblies to load on Ignite start. Each item can be either
/// fully qualified assembly name, path to assembly to DLL or path to a directory when
/// assemblies reside.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<string> Assemblies { get; set; }
/// <summary>
/// Whether to suppress warnings.
/// </summary>
public bool SuppressWarnings { get; set; }
/// <summary>
/// Lifecycle beans.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<ILifecycleBean> LifecycleBeans { get; set; }
/// <summary>
/// Initial amount of memory in megabytes given to JVM. Maps to -Xms Java option.
/// <code>-1</code> maps to JVM defaults.
/// Defaults to <see cref="DefaultJvmInitMem"/>.
/// </summary>
[DefaultValue(DefaultJvmInitMem)]
public int JvmInitialMemoryMb { get; set; }
/// <summary>
/// Maximum amount of memory in megabytes given to JVM. Maps to -Xmx Java option.
/// <code>-1</code> maps to JVM defaults.
/// Defaults to <see cref="DefaultJvmMaxMem"/>.
/// </summary>
[DefaultValue(DefaultJvmMaxMem)]
public int JvmMaxMemoryMb { get; set; }
/// <summary>
/// Gets or sets the discovery service provider.
/// Null for default discovery.
/// </summary>
public IDiscoverySpi DiscoverySpi { get; set; }
/// <summary>
/// Gets or sets the communication service provider.
/// Null for default communication.
/// </summary>
public ICommunicationSpi CommunicationSpi { get; set; }
/// <summary>
/// Gets or sets a value indicating whether node should start in client mode.
/// Client node cannot hold data in the caches.
/// </summary>
public bool ClientMode
{
get { return _clientMode ?? default(bool); }
set { _clientMode = value; }
}
/// <summary>
/// Gets or sets a set of event types (<see cref="EventType" />) to be recorded by Ignite.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<int> IncludedEventTypes { get; set; }
/// <summary>
/// Gets or sets the time after which a certain metric value is considered expired.
/// </summary>
[DefaultValue(typeof(TimeSpan), "10675199.02:48:05.4775807")]
public TimeSpan MetricsExpireTime
{
get { return _metricsExpireTime ?? DefaultMetricsExpireTime; }
set { _metricsExpireTime = value; }
}
/// <summary>
/// Gets or sets the number of metrics kept in history to compute totals and averages.
/// </summary>
[DefaultValue(DefaultMetricsHistorySize)]
public int MetricsHistorySize
{
get { return _metricsHistorySize ?? DefaultMetricsHistorySize; }
set { _metricsHistorySize = value; }
}
/// <summary>
/// Gets or sets the frequency of metrics log print out.
/// <see cref="TimeSpan.Zero"/> to disable metrics print out.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:01:00")]
public TimeSpan MetricsLogFrequency
{
get { return _metricsLogFrequency ?? DefaultMetricsLogFrequency; }
set { _metricsLogFrequency = value; }
}
/// <summary>
/// Gets or sets the job metrics update frequency.
/// <see cref="TimeSpan.Zero"/> to update metrics on job start/finish.
/// Negative value to never update metrics.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:02")]
public TimeSpan MetricsUpdateFrequency
{
get { return _metricsUpdateFrequency ?? DefaultMetricsUpdateFrequency; }
set { _metricsUpdateFrequency = value; }
}
/// <summary>
/// Gets or sets the network send retry count.
/// </summary>
[DefaultValue(DefaultNetworkSendRetryCount)]
public int NetworkSendRetryCount
{
get { return _networkSendRetryCount ?? DefaultNetworkSendRetryCount; }
set { _networkSendRetryCount = value; }
}
/// <summary>
/// Gets or sets the network send retry delay.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:01")]
public TimeSpan NetworkSendRetryDelay
{
get { return _networkSendRetryDelay ?? DefaultNetworkSendRetryDelay; }
set { _networkSendRetryDelay = value; }
}
/// <summary>
/// Gets or sets the network timeout.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:05")]
public TimeSpan NetworkTimeout
{
get { return _networkTimeout ?? DefaultNetworkTimeout; }
set { _networkTimeout = value; }
}
/// <summary>
/// Gets or sets the work directory.
/// If not provided, a folder under <see cref="IgniteHome"/> will be used.
/// </summary>
public string WorkDirectory { get; set; }
/// <summary>
/// Gets or sets system-wide local address or host for all Ignite components to bind to.
/// If provided it will override all default local bind settings within Ignite.
/// <para />
/// If <c>null</c> then Ignite tries to use local wildcard address.That means that all services
/// will be available on all network interfaces of the host machine.
/// <para />
/// It is strongly recommended to set this parameter for all production environments.
/// </summary>
public string Localhost { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this node should be a daemon node.
/// <para />
/// Daemon nodes are the usual grid nodes that participate in topology but not visible on the main APIs,
/// i.e. they are not part of any cluster groups.
/// <para />
/// Daemon nodes are used primarily for management and monitoring functionality that is built on Ignite
/// and needs to participate in the topology, but also needs to be excluded from the "normal" topology,
/// so that it won't participate in the task execution or in-memory data grid storage.
/// </summary>
public bool IsDaemon
{
get { return _isDaemon ?? default(bool); }
set { _isDaemon = value; }
}
/// <summary>
/// Gets or sets the user attributes for this node.
/// <para />
/// These attributes can be retrieved later via <see cref="IClusterNode.GetAttributes"/>.
/// Environment variables are added to node attributes automatically.
/// NOTE: attribute names starting with "org.apache.ignite" are reserved for internal use.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IDictionary<string, object> UserAttributes { get; set; }
/// <summary>
/// Gets or sets the atomic data structures configuration.
/// </summary>
public AtomicConfiguration AtomicConfiguration { get; set; }
/// <summary>
/// Gets or sets the transaction configuration.
/// </summary>
public TransactionConfiguration TransactionConfiguration { get; set; }
/// <summary>
/// Gets or sets a value indicating whether late affinity assignment mode should be used.
/// <para />
/// On each topology change, for each started cache, partition-to-node mapping is
/// calculated using AffinityFunction for cache. When late
/// affinity assignment mode is disabled then new affinity mapping is applied immediately.
/// <para />
/// With late affinity assignment mode, if primary node was changed for some partition, but data for this
/// partition is not rebalanced yet on this node, then current primary is not changed and new primary
/// is temporary assigned as backup. This nodes becomes primary only when rebalancing for all assigned primary
/// partitions is finished. This mode can show better performance for cache operations, since when cache
/// primary node executes some operation and data is not rebalanced yet, then it sends additional message
/// to force rebalancing from other nodes.
/// <para />
/// Note, that <see cref="ICacheAffinity"/> interface provides assignment information taking late assignment
/// into account, so while rebalancing for new primary nodes is not finished it can return assignment
/// which differs from assignment calculated by AffinityFunction.
/// <para />
/// This property should have the same value for all nodes in cluster.
/// <para />
/// If not provided, default value is <see cref="DefaultIsLateAffinityAssignment"/>.
/// </summary>
[DefaultValue(DefaultIsLateAffinityAssignment)]
public bool IsLateAffinityAssignment
{
get { return _isLateAffinityAssignment ?? DefaultIsLateAffinityAssignment; }
set { _isLateAffinityAssignment = value; }
}
/// <summary>
/// Serializes this instance to the specified XML writer.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="rootElementName">Name of the root element.</param>
public void ToXml(XmlWriter writer, string rootElementName)
{
IgniteArgumentCheck.NotNull(writer, "writer");
IgniteArgumentCheck.NotNullOrEmpty(rootElementName, "rootElementName");
IgniteConfigurationXmlSerializer.Serialize(this, writer, rootElementName);
}
/// <summary>
/// Serializes this instance to an XML string.
/// </summary>
public string ToXml()
{
var sb = new StringBuilder();
var settings = new XmlWriterSettings
{
Indent = true
};
using (var xmlWriter = XmlWriter.Create(sb, settings))
{
ToXml(xmlWriter, "igniteConfiguration");
}
return sb.ToString();
}
/// <summary>
/// Deserializes IgniteConfiguration from the XML reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>Deserialized instance.</returns>
public static IgniteConfiguration FromXml(XmlReader reader)
{
IgniteArgumentCheck.NotNull(reader, "reader");
return IgniteConfigurationXmlSerializer.Deserialize(reader);
}
/// <summary>
/// Deserializes IgniteConfiguration from the XML string.
/// </summary>
/// <param name="xml">Xml string.</param>
/// <returns>Deserialized instance.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2202: Do not call Dispose more than one time on an object")]
public static IgniteConfiguration FromXml(string xml)
{
IgniteArgumentCheck.NotNullOrEmpty(xml, "xml");
using (var stringReader = new StringReader(xml))
using (var xmlReader = XmlReader.Create(stringReader))
{
// Skip XML header.
xmlReader.MoveToContent();
return FromXml(xmlReader);
}
}
/// <summary>
/// Gets or sets the logger.
/// <para />
/// If no logger is set, logging is delegated to Java, which uses the logger defined in Spring XML (if present)
/// or logs to console otherwise.
/// </summary>
public ILogger Logger { get; set; }
/// <summary>
/// Gets or sets the failure detection timeout used by <see cref="TcpDiscoverySpi"/>
/// and <see cref="TcpCommunicationSpi"/>.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:10")]
public TimeSpan FailureDetectionTimeout
{
get { return _failureDetectionTimeout ?? DefaultFailureDetectionTimeout; }
set { _failureDetectionTimeout = value; }
}
/// <summary>
/// Gets or sets the swap space SPI.
/// </summary>
public ISwapSpaceSpi SwapSpaceSpi { get; set; }
}
}
| |
using System;
namespace System.Globalization
{
internal static class SR
{
public static string Arg_HexStyleNotSupported
{
get { return Environment.GetResourceString("Arg_HexStyleNotSupported"); }
}
public static string Arg_InvalidHexStyle
{
get { return Environment.GetResourceString("Arg_InvalidHexStyle"); }
}
public static string ArgumentNull_Array
{
get { return Environment.GetResourceString("ArgumentNull_Array"); }
}
public static string ArgumentNull_ArrayValue
{
get { return Environment.GetResourceString("ArgumentNull_ArrayValue"); }
}
public static string ArgumentNull_Obj
{
get { return Environment.GetResourceString("ArgumentNull_Obj"); }
}
public static string ArgumentNull_String
{
get { return Environment.GetResourceString("ArgumentNull_String"); }
}
public static string ArgumentOutOfRange_AddValue
{
get { return Environment.GetResourceString("ArgumentOutOfRange_AddValue"); }
}
public static string ArgumentOutOfRange_BadHourMinuteSecond
{
get { return Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"); }
}
public static string ArgumentOutOfRange_BadYearMonthDay
{
get { return Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"); }
}
public static string ArgumentOutOfRange_Bounds_Lower_Upper
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"); }
}
public static string ArgumentOutOfRange_CalendarRange
{
get { return Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"); }
}
public static string ArgumentOutOfRange_Count
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Count"); }
}
public static string ArgumentOutOfRange_Day
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Day"); }
}
public static string ArgumentOutOfRange_Enum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Enum"); }
}
public static string ArgumentOutOfRange_Era
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Era"); }
}
public static string ArgumentOutOfRange_Index
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Index"); }
}
public static string ArgumentOutOfRange_InvalidEraValue
{
get { return Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"); }
}
public static string ArgumentOutOfRange_Month
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Month"); }
}
public static string ArgumentOutOfRange_NeedNonNegNum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); }
}
public static string ArgumentOutOfRange_NeedPosNum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"); }
}
public static string ArgumentOutOfRange_OffsetLength
{
get { return Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"); }
}
public static string ArgumentOutOfRange_Range
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Range"); }
}
public static string Argument_CompareOptionOrdinal
{
get { return Environment.GetResourceString("Argument_CompareOptionOrdinal"); }
}
public static string Argument_ConflictingDateTimeRoundtripStyles
{
get { return Environment.GetResourceString("Argument_ConflictingDateTimeRoundtripStyles"); }
}
public static string Argument_ConflictingDateTimeStyles
{
get { return Environment.GetResourceString("Argument_ConflictingDateTimeStyles"); }
}
public static string Argument_CultureInvalidIdentifier
{
get { return Environment.GetResourceString("Argument_CultureInvalidIdentifier"); }
}
public static string Argument_CultureNotSupported
{
get { return Environment.GetResourceString("Argument_CultureNotSupported"); }
}
public static string Argument_EmptyDecString
{
get { return Environment.GetResourceString("Argument_EmptyDecString"); }
}
public static string Argument_InvalidArrayLength
{
get { return Environment.GetResourceString("Argument_InvalidArrayLength"); }
}
public static string Argument_InvalidCalendar
{
get { return Environment.GetResourceString("Argument_InvalidCalendar"); }
}
public static string Argument_InvalidCultureName
{
get { return Environment.GetResourceString("Argument_InvalidCultureName"); }
}
public static string Argument_InvalidDateTimeStyles
{
get { return Environment.GetResourceString("Argument_InvalidDateTimeStyles"); }
}
public static string Argument_InvalidFlag
{
get { return Environment.GetResourceString("Argument_InvalidFlag"); }
}
public static string Argument_InvalidGroupSize
{
get { return Environment.GetResourceString("Argument_InvalidGroupSize"); }
}
public static string Argument_InvalidNeutralRegionName
{
get { return Environment.GetResourceString("Argument_InvalidNeutralRegionName"); }
}
public static string Argument_InvalidNumberStyles
{
get { return Environment.GetResourceString("Argument_InvalidNumberStyles"); }
}
public static string Argument_InvalidResourceCultureName
{
get { return Environment.GetResourceString("Argument_InvalidResourceCultureName"); }
}
public static string Argument_NoEra
{
get { return Environment.GetResourceString("Argument_NoEra"); }
}
public static string Argument_NoRegionInvariantCulture
{
get { return Environment.GetResourceString("Argument_NoRegionInvariantCulture"); }
}
public static string Argument_ResultCalendarRange
{
get { return Environment.GetResourceString("Argument_ResultCalendarRange"); }
}
public static string Format_BadFormatSpecifier
{
get { return Environment.GetResourceString("Format_BadFormatSpecifier"); }
}
public static string InvalidOperation_DateTimeParsing
{
get { return Environment.GetResourceString("InvalidOperation_DateTimeParsing"); }
}
public static string InvalidOperation_EnumEnded
{
get { return Environment.GetResourceString("InvalidOperation_EnumEnded"); }
}
public static string InvalidOperation_EnumNotStarted
{
get { return Environment.GetResourceString("InvalidOperation_EnumNotStarted"); }
}
public static string InvalidOperation_ReadOnly
{
get { return Environment.GetResourceString("InvalidOperation_ReadOnly"); }
}
public static string Overflow_TimeSpanTooLong
{
get { return Environment.GetResourceString("Overflow_TimeSpanTooLong"); }
}
public static string Format(string formatString, params object[] args)
{
return string.Format(CultureInfo.CurrentCulture, formatString, args);
}
}
}
| |
using System;
using System.IO;
using System.Text;
namespace Fonet.Pdf
{
public sealed class PdfName : PdfObject
{
private string name;
private byte[] bytes;
public PdfName(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
this.name = name;
}
public PdfName(string name, PdfObjectId objectId)
: base(objectId)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
this.name = name;
}
public string Name
{
get { return name; }
}
protected internal override void Write(PdfWriter writer)
{
writer.Write(NameBytes);
}
private static readonly byte[] HexDigits = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66
};
private byte[] NameBytes
{
get
{
if (bytes == null)
{
// Create a memory stream to hold the results.
// We guess the size, based on the most likely outcome
// (i.e. all ASCII characters with no escapes.
MemoryStream ms = new MemoryStream(name.Length + 1);
// The forward slash introduces a name.
ms.WriteByte((byte)'/');
// The PDF specification recommends encoding name objects using UTF8.
byte[] data = Encoding.UTF8.GetBytes(name);
for (int x = 0; x < data.Length; x++)
{
byte b = data[x];
// The PDF specification recommends using a special #hh syntax
// for any bytes that are outside the range 33 to 126 and for
// the # character itself (35).
if (b < 34 || b > 125 || b == 35)
{
ms.WriteByte((byte)'#');
ms.WriteByte(HexDigits[b >> 4]);
ms.WriteByte(HexDigits[b & 0x0f]);
}
else
{
ms.WriteByte(b);
}
}
ms.Close();
bytes = ms.ToArray();
}
return bytes;
}
}
public override int GetHashCode()
{
return name.GetHashCode();
}
public override bool Equals(object obj)
{
PdfName pobj = obj as PdfName;
if (pobj == null)
{
return false;
}
return name.Equals(pobj.Name);
}
// public static bool operator ==(PdfName o1, PdfName o2) {
// return o1.Equals(o2);
// }
//
// public static bool operator !=(PdfName o1, PdfName o2) {
// return !(o1 == o2);
// }
/// <summary>
/// Well-known PDF name objects.
/// </summary>
public class Names
{
public static readonly PdfName Catalog = new PdfName("Catalog");
public static readonly PdfName Type = new PdfName("Type");
public static readonly PdfName Subtype = new PdfName("Subtype");
public static readonly PdfName Pages = new PdfName("Pages");
public static readonly PdfName Outlines = new PdfName("Outlines");
public static readonly PdfName Kids = new PdfName("Kids");
public static readonly PdfName Count = new PdfName("Count");
public static readonly PdfName Title = new PdfName("Title");
public static readonly PdfName Author = new PdfName("Author");
public static readonly PdfName Subject = new PdfName("Subject");
public static readonly PdfName Keywords = new PdfName("Keywords");
public static readonly PdfName Creator = new PdfName("Creator");
public static readonly PdfName Producer = new PdfName("Producer");
public static readonly PdfName CreationDate = new PdfName("CreationDate");
public static readonly PdfName ModDate = new PdfName("ModDate");
public static readonly PdfName Size = new PdfName("Size");
public static readonly PdfName Prev = new PdfName("Prev");
public static readonly PdfName Root = new PdfName("Root");
public static readonly PdfName Encrypt = new PdfName("Encrypt");
public static readonly PdfName Info = new PdfName("Info");
public static readonly PdfName Id = new PdfName("ID");
public static readonly PdfName Encoding = new PdfName("Encoding");
public static readonly PdfName BaseEncoding = new PdfName("BaseEncoding");
public static readonly PdfName MacRomanEncoding = new PdfName("MacRomanEncoding");
public static readonly PdfName MacExpertEncoding = new PdfName("MacExpertEncoding");
public static readonly PdfName WinAnsiEncoding = new PdfName("WinAnsiEncoding");
public static readonly PdfName FileSpec = new PdfName("FileSpec");
public static readonly PdfName F = new PdfName("F");
public static readonly PdfName Annot = new PdfName("Annot");
public static readonly PdfName Action = new PdfName("Action");
public static readonly PdfName Link = new PdfName("Link");
public static readonly PdfName H = new PdfName("H");
public static readonly PdfName I = new PdfName("I");
public static readonly PdfName A = new PdfName("A");
public static readonly PdfName Border = new PdfName("Border");
public static readonly PdfName Rect = new PdfName("Rect");
public static readonly PdfName C = new PdfName("C");
public static readonly PdfName S = new PdfName("S");
public static readonly PdfName GoTo = new PdfName("GoTo");
public static readonly PdfName GoToR = new PdfName("GoToR");
public static readonly PdfName D = new PdfName("D");
public static readonly PdfName XYZ = new PdfName("XYZ");
public static readonly PdfName URI = new PdfName("URI");
public static readonly PdfName Font = new PdfName("Font");
public static readonly PdfName FontName = new PdfName("FontName");
public static readonly PdfName FontDescriptor = new PdfName("FontDescriptor");
public static readonly PdfName Flags = new PdfName("Flags");
public static readonly PdfName FontBBox = new PdfName("FontBBox");
public static readonly PdfName ItalicAngle = new PdfName("ItalicAngle");
public static readonly PdfName Ascent = new PdfName("Ascent");
public static readonly PdfName Descent = new PdfName("Descent");
public static readonly PdfName Leading = new PdfName("Leading");
public static readonly PdfName CapHeight = new PdfName("CapHeight");
public static readonly PdfName XHeight = new PdfName("XHeight");
public static readonly PdfName StemV = new PdfName("StemV");
public static readonly PdfName StemH = new PdfName("StemH");
public static readonly PdfName AvgWidth = new PdfName("AvgWidth");
public static readonly PdfName MaxWidth = new PdfName("MaxWidth");
public static readonly PdfName MissingWidth = new PdfName("MissingWidth");
public static readonly PdfName FontFile = new PdfName("FontFile");
public static readonly PdfName FontFile2 = new PdfName("FontFile2");
public static readonly PdfName FontFile3 = new PdfName("FontFile3");
public static readonly PdfName CharSet = new PdfName("CharSet");
public static readonly PdfName CIDToGIDMap = new PdfName("CIDToGIDMap");
public static readonly PdfName Identity = new PdfName("Identity");
public static readonly PdfName Length1 = new PdfName("Length1");
public static readonly PdfName Length2 = new PdfName("Length2");
public static readonly PdfName Length3 = new PdfName("Length3");
public static readonly PdfName ToUnicode = new PdfName("ToUnicode");
public static readonly PdfName CMap = new PdfName("CMap");
public static readonly PdfName CMapName = new PdfName("CMapName");
public static readonly PdfName WMode = new PdfName("WMode");
public static readonly PdfName Type0 = new PdfName("Type0");
public static readonly PdfName Type1 = new PdfName("Type1");
public static readonly PdfName TrueType = new PdfName("TrueType");
public static readonly PdfName Name = new PdfName("Name");
public static readonly PdfName BaseFont = new PdfName("BaseFont");
public static readonly PdfName XObject = new PdfName("XObject");
public static readonly PdfName CIDFontType0 = new PdfName("CIDFontType0");
public static readonly PdfName CIDFontType2 = new PdfName("CIDFontType2");
public static readonly PdfName CIDSystemInfo = new PdfName("CIDSystemInfo");
public static readonly PdfName DescendantFonts = new PdfName("DescendantFonts");
public static readonly PdfName Registry = new PdfName("Registry");
public static readonly PdfName Ordering = new PdfName("Ordering");
public static readonly PdfName Supplement = new PdfName("Supplement");
public static readonly PdfName DW = new PdfName("DW");
public static readonly PdfName W = new PdfName("W");
public static readonly PdfName Page = new PdfName("Page");
public static readonly PdfName PageMode = new PdfName("PageMode");
public static readonly PdfName UseOutlines = new PdfName("UseOutlines");
public static readonly PdfName Resources = new PdfName("Resources");
public static readonly PdfName Contents = new PdfName("Contents");
public static readonly PdfName MediaBox = new PdfName("MediaBox");
public static readonly PdfName Parent = new PdfName("Parent");
public static readonly PdfName Annots = new PdfName("Annots");
public static readonly PdfName Image = new PdfName("Image");
public static readonly PdfName Width = new PdfName("Width");
public static readonly PdfName Height = new PdfName("Height");
public static readonly PdfName BitsPerComponent = new PdfName("BitsPerComponent");
public static readonly PdfName ColorSpace = new PdfName("ColorSpace");
public static readonly PdfName ProcSet = new PdfName("ProcSet");
public static readonly PdfName PDF = new PdfName("PDF");
public static readonly PdfName Text = new PdfName("Text");
public static readonly PdfName ImageB = new PdfName("ImageB");
public static readonly PdfName ImageC = new PdfName("ImageC");
public static readonly PdfName ImageI = new PdfName("ImageI");
public static readonly PdfName Length = new PdfName("Length");
public static readonly PdfName Filter = new PdfName("Filter");
public static readonly PdfName DecodeParams = new PdfName("DecodeParams");
public static readonly PdfName ASCII85Decode = new PdfName("ASCII85Decode");
public static readonly PdfName ASCIIHexDecode = new PdfName("ASCIIHexDecode");
public static readonly PdfName CCITTFaxDecode = new PdfName("CCITTFaxDecode");
public static readonly PdfName DCTDecode = new PdfName("DCTDecode");
public static readonly PdfName FlateDecode = new PdfName("FlateDecode");
public static readonly PdfName JBIG2Decode = new PdfName("JBIG2Decode");
public static readonly PdfName LZWDecode = new PdfName("LZWDecode");
public static readonly PdfName RunLengthDecode = new PdfName("RunLengthDecode");
public static readonly PdfName Standard = new PdfName("Standard");
public static readonly PdfName V = new PdfName("V");
public static readonly PdfName R = new PdfName("R");
public static readonly PdfName O = new PdfName("O");
public static readonly PdfName U = new PdfName("U");
public static readonly PdfName P = new PdfName("P");
public static readonly PdfName FirstChar = new PdfName("FirstChar");
public static readonly PdfName LastChar = new PdfName("LastChar");
public static readonly PdfName Widths = new PdfName("Widths");
public static readonly PdfName First = new PdfName("First");
public static readonly PdfName Last = new PdfName("Last");
public static readonly PdfName Next = new PdfName("Next");
public static readonly PdfName Alternate = new PdfName("Alternate");
public static readonly PdfName ICCBased = new PdfName("ICCBased");
public static readonly PdfName N = new PdfName("N");
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Media;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.PythonTools.Refactoring {
using AP = AnalysisProtocol;
/// <summary>
/// Provides a view model for the ExtractMethodRequest class.
/// </summary>
sealed class ExtractMethodRequestView : INotifyPropertyChanged {
private readonly ExtractedMethodCreator _previewer;
internal static readonly Regex _validNameRegex = new Regex("^[a-zA-Z_][a-zA-Z0-9_]*$");
private const string _defaultName = "method_name";
private string _name;
private readonly FontFamily _previewFontFamily;
private bool _isValid;
private readonly ReadOnlyCollection<ScopeWrapper> _targetScopes;
private readonly ScopeWrapper _defaultScope;
private readonly IServiceProvider _serviceProvider;
private ScopeWrapper _targetScope;
private ReadOnlyCollection<ClosureVariable> _closureVariables;
private string _previewText;
/// <summary>
/// Create an ExtractMethodRequestView with default values.
/// </summary>
public ExtractMethodRequestView(IServiceProvider serviceProvider, ExtractedMethodCreator previewer) {
_previewer = previewer;
_serviceProvider = serviceProvider;
var extraction = _previewer.LastExtraction;
AP.ScopeInfo lastClass = null;
for (int i = extraction.scopes.Length - 1; i >= 0; i--) {
if (extraction.scopes[i].type == "class") {
lastClass = extraction.scopes[i];
break;
}
}
var targetScopes = new List<ScopeWrapper>();
foreach (var scope in extraction.scopes) {
if (!(scope.type == "class") || scope == lastClass) {
var wrapper = new ScopeWrapper(scope);
if (scope == lastClass) {
_defaultScope = wrapper;
}
targetScopes.Add(wrapper);
}
}
_targetScopes = new ReadOnlyCollection<ScopeWrapper>(targetScopes);
if (_defaultScope == null && _targetScopes.Any()) {
_defaultScope = _targetScopes[0];
}
_previewFontFamily = new FontFamily(GetTextEditorFont());
PropertyChanged += ExtractMethodRequestView_PropertyChanged;
// Access properties rather than underlying variables to ensure dependent properties
// are also updated.
Name = _defaultName;
TargetScope = _defaultScope;
}
/// <summary>
/// Create an ExtractMethodRequestView with values taken from template.
/// </summary>
public ExtractMethodRequestView(IServiceProvider serviceProvider, ExtractedMethodCreator previewer, ExtractMethodRequest template)
: this(serviceProvider, previewer) {
// Access properties rather than underlying variables to ensure dependent properties
// are also updated.
Name = template.Name;
TargetScope = template.TargetScope;
foreach (var cv in ClosureVariables) {
cv.IsClosure = !template.Parameters.Contains(cv.Name);
}
}
/// <summary>
/// Returns an ExtractMethodRequestView with the values set from the view model.
/// </summary>
public ExtractMethodRequest GetRequest() {
if (IsValid) {
string[] parameters;
if (ClosureVariables != null) {
parameters = ClosureVariables.Where(cv => !cv.IsClosure).Select(cv => cv.Name).ToArray();
} else {
parameters = new string[0];
}
return new ExtractMethodRequest(TargetScope ?? _defaultScope,
Name ?? _defaultName,
parameters);
} else {
return null;
}
}
/// <summary>
/// The name of the new method which should be created
/// </summary>
public string Name {
get {
return _name;
}
set {
if (_name != value) {
_name = value;
OnPropertyChanged("Name");
}
}
}
/// <summary>
/// The font family to display preview text using.
/// </summary>
public FontFamily PreviewFontFamily {
get {
return _previewFontFamily;
}
}
/// <summary>
/// True if the name is a valid Python name; otherwise, false.
/// </summary>
public bool IsValid {
get {
return _isValid;
}
private set {
if (_isValid != value) {
_isValid = value;
OnPropertyChanged("IsValid");
}
}
}
/// <summary>
/// The target scope to extract the method to.
/// </summary>
public ScopeWrapper TargetScope {
get {
return _targetScope;
}
set {
if (_targetScope != value) {
_targetScope = value;
OnPropertyChanged("TargetScope");
List<ClosureVariable> closureVariables = new List<ClosureVariable>();
if (_targetScope != null) {
foreach (var variable in _previewer.LastExtraction.variables) {
if (_targetScope.Scope.variables.Contains(variable)) {
// we can either close over or pass these in as parameters, add them to the list
closureVariables.Add(new ClosureVariable(variable));
}
}
closureVariables.Sort();
}
ClosureVariables = new ReadOnlyCollection<ClosureVariable>(closureVariables);
}
}
}
/// <summary>
/// The set of potential scopes to extract the method to.
/// </summary>
public ReadOnlyCollection<ScopeWrapper> TargetScopes {
get {
return _targetScopes;
}
}
/// <summary>
/// The list of closure/parameter settings for the current TargetScope.
/// </summary>
public ReadOnlyCollection<ClosureVariable> ClosureVariables {
get {
return _closureVariables;
}
private set {
if (_closureVariables != value) {
if (_closureVariables != null) {
foreach (var cv in _closureVariables) {
cv.PropertyChanged -= ClosureVariable_PropertyChanged;
}
}
_closureVariables = value;
if (_closureVariables != null) {
foreach (var cv in ClosureVariables) {
cv.PropertyChanged += ClosureVariable_PropertyChanged;
}
}
OnPropertyChanged("ClosureVariables");
UpdatePreview();
}
}
}
/// <summary>
/// Receives our own property change events to update IsValid.
/// </summary>
void ExtractMethodRequestView_PropertyChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName != "IsValid") {
IsValid = (Name != null && _validNameRegex.IsMatch(Name)) &&
TargetScope != null;
}
if (e.PropertyName != "PreviewText") {
UpdatePreview();
}
}
/// <summary>
/// Propagate property change events from ClosureVariable.
/// </summary>
void ClosureVariable_PropertyChanged(object sender, PropertyChangedEventArgs e) {
OnPropertyChanged("ClosureVariables");
}
/// <summary>
/// Updates PreviewText based on the current settings.
/// </summary>
private void UpdatePreview() {
var info = GetRequest();
if (info != null) {
_previewer.GetExtractionResult(info).ContinueWith(
x => PreviewText = x?.WaitOrDefault(1000)?.methodBody ?? "<failed to get preview>"
).DoNotWait();
} else {
PreviewText = "The method name is not valid.";
}
}
/// <summary>
/// An example of how the extracted method will appear.
/// </summary>
public string PreviewText {
get {
return _previewText;
}
private set {
if (_previewText != value) {
_previewText = value;
OnPropertyChanged("PreviewText");
}
}
}
/// <summary>
/// Returns the name of the font set by the user for editor windows.
/// </summary>
private string GetTextEditorFont() {
try {
var store = (IVsFontAndColorStorage)_serviceProvider.GetService(typeof(SVsFontAndColorStorage));
Guid textEditorCategory = new Guid(FontsAndColorsCategory.TextEditor);
if (store != null && store.OpenCategory(ref textEditorCategory,
(uint)(__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_READONLY)) == VSConstants.S_OK) {
try {
FontInfo[] info = new FontInfo[1];
store.GetFont(null, info);
if (info[0].bstrFaceName != null) {
return info[0].bstrFaceName;
}
}
finally {
store.CloseCategory();
}
}
}
catch { }
return "Consolas";
}
private void OnPropertyChanged(string propertyName) {
var evt = PropertyChanged;
if (evt != null) {
evt(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Raised when the value of a property changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Provides a view model for the closure/parameter state of a variable.
/// </summary>
public sealed class ClosureVariable : INotifyPropertyChanged, IComparable<ClosureVariable> {
private readonly string _name;
private readonly string _displayName;
private bool _isClosure;
public ClosureVariable(string name) {
_name = name;
_displayName = name.Replace("_", "__");
_isClosure = true;
}
/// <summary>
/// The name of the variable.
/// </summary>
public string Name {
get { return _name; }
}
/// <summary>
/// The name of the variable with
/// </summary>
public string DisplayName {
get { return _displayName; }
}
/// <summary>
/// True to close over the variable; otherwise, false to pass it as a parameter.
/// </summary>
public bool IsClosure {
get { return _isClosure; }
set {
if (_isClosure != value) {
_isClosure = value;
OnPropertyChanged("IsClosure");
}
}
}
private void OnPropertyChanged(string propertyName) {
var evt = PropertyChanged;
if (evt != null) {
evt(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Raised when the value of a property changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Compares two ClosureVariable instances by name.
/// </summary>
public int CompareTo(ClosureVariable other) {
return Name.CompareTo((other == null) ? string.Empty : other.Name);
}
}
}
class ScopeWrapper {
public readonly AP.ScopeInfo Scope;
public ScopeWrapper(AP.ScopeInfo scope) {
Scope = scope;
}
public string Name {
get {
return Scope.name;
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Management.Automation;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Xml;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Management.ServiceManagement.Extensions;
using Microsoft.WindowsAzure.Management.ServiceManagement.Model;
using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo;
using Microsoft.WindowsAzure.Management.ServiceManagement.Test.Properties;
using Microsoft.WindowsAzure.ServiceManagement;
[TestClass]
public class FunctionalTest : ServiceManagementTest
{
bool createOwnService = false;
private static string defaultService;
private static string defaultVm;
private const string vhdName = "os.vhd";
private string serviceName;
private string vmName;
protected static string vhdBlobLocation;
[ClassInitialize]
public static void ClassInit(TestContext context)
{
SetTestSettings();
if (defaultAzureSubscription.Equals(null))
{
Assert.Inconclusive("No Subscription is selected!");
}
do
{
defaultService = Utilities.GetUniqueShortName(serviceNamePrefix);
}
while (vmPowershellCmdlets.TestAzureServiceName(defaultService));
defaultVm = Utilities.GetUniqueShortName(vmNamePrefix);
Assert.IsNull(vmPowershellCmdlets.GetAzureVM(defaultVm, defaultService));
vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, defaultVm, defaultService, imageName, username, password, locationName);
Console.WriteLine("Service Name: {0} is created.", defaultService);
vhdBlobLocation = string.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdName);
if (string.IsNullOrEmpty(localFile))
{
try
{
CopyTestData(testDataContainer, osVhdName, vhdContainerName, vhdName);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Assert.Inconclusive("Upload vhd is not set!");
}
}
else
{
try
{
vmPowershellCmdlets.AddAzureVhd(new FileInfo(localFile), vhdBlobLocation);
}
catch (Exception e)
{
if (e.ToString().Contains("already exists"))
{
// Use the already uploaded vhd.
Console.WriteLine("Using already uploaded blob..");
}
else
{
throw;
}
}
}
}
[TestInitialize]
public void Initialize()
{
ReImportSubscription();
pass = false;
testStartTime = DateTime.Now;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureStorageAccount)")]
[Ignore]
public void ScriptTestSample()
{
var result = vmPowershellCmdlets.RunPSScript("Get-Help Save-AzureVhd -full");
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove)-AzureAffinityGroup)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\affinityGroupData.csv", "affinityGroupData#csv", DataAccessMethod.Sequential)]
public void AzureAffinityGroupTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string affinityName1 = Convert.ToString(TestContext.DataRow["affinityName1"]);
string affinityLabel1 = Convert.ToString(TestContext.DataRow["affinityLabel1"]);
string location1 = CheckLocation(Convert.ToString(TestContext.DataRow["location1"]));
string description1 = Convert.ToString(TestContext.DataRow["description1"]);
string affinityName2 = Convert.ToString(TestContext.DataRow["affinityName2"]);
string affinityLabel2 = Convert.ToString(TestContext.DataRow["affinityLabel2"]);
string location2 = CheckLocation(Convert.ToString(TestContext.DataRow["location2"]));
string description2 = Convert.ToString(TestContext.DataRow["description2"]);
try
{
ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper();
// Remove previously created affinity groups
foreach (var aff in vmPowershellCmdlets.GetAzureAffinityGroup(null))
{
if (aff.Name == affinityName1 || aff.Name == affinityName2)
{
vmPowershellCmdlets.RemoveAzureAffinityGroup(aff.Name);
}
}
// New-AzureAffinityGroup
vmPowershellCmdlets.NewAzureAffinityGroup(affinityName1, location1, affinityLabel1, description1);
vmPowershellCmdlets.NewAzureAffinityGroup(affinityName2, location2, affinityLabel2, description2);
Console.WriteLine("Affinity groups created: {0}, {1}", affinityName1, affinityName2);
// Get-AzureAffinityGroup
pass = AffinityGroupVerify(vmPowershellCmdlets.GetAzureAffinityGroup(affinityName1)[0], affinityName1, affinityLabel1, location1, description1);
pass &= AffinityGroupVerify(vmPowershellCmdlets.GetAzureAffinityGroup(affinityName2)[0], affinityName2, affinityLabel2, location2, description2);
// Set-AzureAffinityGroup
vmPowershellCmdlets.SetAzureAffinityGroup(affinityName2, affinityLabel1, description1);
Console.WriteLine("update affinity group: {0}", affinityName2);
pass &= AffinityGroupVerify(vmPowershellCmdlets.GetAzureAffinityGroup(affinityName2)[0], affinityName2, affinityLabel1, location2, description1);
// Remove-AzureAffinityGroup
vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityName2);
pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityName2);
vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityName1);
pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityName1);
}
catch (Exception e)
{
pass = false;
Assert.Fail(e.ToString());
}
}
private bool AffinityGroupVerify(AffinityGroupContext affContext, string name, string label, string location, string description)
{
bool result = true;
Console.WriteLine("AffinityGroup: Name - {0}, Location - {1}, Label - {2}, Description - {3}", affContext.Name, affContext.Location, affContext.Label, affContext.Description);
try
{
Assert.AreEqual(affContext.Name, name, "Error: Affinity Name is not equal!");
Assert.AreEqual(affContext.Label, label, "Error: Affinity Label is not equal!");
Assert.AreEqual(affContext.Location, location, "Error: Affinity Location is not equal!");
Assert.AreEqual(affContext.Description, description, "Error: Affinity Description is not equal!");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
result = false;
}
return result;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Remove)-AzureCertificate)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\certificateData.csv", "certificateData#csv", DataAccessMethod.Sequential)]
public void AzureCertificateTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
const string DefaultCertificateIssuer = "CN=Windows Azure Powershell Test";
const string DefaultFriendlyName = "PSTest";
// Certificate files to test
string cerFileName = Convert.ToString(TestContext.DataRow["cerFileName"]);
string pfxFileName = Convert.ToString(TestContext.DataRow["pfxFileName"]);
string password = Convert.ToString(TestContext.DataRow["password"]);
string thumbprintAlgorithm = Convert.ToString(TestContext.DataRow["algorithm"]);
// Create a certificate
X509Certificate2 certCreated = Utilities.CreateCertificate(DefaultCertificateIssuer, DefaultFriendlyName, password);
byte[] certData = certCreated.Export(X509ContentType.Pfx, password);
File.WriteAllBytes(pfxFileName, certData);
byte[] certData2 = certCreated.Export(X509ContentType.Cert);
File.WriteAllBytes(cerFileName, certData2);
// Install the .cer file to local machine.
StoreLocation certStoreLocation = StoreLocation.CurrentUser;
StoreName certStoreName = StoreName.My;
X509Certificate2 installedCert = InstallCert(cerFileName, certStoreLocation, certStoreName);
// Certificate1: get it from the installed certificate.
PSObject cert1 = vmPowershellCmdlets.RunPSScript(
String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), installedCert.Thumbprint))[0];
string cert1data = Convert.ToBase64String(((X509Certificate2)cert1.BaseObject).RawData);
// Certificate2: get it from .pfx file.
X509Certificate2Collection cert2 = new X509Certificate2Collection();
cert2.Import(pfxFileName, password, X509KeyStorageFlags.PersistKeySet);
string cert2data = Convert.ToBase64String(cert2[0].RawData);
// Certificate3: get it from .cer file.
X509Certificate2Collection cert3 = new X509Certificate2Collection();
cert3.Import(cerFileName);
string cert3data = Convert.ToBase64String(cert3[0].RawData);
try
{
RemoveAllExistingCerts(defaultService);
// Add a cert item
vmPowershellCmdlets.AddAzureCertificate(defaultService, cert1);
CertificateContext getCert1 = vmPowershellCmdlets.GetAzureCertificate(defaultService)[0];
Console.WriteLine("Cert is added: {0}", getCert1.Thumbprint);
Assert.AreEqual(getCert1.Data, cert1data, "Cert is different!!");
vmPowershellCmdlets.RemoveAzureCertificate(defaultService, getCert1.Thumbprint, thumbprintAlgorithm);
pass = Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, getCert1.Thumbprint, thumbprintAlgorithm);
// Add .pfx file
vmPowershellCmdlets.AddAzureCertificate(defaultService, pfxFileName, password);
CertificateContext getCert2 = vmPowershellCmdlets.GetAzureCertificate(defaultService, cert2[0].Thumbprint, thumbprintAlgorithm)[0];
Console.WriteLine("Cert is added: {0}", cert2[0].Thumbprint);
Assert.AreEqual(getCert2.Data, cert2data, "Cert is different!!");
vmPowershellCmdlets.RemoveAzureCertificate(defaultService, cert2[0].Thumbprint, thumbprintAlgorithm);
pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, cert2[0].Thumbprint, thumbprintAlgorithm);
// Add .cer file
vmPowershellCmdlets.AddAzureCertificate(defaultService, cerFileName);
CertificateContext getCert3 = vmPowershellCmdlets.GetAzureCertificate(defaultService, cert3[0].Thumbprint, thumbprintAlgorithm)[0];
Console.WriteLine("Cert is added: {0}", cert3[0].Thumbprint);
Assert.AreEqual(getCert3.Data, cert3data, "Cert is different!!");
vmPowershellCmdlets.RemoveAzureCertificate(defaultService, cert3[0].Thumbprint, thumbprintAlgorithm);
pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, cert3[0].Thumbprint, thumbprintAlgorithm);
}
catch (Exception e)
{
pass = false;
Assert.Fail(e.ToString());
}
finally
{
UninstallCert(installedCert, certStoreLocation, certStoreName);
RemoveAllExistingCerts(defaultService);
}
}
private void RemoveAllExistingCerts(string serviceName)
{
vmPowershellCmdlets.RunPSScript(String.Format("{0} -ServiceName {1} | {2}", Utilities.GetAzureCertificateCmdletName, serviceName, Utilities.RemoveAzureCertificateCmdletName));
}
private X509Certificate2 InstallCert(string certFile, StoreLocation location, StoreName name)
{
X509Certificate2 cert = new X509Certificate2(certFile);
X509Store certStore = new X509Store(name, location);
certStore.Open(OpenFlags.ReadWrite);
certStore.Add(cert);
certStore.Close();
Console.WriteLine("Cert, {0}, is installed.", cert.Thumbprint);
return cert;
}
private void UninstallCert(X509Certificate2 cert, StoreLocation location, StoreName name)
{
try
{
X509Store certStore = new X509Store(name, location);
certStore.Open(OpenFlags.ReadWrite);
certStore.Remove(cert);
certStore.Close();
Console.WriteLine("Cert, {0}, is uninstalled.", cert.Thumbprint);
}
catch (Exception e)
{
Console.WriteLine("Error during uninstalling the cert: {0}", e.ToString());
throw;
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (New-AzureCertificateSetting)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\certificateData.csv", "certificateData#csv", DataAccessMethod.Sequential)]
public void AzureCertificateSettingTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
const string DefaultCertificateIssuer = "CN=Windows Azure Powershell Test";
const string DefaultFriendlyName = "PSTest";
// Create a certificate
string cerFileName = Convert.ToString(TestContext.DataRow["cerFileName"]);
X509Certificate2 certCreated = Utilities.CreateCertificate(DefaultCertificateIssuer, DefaultFriendlyName, password);
byte[] certData2 = certCreated.Export(X509ContentType.Cert);
File.WriteAllBytes(cerFileName, certData2);
// Install the .cer file to local machine.
StoreLocation certStoreLocation = StoreLocation.CurrentUser;
StoreName certStoreName = StoreName.My;
X509Certificate2 installedCert = InstallCert(cerFileName, certStoreLocation, certStoreName);
PSObject certToUpload = vmPowershellCmdlets.RunPSScript(
String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), installedCert.Thumbprint))[0];
try
{
vmName = Utilities.GetUniqueShortName(vmNamePrefix);
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmPowershellCmdlets.NewAzureService(serviceName, locationName);
vmPowershellCmdlets.AddAzureCertificate(serviceName, certToUpload);
CertificateSettingList certList = new CertificateSettingList();
certList.Add(vmPowershellCmdlets.NewAzureCertificateSetting(certStoreName.ToString(), installedCert.Thumbprint));
AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, InstanceSize.Small, imageName);
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, certList, username, password);
PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null);
PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo);
vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm });
PersistentVMRoleContext result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName);
Console.WriteLine("{0} is created", result.Name);
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail(e.ToString());
}
finally
{
UninstallCert(installedCert, certStoreLocation, certStoreName);
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Set,Remove)-AzureDataDisk)")]
public void AzureDataDiskTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string diskLabel1 = "disk1";
int diskSize1 = 30;
int lunSlot1 = 0;
string diskLabel2 = "disk2";
int diskSize2 = 50;
int lunSlot2 = 2;
try
{
AddAzureDataDiskConfig dataDiskInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize1, diskLabel1, lunSlot1);
AddAzureDataDiskConfig dataDiskInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize2, diskLabel2, lunSlot2);
vmPowershellCmdlets.AddDataDisk(defaultVm, defaultService, new [] {dataDiskInfo1, dataDiskInfo2}); // Add-AzureEndpoint with Get-AzureVM and Update-AzureVm
Assert.IsTrue(CheckDataDisk(defaultVm, defaultService, dataDiskInfo1, HostCaching.None), "Data disk is not properly added");
Console.WriteLine("Data disk added correctly.");
Assert.IsTrue(CheckDataDisk(defaultVm, defaultService, dataDiskInfo2, HostCaching.None), "Data disk is not properly added");
Console.WriteLine("Data disk added correctly.");
vmPowershellCmdlets.SetDataDisk(defaultVm, defaultService, HostCaching.ReadOnly, lunSlot1);
Assert.IsTrue(CheckDataDisk(defaultVm, defaultService, dataDiskInfo1, HostCaching.ReadOnly), "Data disk is not properly changed");
Console.WriteLine("Data disk is changed correctly.");
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
// Remove DataDisks created
foreach (DataVirtualHardDisk disk in vmPowershellCmdlets.GetAzureDataDisk(defaultVm, defaultService))
{
vmPowershellCmdlets.RemoveDataDisk(defaultVm, defaultService, new[] { disk.Lun }); // Remove-AzureDataDisk
RemoveDisk(disk.DiskName, 10);
}
Assert.AreEqual(0, vmPowershellCmdlets.GetAzureDataDisk(defaultVm, defaultService).Count, "DataDisk is not removed.");
}
}
private void RemoveDisk(string diskName, int maxTry)
{
for (int i = 0; i < maxTry ; i++)
{
try
{
vmPowershellCmdlets.RemoveAzureDisk(diskName, true);
break;
}
catch (Exception e)
{
if (i == maxTry)
{
Console.WriteLine("Max try reached. Couldn't delete the Virtual disk");
}
if (e.ToString().Contains("currently in use"))
{
Thread.Sleep(5000);
continue;
}
}
}
}
private bool CheckDataDisk(string vmName, string serviceName, AddAzureDataDiskConfig dataDiskInfo, HostCaching hc)
{
bool found = false;
foreach (DataVirtualHardDisk disk in vmPowershellCmdlets.GetAzureDataDisk(vmName, serviceName))
{
Console.WriteLine("DataDisk - Name:{0}, Label:{1}, Size:{2}, LUN:{3}, HostCaching: {4}", disk.DiskName, disk.DiskLabel, disk.LogicalDiskSizeInGB, disk.Lun, disk.HostCaching);
if (disk.DiskLabel == dataDiskInfo.DiskLabel && disk.LogicalDiskSizeInGB == dataDiskInfo.DiskSizeGB && disk.Lun == dataDiskInfo.LunSlot)
{
if (disk.HostCaching == hc.ToString())
{
found = true;
Console.WriteLine("DataDisk found: {0}", disk.DiskLabel);
}
}
}
return found;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Update,Remove)-AzureDisk)")]
public void AzureDiskTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string mediaLocation = String.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdName);
try
{
vmPowershellCmdlets.AddAzureDisk(vhdName, mediaLocation, vhdName, null);
bool found = false;
foreach (DiskContext disk in vmPowershellCmdlets.GetAzureDisk(vhdName))
{
Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk.DiskName, disk.Label, disk.DiskSizeInGB);
if (disk.DiskName == vhdName && disk.Label == vhdName)
{
found = true;
Console.WriteLine("{0} is found", disk.DiskName);
}
}
Assert.IsTrue(found, "Error: Disk is not added");
string newLabel = "NewLabel";
vmPowershellCmdlets.UpdateAzureDisk(vhdName, newLabel);
DiskContext disk2 = vmPowershellCmdlets.GetAzureDisk(vhdName)[0];
Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk2.DiskName, disk2.Label, disk2.DiskSizeInGB);
Assert.AreEqual(newLabel, disk2.Label);
Console.WriteLine("Disk Label is successfully updated");
vmPowershellCmdlets.RemoveAzureDisk(vhdName, false);
Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDisk, vhdName), "The disk was not removed");
}
catch (Exception e)
{
pass = false;
if (e.ToString().Contains("ResourceNotFound"))
{
Console.WriteLine("Please upload {0} file to \\vhdtest\\ blob directory before running this test", vhdName);
}
Assert.Fail("Exception occurs: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove,Move)-AzureDeployment)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)]
public void AzureDeploymentTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
// Choose the package and config files from local machine
string packageName = Convert.ToString(TestContext.DataRow["packageName"]);
string configName = Convert.ToString(TestContext.DataRow["configName"]);
string upgradePackageName = Convert.ToString(TestContext.DataRow["upgradePackage"]);
string upgradeConfigName = Convert.ToString(TestContext.DataRow["upgradeConfig"]);
string upgradeConfigName2 = Convert.ToString(TestContext.DataRow["upgradeConfig2"]);
var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName);
var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName);
var packagePath2 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + upgradePackageName);
var configPath2 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + upgradeConfigName);
var configPath3 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + upgradeConfigName2);
Assert.IsTrue(File.Exists(packagePath1.FullName), "file not exist={0}", packagePath1);
Assert.IsTrue(File.Exists(packagePath2.FullName), "file not exist={0}", packagePath2);
Assert.IsTrue(File.Exists(configPath1.FullName), "file not exist={0}", configPath1);
Assert.IsTrue(File.Exists(configPath2.FullName), "file not exist={0}", configPath2);
Assert.IsTrue(File.Exists(configPath3.FullName), "file not exist={0}", configPath3);
string deploymentName = "deployment1";
string deploymentLabel = "label1";
DeploymentInfoContext result;
try
{
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
Console.WriteLine("service, {0}, is created.", serviceName);
vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Staging, deploymentLabel, deploymentName, false, false);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Staging);
pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Staging, null, 1);
Console.WriteLine("successfully deployed the package");
// Move the deployment from 'Staging' to 'Production'
vmPowershellCmdlets.MoveAzureDeployment(serviceName);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 1);
Console.WriteLine("successfully moved");
// Set the deployment status to 'Suspended'
vmPowershellCmdlets.SetAzureDeploymentStatus(serviceName, DeploymentSlotType.Production, DeploymentStatus.Suspended);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, DeploymentStatus.Suspended, 1);
Console.WriteLine("successfully changed the status");
// Update the deployment
vmPowershellCmdlets.SetAzureDeploymentConfig(serviceName, DeploymentSlotType.Production, configPath2.FullName);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2);
Console.WriteLine("successfully updated the deployment");
// Upgrade the deployment
DateTime start = DateTime.Now;
vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Simultaneous, packagePath2.FullName, configPath3.FullName);
TimeSpan duration = DateTime.Now - start;
Console.WriteLine("Auto upgrade took {0}.", duration);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 4);
Console.WriteLine("successfully updated the deployment");
vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true);
pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production);
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
}
}
/// <summary>
///
/// </summary>
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get)-AzureDns)")]
public void AzureDnsTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string dnsName = "OpenDns1";
string ipAddress = "208.67.222.222";
try
{
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmPowershellCmdlets.NewAzureService(serviceName, locationName);
DnsServer dns = vmPowershellCmdlets.NewAzureDns(dnsName, ipAddress);
AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, InstanceSize.ExtraSmall, imageName);
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password);
PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null);
PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo);
vmPowershellCmdlets.NewAzureVM(serviceName, new []{vm}, null, new[]{dns}, null, null, null, null, null, null);
DnsServerList dnsList = vmPowershellCmdlets.GetAzureDns(vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production).DnsSettings);
foreach (DnsServer dnsServer in dnsList)
{
Console.WriteLine("DNS Server Name: {0}, DNS Server Address: {1}", dnsServer.Name, dnsServer.Address);
Assert.AreEqual(dnsServer.Name, dns.Name);
Assert.AreEqual(dnsServer.Address, dns.Address);
}
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet Set-AzureAvailabilitySet)")]
public void AzureAvailabilitySetTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string testAVSetName = "testAVSet1";
try
{
var vm = vmPowershellCmdlets.SetAzureAvailabilitySet(defaultVm, defaultService, testAVSetName);
vmPowershellCmdlets.UpdateAzureVM(defaultVm, defaultService, vm);
CheckAvailabilitySet(defaultVm, defaultService, testAVSetName);
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
private void CheckAvailabilitySet(string vmName, string serviceName, string availabilitySetName)
{
var vm = vmPowershellCmdlets.GetAzureVM(vmName, serviceName);
Assert.IsTrue(vm.AvailabilitySetName.Equals(availabilitySetName, StringComparison.InvariantCultureIgnoreCase));
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureLocation)")]
public void AzureLocationTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
foreach (LocationsContext loc in vmPowershellCmdlets.GetAzureLocation())
{
Console.WriteLine("Location: Name - {0}, DisplayName - {1}", loc.Name, loc.DisplayName);
}
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureOSDisk)")]
public void AzureOSDiskTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
PersistentVM vm = vmPowershellCmdlets.GetAzureVM(defaultVm, defaultService).VM;
OSVirtualHardDisk osdisk = vmPowershellCmdlets.GetAzureOSDisk(vm);
Console.WriteLine("OS Disk: Name - {0}, Label - {1}, HostCaching - {2}, OS - {3}", osdisk.DiskName, osdisk.DiskLabel, osdisk.HostCaching, osdisk.OS);
Assert.IsTrue(osdisk.Equals(vm.OSVirtualHardDisk), "OS disk returned is not the same!");
PersistentVM vm2 = vmPowershellCmdlets.SetAzureOSDisk(HostCaching.ReadOnly, vm);
osdisk = vmPowershellCmdlets.GetAzureOSDisk(vm2);
Console.WriteLine("OS Disk: Name - {0}, Label - {1}, HostCaching - {2}, OS - {3}", osdisk.DiskName, osdisk.DiskLabel, osdisk.HostCaching, osdisk.OS);
Assert.IsTrue(osdisk.Equals(vm2.OSVirtualHardDisk), "OS disk returned is not the same!");
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureOSVersion)")]
public void AzureOSVersionTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
foreach (OSVersionsContext osVersions in vmPowershellCmdlets.GetAzureOSVersion())
{
Console.WriteLine("OS Version: Family - {0}, FamilyLabel - {1}, Version - {2}", osVersions.Family, osVersions.FamilyLabel, osVersions.Version);
}
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureRole)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)]
public void AzureRoleTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
// Choose the package and config files from local machine
string packageName = Convert.ToString(TestContext.DataRow["packageName"]);
string configName = Convert.ToString(TestContext.DataRow["configName"]);
string upgradePackageName = Convert.ToString(TestContext.DataRow["upgradePackage"]);
string upgradeConfigName = Convert.ToString(TestContext.DataRow["upgradeConfig"]);
var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName);
var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName);
Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1);
Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1);
string deploymentName = "deployment1";
string deploymentLabel = "label1";
string slot = DeploymentSlotType.Production;
//DeploymentInfoContext result;
string roleName = "";
try
{
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, slot, deploymentLabel, deploymentName, false, false);
foreach (RoleContext role in vmPowershellCmdlets.GetAzureRole(serviceName, slot, null, false))
{
Console.WriteLine("Role: Name - {0}, ServiceName - {1}, DeploymenntID - {2}, InstanceCount - {3}", role.RoleName, role.ServiceName, role.DeploymentID, role.InstanceCount);
Assert.AreEqual(serviceName, role.ServiceName);
roleName = role.RoleName;
}
vmPowershellCmdlets.SetAzureRole(serviceName, slot, roleName, 2);
foreach (RoleContext role in vmPowershellCmdlets.GetAzureRole(serviceName, slot, null, false))
{
Console.WriteLine("Role: Name - {0}, ServiceName - {1}, DeploymenntID - {2}, InstanceCount - {3}", role.RoleName, role.ServiceName, role.DeploymentID, role.InstanceCount);
Assert.AreEqual(serviceName, role.ServiceName);
Assert.AreEqual(2, role.InstanceCount);
}
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (New-AzureServiceRemoteDesktopConfig)")]
public void AzureServiceDiagnosticsExtensionConfigTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
List<string> defaultRoles = new List<string>(new string[] { "AllRoles" });
string[] roles = new string[] { "WebRole1", "WorkerRole2" };
string thumb = "abc";
string alg = "sha1";
// Create a certificate
const string DefaultCertificateIssuer = "CN=Windows Azure Powershell Test";
const string DefaultFriendlyName = "PSTest";
X509Certificate2 cert = Utilities.CreateCertificate(DefaultCertificateIssuer, DefaultFriendlyName, password);
string storage = defaultAzureSubscription.CurrentStorageAccount;
XmlDocument daConfig = new XmlDocument();
daConfig.Load(@".\da.xml");
try
{
//// Case 1: No thumbprint, no Certificate
ExtensionConfigurationInput resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, defaultRoles));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, daConfig);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, defaultRoles, daConfig));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, null, roles);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, new List<string>(roles)));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, daConfig, roles);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, new List<string>(roles), daConfig));
// Case 2: Thumbprint, no algorithm
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, thumb, null);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, defaultRoles, null, thumb));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, thumb, null, daConfig);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, defaultRoles, daConfig, thumb));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, thumb, null, null, roles);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, new List<string>(roles), null, thumb));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, thumb, null, daConfig, roles);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, new List<string>(roles), daConfig, thumb));
// Case 3: Thumbprint and algorithm
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, thumb, alg);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, defaultRoles, null, thumb, alg));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, thumb, alg, daConfig);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, defaultRoles, daConfig, thumb, alg));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, thumb, alg, null, roles);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, new List<string>(roles), null, thumb, alg));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, thumb, alg, daConfig, roles);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, new List<string>(roles), daConfig, thumb, alg));
// Case 4: Certificate
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, cert);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, defaultRoles, null, cert.Thumbprint, null, cert));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, cert, daConfig);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, defaultRoles, daConfig, cert.Thumbprint, null, cert));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, cert, null, roles);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, new List<string>(roles), null, cert.Thumbprint, null, cert));
resultConfig = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, cert, daConfig, roles);
Assert.IsTrue(VerifyExtensionConfigDiag(resultConfig, storage, new List<string>(roles), daConfig, cert.Thumbprint, null, cert));
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
private bool VerifyExtensionConfigDiag(ExtensionConfigurationInput resultConfig, string storage, List<string> roles, XmlDocument wadconfig = null, string thumbprint = null, string algorithm = null, X509Certificate2 cert = null)
{
try
{
string resultStorageAccount = GetInnerText(resultConfig.PublicConfiguration, "Name");
string resultWadCfg = Utilities.GetInnerXml(resultConfig.PublicConfiguration, "WadCfg");
if (string.IsNullOrWhiteSpace(resultWadCfg))
{
resultWadCfg = null;
}
string resultStorageKey = GetInnerText(resultConfig.PrivateConfiguration, "StorageKey");
Console.WriteLine("Type: {0}, StorageAccountName:{1}, StorageKey: {2}, WadCfg: {3}, CertificateThumbprint: {4}, ThumbprintAlgorithm: {5}, X509Certificate: {6}",
resultConfig.Type, resultStorageAccount, resultStorageKey, resultWadCfg, resultConfig.CertificateThumbprint, resultConfig.ThumbprintAlgorithm, resultConfig.X509Certificate);
Assert.AreEqual(resultConfig.Type, "Diagnostics", "Type is not equal!");
Assert.AreEqual(resultStorageAccount, storage);
Assert.IsTrue(Utilities.CompareWadCfg(resultWadCfg, wadconfig));
if (string.IsNullOrWhiteSpace(thumbprint))
{
Assert.IsTrue(string.IsNullOrWhiteSpace(resultConfig.CertificateThumbprint));
}
else
{
Assert.AreEqual(resultConfig.CertificateThumbprint, thumbprint, "Certificate thumbprint is not equal!");
}
if (string.IsNullOrWhiteSpace(algorithm))
{
Assert.IsTrue(string.IsNullOrWhiteSpace(resultConfig.ThumbprintAlgorithm));
}
else
{
Assert.AreEqual(resultConfig.ThumbprintAlgorithm, algorithm, "Thumbprint algorithm is not equal!");
}
Assert.AreEqual(resultConfig.X509Certificate, cert, "X509Certificate is not equal!");
if (resultConfig.Roles.Count == 1 && string.IsNullOrEmpty(resultConfig.Roles[0].RoleName))
{
Assert.IsTrue(roles.Contains(resultConfig.Roles[0].RoleType.ToString()));
}
else
{
foreach (ExtensionRole role in resultConfig.Roles)
{
Assert.IsTrue(roles.Contains(role.RoleName));
}
}
return true;
}
catch
{
return false;
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (New-AzureServiceRemoteDesktopConfig)")]
public void AzureServiceRemoteDesktopExtensionConfigTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
PSCredential cred = new PSCredential(username, Utilities.convertToSecureString(password));
DateTime exp = DateTime.Now.AddYears(1);
DateTime defaultExp = DateTime.Now.AddMonths(6);
List<string> defaultRoles = new List<string>(new string[] { "AllRoles" });
string[] roles = new string[]{"WebRole1", "WorkerRole2"};
string thumb = "abc";
string alg = "sha1";
// Create a certificate
const string DefaultCertificateIssuer = "CN=Windows Azure Powershell Test";
const string DefaultFriendlyName = "PSTest";
X509Certificate2 cert = Utilities.CreateCertificate(DefaultCertificateIssuer, DefaultFriendlyName, password);
try
{
// Case 1: No thumbprint, no Certificate
ExtensionConfigurationInput resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, defaultRoles, defaultExp));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, exp);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, defaultRoles, exp));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, null, roles);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, new List<string>(roles), defaultExp));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, exp, roles);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, new List<string>(roles), exp));
// Case 2: Thumbprint, no algorithm
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, thumb, null);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, defaultRoles, defaultExp, thumb));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, thumb, null, exp);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, defaultRoles, exp, thumb));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, thumb, null, null, roles);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, new List<string>(roles), defaultExp, thumb));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, thumb, null, exp, roles);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, new List<string>(roles), exp, thumb));
// Case 3: Thumbprint and algorithm
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, thumb, alg);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, defaultRoles, defaultExp, thumb, alg));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, thumb, alg, exp);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, defaultRoles, exp, thumb, alg));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, thumb, alg, null, roles);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, new List<string>(roles), defaultExp, thumb, alg));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, thumb, alg, exp, roles);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, new List<string>(roles), exp, thumb, alg));
// Case 4: Certificate
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, cert);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, defaultRoles, defaultExp, cert.Thumbprint, null, cert));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, cert, null, exp);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, defaultRoles, exp, cert.Thumbprint, null, cert));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, cert, null, null, roles);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, new List<string>(roles), defaultExp, cert.Thumbprint, null, cert));
resultConfig = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred, cert, null, exp, roles);
Assert.IsTrue(VerifyExtensionConfigRDP(resultConfig, username, password, new List<string>(roles), exp, cert.Thumbprint, null, cert));
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
private bool VerifyExtensionConfigRDP(ExtensionConfigurationInput resultConfig, string user, string pass, List<string> roles, DateTime exp, string thumbprint = null, string algorithm = null, X509Certificate2 cert = null)
{
try
{
string resultUserName = GetInnerText(resultConfig.PublicConfiguration, "UserName");
string resultPassword = GetInnerText(resultConfig.PrivateConfiguration, "Password");
string resultExpDate = GetInnerText(resultConfig.PublicConfiguration, "Expiration");
Console.WriteLine("Type: {0}, UserName:{1}, Password: {2}, ExpirationDate: {3}, CertificateThumbprint: {4}, ThumbprintAlgorithm: {5}, X509Certificate: {6}",
resultConfig.Type, resultUserName, resultPassword, resultExpDate, resultConfig.CertificateThumbprint, resultConfig.ThumbprintAlgorithm, resultConfig.X509Certificate);
Assert.AreEqual(resultConfig.Type, "RDP", "Type is not equal!");
Assert.AreEqual(resultUserName, user);
Assert.AreEqual(resultPassword, pass);
Assert.IsTrue(Utilities.CompareDateTime(exp, resultExpDate));
if (string.IsNullOrWhiteSpace(thumbprint))
{
Assert.IsTrue(string.IsNullOrWhiteSpace(resultConfig.CertificateThumbprint));
}
else
{
Assert.AreEqual(resultConfig.CertificateThumbprint, thumbprint, "Certificate thumbprint is not equal!");
}
if (string.IsNullOrWhiteSpace(algorithm))
{
Assert.IsTrue(string.IsNullOrWhiteSpace(resultConfig.ThumbprintAlgorithm));
}
else
{
Assert.AreEqual(resultConfig.ThumbprintAlgorithm, algorithm, "Thumbprint algorithm is not equal!");
}
Assert.AreEqual(resultConfig.X509Certificate, cert, "X509Certificate is not equal!");
if (resultConfig.Roles.Count == 1 && string.IsNullOrEmpty(resultConfig.Roles[0].RoleName))
{
Assert.IsTrue(roles.Contains(resultConfig.Roles[0].RoleType.ToString()));
}
else
{
foreach (ExtensionRole role in resultConfig.Roles)
{
Assert.IsTrue(roles.Contains(role.RoleName));
}
}
return true;
}
catch
{
return false;
}
}
private string GetInnerText(string xmlString, string tag)
{
string removedHeader = xmlString.Substring(xmlString.IndexOf('<', 2));
byte[] encodedString = Encoding.UTF8.GetBytes(xmlString);
MemoryStream stream = new MemoryStream(encodedString);
stream.Flush();
stream.Position = 0;
XmlDocument xml = new XmlDocument();
xml.Load(stream);
return xml.GetElementsByTagName(tag)[0].InnerText;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureSubnet)")]
public void AzureSubnetTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
PersistentVM vm = vmPowershellCmdlets.NewAzureVMConfig(new AzureVMConfigInfo(vmName, InstanceSize.Small, imageName));
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password);
azureProvisioningConfig.Vm = vm;
string [] subs = new [] {"subnet1", "subnet2", "subnet3"};
vm = vmPowershellCmdlets.SetAzureSubnet(vmPowershellCmdlets.AddAzureProvisioningConfig(azureProvisioningConfig), subs);
SubnetNamesCollection subnets = vmPowershellCmdlets.GetAzureSubnet(vm);
foreach (string subnet in subnets)
{
Console.WriteLine("Subnet: {0}", subnet);
}
CollectionAssert.AreEqual(subnets, subs);
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get)-AzureStorageKey)")]
public void AzureStorageKeyTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
StorageServiceKeyOperationContext key1 = vmPowershellCmdlets.GetAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccount); // Get-AzureStorageAccountKey
Console.WriteLine("Primary - {0}", key1.Primary);
Console.WriteLine("Secondary - {0}", key1.Secondary);
StorageServiceKeyOperationContext key2 = vmPowershellCmdlets.NewAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccount, KeyType.Secondary);
Console.WriteLine("Primary - {0}", key2.Primary);
Console.WriteLine("Secondary - {0}", key2.Secondary);
Assert.AreEqual(key1.Primary, key2.Primary);
Assert.AreNotEqual(key1.Secondary, key2.Secondary);
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove)-AzureStorageAccount)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\storageAccountTestData.csv", "storageAccountTestData#csv", DataAccessMethod.Sequential)]
public void AzureStorageAccountTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string storageAccountPrefix = Convert.ToString(TestContext.DataRow["NamePrefix"]);
string locationName1 = CheckLocation(Convert.ToString(TestContext.DataRow["Location1"]));
string locationName2 = CheckLocation(Convert.ToString(TestContext.DataRow["Location2"]));
string affinityGroupName = Convert.ToString(TestContext.DataRow["AffinityGroupName"]);
string[] label = new string[3] {
Convert.ToString(TestContext.DataRow["Label1"]),
Convert.ToString(TestContext.DataRow["Label2"]),
Convert.ToString(TestContext.DataRow["Label3"])};
string[] description = new string[3] {
Convert.ToString(TestContext.DataRow["Description1"]),
Convert.ToString(TestContext.DataRow["Description2"]),
Convert.ToString(TestContext.DataRow["Description3"])};
bool?[] geoReplicationSettings = new bool?[3] { true, false, null };
bool geoReplicationEnabled = true;
string[] storageName = new string[2] {
Utilities.GetUniqueShortName(storageAccountPrefix),
Utilities.GetUniqueShortName(storageAccountPrefix)};
string[][] storageStaticProperties = new string[2][] {
new string[3] {storageName[0], locationName1, null},
new string [3] {storageName[1], null, affinityGroupName}};
try
{
// New-AzureStorageAccount test
vmPowershellCmdlets.NewAzureStorageAccount(storageName[0], locationName1, null, null, null);
Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[0])[0],
storageStaticProperties[0], storageName[0], null, true));
Console.WriteLine("{0} is created", storageName[0]);
if (Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityGroupName))
{
vmPowershellCmdlets.NewAzureAffinityGroup(affinityGroupName, locationName2, label[0], description[0]);
}
vmPowershellCmdlets.NewAzureStorageAccount(storageName[1], null, affinityGroupName, null, null);
Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[1])[0],
storageStaticProperties[1], storageName[1], null, true));
Console.WriteLine("{0} is created", storageName[1]);
// Set-AzureStorageAccount & Remove-AzureStorageAccount test
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
vmPowershellCmdlets.SetAzureStorageAccount(storageName[i], label[j], null, geoReplicationSettings[j]);
if (geoReplicationSettings[j] != null)
{
geoReplicationEnabled = geoReplicationSettings[j].Value;
}
Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[i])[0],
storageStaticProperties[i], label[j], null, geoReplicationEnabled));
}
for (int j = 0; j < 3; j++)
{
vmPowershellCmdlets.SetAzureStorageAccount(storageName[i], null, description[j], geoReplicationSettings[j]);
if (geoReplicationSettings[j] != null)
{
geoReplicationEnabled = geoReplicationSettings[j].Value;
}
Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[i])[0],
storageStaticProperties[i], label[2], description[j], geoReplicationEnabled));
}
for (int j = 0; j < 3; j++)
{
vmPowershellCmdlets.SetAzureStorageAccount(storageName[i], null, null, geoReplicationSettings[j]);
if (geoReplicationSettings[j] != null)
{
geoReplicationEnabled = geoReplicationSettings[j].Value;
}
Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[i])[0],
storageStaticProperties[i], label[2], description[2], geoReplicationEnabled));
}
for (int j = 0; j < 3; j++)
{
vmPowershellCmdlets.SetAzureStorageAccount(storageName[i], label[j], description[j], geoReplicationSettings[j]);
if (geoReplicationSettings[j] != null)
{
geoReplicationEnabled = geoReplicationSettings[j].Value;
}
Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[i])[0],
storageStaticProperties[i], label[j], description[j], geoReplicationEnabled));
}
vmPowershellCmdlets.RemoveAzureStorageAccount(storageName[i]);
Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureStorageAccount, storageName[i]), "The storage account was not removed");
}
vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityGroupName);
pass = true;
}
catch (Exception e)
{
pass = false;
// Clean-up storage if it is not removed.
foreach (string storage in storageName)
{
if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureStorageAccount, storage))
{
vmPowershellCmdlets.RemoveAzureStorageAccount(storage);
}
}
// Clean-up affinity group created.
if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityGroupName))
{
vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityGroupName);
}
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
private bool StorageAccountVerify(StorageServicePropertiesOperationContext storageContext,
string [] staticParameters, string label, string description, bool geo)
{
string name = staticParameters[0];
string location = staticParameters[1];
string affinity = staticParameters[2];
Console.WriteLine("Name: {0}, Label: {1}, Description: {2}, AffinityGroup: {3}, Location: {4}, GeoReplicationEnabled: {5}",
storageContext.StorageAccountName,
storageContext.Label,
storageContext.StorageAccountDescription,
storageContext.AffinityGroup,
storageContext.Location,
storageContext.GeoReplicationEnabled);
try
{
Assert.AreEqual(storageContext.StorageAccountName, name, "Error: Storage Account Name is not equal!");
Assert.AreEqual(storageContext.Label, label, "Error: Storage Account Label is not equal!");
Assert.AreEqual(storageContext.StorageAccountDescription, description, "Error: Storage Account Description is not equal!");
Assert.AreEqual(storageContext.AffinityGroup, affinity, "Error: Affinity Group is not equal!");
Assert.AreEqual(storageContext.Location, location, "Error: Location is not equal!");
Assert.AreEqual(storageContext.GeoReplicationEnabled, geo, "Error: GeoReplicationEnabled is not equal!");
Console.WriteLine("All contexts are matched!!\n");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
return true;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Save,Update,Remove)-AzureVMImage)")]
public void AzureVMImageTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string newImageName = Utilities.GetUniqueShortName("vmimage");
string mediaLocation = string.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdName);
string oldLabel = "old label";
string newLabel = "new label";
try
{
OSImageContext result = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OS.Windows, oldLabel);
OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0];
Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned));
result = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, newLabel);
resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0];
Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned));
vmPowershellCmdlets.RemoveAzureVMImage(newImageName, true);
Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureVMImage, newImageName));
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureVMImage, newImageName))
{
vmPowershellCmdlets.RemoveAzureVMImage(newImageName, true);
}
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set,Remove)-AzureVNetConfig)")]
public void AzureVNetConfigTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string affinityGroup = "WestUsAffinityGroup";
try
{
if (Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityGroup))
{
vmPowershellCmdlets.NewAzureAffinityGroup(affinityGroup, Resource.Location, null, null);
}
vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath);
var result = vmPowershellCmdlets.GetAzureVNetConfig(vnetConfigFilePath);
vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath);
Collection<VirtualNetworkSiteContext> vnetSites = vmPowershellCmdlets.GetAzureVNetSite(null);
foreach (var re in vnetSites)
{
Console.WriteLine("VNet: {0}", re.Name);
}
vmPowershellCmdlets.RemoveAzureVNetConfig();
Collection<VirtualNetworkSiteContext> vnetSitesAfter = vmPowershellCmdlets.GetAzureVNetSite(null);
Assert.AreNotEqual(vnetSites.Count, vnetSitesAfter.Count, "No Vnet is removed");
foreach (var re in vnetSitesAfter)
{
Console.WriteLine("VNet: {0}", re.Name);
}
pass = true;
}
catch (Exception e)
{
if (e.ToString().Contains("while in use"))
{
Console.WriteLine(e.InnerException.ToString());
}
else
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Set,Remove)-AzureEndpoint)")]
[Ignore]
public void VMSizeTest()
{
string newImageName = Utilities.GetUniqueShortName("vmimage");
string mediaLocation = string.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdName);
string a6ServiceName = Utilities.GetUniqueShortName(serviceNamePrefix);
string a6VmName = Utilities.GetUniqueShortName(vmNamePrefix);
try
{
Array instanceSizes = Enum.GetValues(typeof(InstanceSize));
int arrayLength = instanceSizes.GetLength(0);
for (int i = 1; i < arrayLength; i++)
{
// Add-AzureVMImage test for VM size
OSImageContext result2 = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OS.Windows, (InstanceSize)instanceSizes.GetValue(i));
OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0];
Assert.IsTrue(CompareContext<OSImageContext>(result2, resultReturned));
// Update-AzureVMImage test for VM size
result2 = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, (InstanceSize)instanceSizes.GetValue(Math.Max((i + 1) % arrayLength, 1)));
resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0];
Assert.IsTrue(CompareContext<OSImageContext>(result2, resultReturned));
vmPowershellCmdlets.RemoveAzureVMImage(newImageName);
}
vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, a6VmName, a6ServiceName, imageName, username, password, locationName, InstanceSize.A6);
PersistentVMRoleContext result;
foreach (InstanceSize size in instanceSizes)
{
if (size.Equals(InstanceSize.A6) || size.Equals(InstanceSize.A7))
{ // We skip tests for regular VM sizes. Also, a VM created with regular size cannot be updated to Hi-MEM.
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmName = Utilities.GetUniqueShortName(vmNamePrefix);
// New-AzureQuickVM test for VM size
result = vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, username, password, locationName, size);
Assert.AreEqual(size.ToString(), result.InstanceSize);
Console.WriteLine("VM size, {0}, is verified for New-AzureQuickVM", size.ToString());
vmPowershellCmdlets.RemoveAzureVM(vmName, serviceName);
// New-AzureVMConfig test for VM size
AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, size, imageName);
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password);
PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null);
PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo);
vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm });
result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName);
Assert.AreEqual(size.ToString(), result.InstanceSize);
Console.WriteLine("VM size, {0}, is verified for New-AzureVMConfig", size.ToString());
vmPowershellCmdlets.RemoveAzureVM(vmName, serviceName);
vmPowershellCmdlets.RemoveAzureService(serviceName);
}
if (!size.Equals(InstanceSize.A6) && !size.Equals(InstanceSize.A7))
{
// Set-AzureVMSize test for regular VM size
vmPowershellCmdlets.SetVMSize(defaultVm, defaultService, new SetAzureVMSizeConfig(size));
result = vmPowershellCmdlets.GetAzureVM(defaultVm, defaultService);
Assert.AreEqual(size.ToString(), result.InstanceSize);
Console.WriteLine("VM size, {0}, is verified for Set-AzureVMSize", size.ToString());
}
if (size.Equals(InstanceSize.ExtraLarge))
{
vmPowershellCmdlets.SetVMSize(defaultVm, defaultService, new SetAzureVMSizeConfig(InstanceSize.Small));
result = vmPowershellCmdlets.GetAzureVM(defaultVm, defaultService);
Assert.AreEqual(InstanceSize.Small.ToString(), result.InstanceSize);
}
if (size.Equals(InstanceSize.A7))
{
// Set-AzureVMSize test for Hi-MEM VM size
vmPowershellCmdlets.SetVMSize(a6VmName, a6ServiceName, new SetAzureVMSizeConfig(size));
result = vmPowershellCmdlets.GetAzureVM(a6VmName, a6ServiceName);
Assert.AreEqual(size.ToString(), result.InstanceSize);
vmPowershellCmdlets.SetVMSize(a6VmName, a6ServiceName, new SetAzureVMSizeConfig(InstanceSize.A6));
result = vmPowershellCmdlets.GetAzureVM(a6VmName, a6ServiceName);
Assert.AreEqual(InstanceSize.A6.ToString(), result.InstanceSize);
Console.WriteLine("VM size, {0}, is verified for Set-AzureVMSize", size.ToString());
vmPowershellCmdlets.RemoveAzureVM(a6VmName, a6ServiceName);
}
}
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureVM, a6VmName, a6ServiceName))
{
vmPowershellCmdlets.RemoveAzureVM(a6VmName, a6ServiceName);
}
if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureService, a6ServiceName))
{
vmPowershellCmdlets.RemoveAzureService(a6ServiceName);
}
}
}
private bool CompareContext<T>(T obj1, T obj2)
{
bool result = true;
Type type = typeof(T);
foreach(PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
string typeName = property.PropertyType.FullName;
if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable"))
{
var obj1Value = property.GetValue(obj1, null);
var obj2Value = property.GetValue(obj2, null);
if (obj1Value == null)
{
result &= (obj2Value == null);
}
else
{
result &= (obj1Value.Equals(obj2Value));
}
}
else
{
Console.WriteLine("This type is not compared: {0}", typeName);
}
}
return result;
}
[TestCleanup]
public virtual void CleanUp()
{
Console.WriteLine("Test {0}", pass ? "passed" : "failed");
// Cleanup
if ((createOwnService && cleanupIfPassed && pass) || (createOwnService && cleanupIfFailed && !pass))
{
Console.WriteLine("Starting to clean up created VM and service.");
try
{
vmPowershellCmdlets.RemoveAzureVM(vmName, serviceName);
Console.WriteLine("VM, {0}, is deleted", vmName);
}
catch (Exception e)
{
Console.WriteLine("Error during removing VM: {0}", e.ToString());
}
try
{
vmPowershellCmdlets.RemoveAzureService(serviceName);
Console.WriteLine("Service, {0}, is deleted", serviceName);
}
catch (Exception e)
{
Console.WriteLine("Error during removing VM: {0}", e.ToString());
}
}
}
[ClassCleanup]
public static void ClassCleanUp()
{
try
{
vmPowershellCmdlets.RemoveAzureVM(defaultVm, defaultService);
Console.WriteLine("VM, {0}, is deleted", defaultVm);
}
catch (Exception e)
{
Console.WriteLine("Error during removing VM: {0}", e.ToString());
}
try
{
vmPowershellCmdlets.RemoveAzureService(defaultService);
Console.WriteLine("Service, {0}, is deleted", defaultService);
}
catch (Exception e)
{
Console.WriteLine("Error during removing VM: {0}", e.ToString());
}
}
private string CheckLocation(string loc)
{
string checkLoc = vmPowershellCmdlets.GetAzureLocationName(new string[] { loc });
if (string.IsNullOrEmpty(checkLoc))
{
foreach (LocationsContext l in vmPowershellCmdlets.GetAzureLocation())
{
if (l.AvailableServices.Contains("Storage"))
{
return l.Name;
}
}
return null;
}
else
{
return checkLoc;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Threading;
namespace System.Text
{
public abstract class DecoderFallback
{
private static DecoderFallback s_replacementFallback; // Default fallback, uses no best fit & "?"
private static DecoderFallback s_exceptionFallback;
public static DecoderFallback ReplacementFallback =>
s_replacementFallback ?? Interlocked.CompareExchange(ref s_replacementFallback, new DecoderReplacementFallback(), null) ?? s_replacementFallback;
public static DecoderFallback ExceptionFallback =>
s_exceptionFallback ?? Interlocked.CompareExchange<DecoderFallback>(ref s_exceptionFallback, new DecoderExceptionFallback(), null) ?? s_exceptionFallback;
// Fallback
//
// Return the appropriate unicode string alternative to the character that need to fall back.
// Most implementations will be:
// return new MyCustomDecoderFallbackBuffer(this);
public abstract DecoderFallbackBuffer CreateFallbackBuffer();
// Maximum number of characters that this instance of this fallback could return
public abstract int MaxCharCount { get; }
}
public abstract class DecoderFallbackBuffer
{
// Most implementations will probably need an implementation-specific constructor
// internal methods that cannot be overridden that let us do our fallback thing
// These wrap the internal methods so that we can check for people doing stuff that's incorrect
public abstract bool Fallback(byte[] bytesUnknown, int index);
// Get next character
public abstract char GetNextChar();
// Back up a character
public abstract bool MovePrevious();
// How many chars left in this fallback?
public abstract int Remaining { get; }
// Clear the buffer
public virtual void Reset()
{
while (GetNextChar() != (char)0) ;
}
// Internal items to help us figure out what we're doing as far as error messages, etc.
// These help us with our performance and messages internally
internal unsafe byte* byteStart;
internal unsafe char* charEnd;
internal Encoding _encoding;
internal DecoderNLS _decoder;
private int _originalByteCount;
// Internal Reset
internal unsafe void InternalReset()
{
byteStart = null;
Reset();
}
// Set the above values
// This can't be part of the constructor because DecoderFallbacks would have to know how to implement these.
internal unsafe void InternalInitialize(byte* byteStart, char* charEnd)
{
this.byteStart = byteStart;
this.charEnd = charEnd;
}
internal static DecoderFallbackBuffer CreateAndInitialize(Encoding encoding, DecoderNLS decoder, int originalByteCount)
{
// The original byte count is only used for keeping track of what 'index' value needs
// to be passed to the abstract Fallback method. The index value is calculated by subtracting
// 'bytes.Length' (where bytes is expected to be the entire remaining input buffer)
// from the 'originalByteCount' value specified here.
DecoderFallbackBuffer fallbackBuffer = (decoder is null) ? encoding.DecoderFallback.CreateFallbackBuffer() : decoder.FallbackBuffer;
fallbackBuffer._encoding = encoding;
fallbackBuffer._decoder = decoder;
fallbackBuffer._originalByteCount = originalByteCount;
return fallbackBuffer;
}
// Fallback the current byte by sticking it into the remaining char buffer.
// This can only be called by our encodings (other have to use the public fallback methods), so
// we can use our DecoderNLS here too (except we don't).
// Returns true if we are successful, false if we can't fallback the character (no buffer space)
// So caller needs to throw buffer space if return false.
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
// Don't touch ref chars unless we succeed
internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars)
{
Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
// See if there's a fallback character and we have an output buffer then copy our string.
if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
{
// Copy the chars to our output
char ch;
char* charTemp = chars;
bool bHighSurrogate = false;
while ((ch = GetNextChar()) != 0)
{
// Make sure no mixed up surrogates
if (char.IsSurrogate(ch))
{
if (char.IsHighSurrogate(ch))
{
// High Surrogate
if (bHighSurrogate)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = true;
}
else
{
// Low surrogate
if (bHighSurrogate == false)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = false;
}
}
if (charTemp >= charEnd)
{
// No buffer space
return false;
}
*(charTemp++) = ch;
}
// Need to make sure that bHighSurrogate isn't true
if (bHighSurrogate)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
// Now we aren't going to be false, so its OK to update chars
chars = charTemp;
}
return true;
}
// This version just counts the fallback and doesn't actually copy anything.
internal unsafe virtual int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
// See if there's a fallback character and we have an output buffer then copy our string.
if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
{
int count = 0;
char ch;
bool bHighSurrogate = false;
while ((ch = GetNextChar()) != 0)
{
// Make sure no mixed up surrogates
if (char.IsSurrogate(ch))
{
if (char.IsHighSurrogate(ch))
{
// High Surrogate
if (bHighSurrogate)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = true;
}
else
{
// Low surrogate
if (bHighSurrogate == false)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = false;
}
}
count++;
}
// Need to make sure that bHighSurrogate isn't true
if (bHighSurrogate)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
return count;
}
// If no fallback return 0
return 0;
}
internal int InternalFallbackGetCharCount(ReadOnlySpan<byte> remainingBytes, int fallbackLength)
{
return (Fallback(remainingBytes.Slice(0, fallbackLength).ToArray(), index: _originalByteCount - remainingBytes.Length))
? DrainRemainingDataForGetCharCount()
: 0;
}
internal bool TryInternalFallbackGetChars(ReadOnlySpan<byte> remainingBytes, int fallbackLength, Span<char> chars, out int charsWritten)
{
if (Fallback(remainingBytes.Slice(0, fallbackLength).ToArray(), index: _originalByteCount - remainingBytes.Length))
{
return TryDrainRemainingDataForGetChars(chars, out charsWritten);
}
else
{
// Return true because we weren't asked to write anything, so this is a "success" in the sense that
// the output buffer was large enough to hold the desired 0 chars of output.
charsWritten = 0;
return true;
}
}
private Rune GetNextRune()
{
// Call GetNextChar() and try treating it as a non-surrogate character.
// If that fails, call GetNextChar() again and attempt to treat the two chars
// as a surrogate pair. If that still fails, throw an exception since the fallback
// mechanism is giving us a bad replacement character.
Rune rune;
char ch = GetNextChar();
if (!Rune.TryCreate(ch, out rune) && !Rune.TryCreate(ch, GetNextChar(), out rune))
{
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
}
return rune;
}
internal int DrainRemainingDataForGetCharCount()
{
int totalCharCount = 0;
Rune thisRune;
while ((thisRune = GetNextRune()).Value != 0)
{
// We need to check for overflow while tallying the fallback char count.
totalCharCount += thisRune.Utf16SequenceLength;
if (totalCharCount < 0)
{
InternalReset();
Encoding.ThrowConversionOverflow();
}
}
return totalCharCount;
}
internal bool TryDrainRemainingDataForGetChars(Span<char> chars, out int charsWritten)
{
int originalCharCount = chars.Length;
Rune thisRune;
while ((thisRune = GetNextRune()).Value != 0)
{
if (thisRune.TryEncodeToUtf16(chars, out int charsWrittenJustNow))
{
chars = chars.Slice(charsWrittenJustNow);
continue;
}
else
{
InternalReset();
charsWritten = default;
return false;
}
}
charsWritten = originalCharCount - chars.Length;
return true;
}
// private helper methods
internal void ThrowLastBytesRecursive(byte[] bytesUnknown)
{
// Create a string representation of our bytes.
StringBuilder strBytes = new StringBuilder(bytesUnknown.Length * 3);
int i;
for (i = 0; i < bytesUnknown.Length && i < 20; i++)
{
if (strBytes.Length > 0)
strBytes.Append(' ');
strBytes.AppendFormat(CultureInfo.InvariantCulture, "\\x{0:X2}", bytesUnknown[i]);
}
// In case the string's really long
if (i == 20)
strBytes.Append(" ...");
// Throw it, using our complete bytes
throw new ArgumentException(
SR.Format(SR.Argument_RecursiveFallbackBytes,
strBytes.ToString()), nameof(bytesUnknown));
}
}
}
| |
// 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.IO.PortsTests;
using System.Text;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class SerialStream_Write_byte_int_int : PortsTest
{
// The string size used for large byte array testing
private const int LARGE_BUFFER_SIZE = 2048;
// When we test Write and do not care about actually writing anything we must still
// create an byte array to pass into the method the following is the size of the
// byte array used in this situation
private const int DEFAULT_BUFFER_SIZE = 1;
private const int DEFAULT_BUFFER_OFFSET = 0;
private const int DEFAULT_BUFFER_COUNT = 1;
// The maximum buffer size when a exception occurs
private const int MAX_BUFFER_SIZE_FOR_EXCEPTION = 255;
// The maximum buffer size when a exception is not expected
private const int MAX_BUFFER_SIZE = 8;
// The default number of times the write method is called when verifying write
private const int DEFAULT_NUM_WRITES = 3;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void Buffer_Null()
{
VerifyWriteException(null, 0, 1, typeof(ArgumentNullException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEG1()
{
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], -1, DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEGRND()
{
var rndGen = new Random(-55);
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], rndGen.Next(int.MinValue, 0), DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_MinInt()
{
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], int.MinValue, DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEG1()
{
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, -1, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEGRND()
{
var rndGen = new Random(-55);
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_MinInt()
{
VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, int.MinValue, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasNullModem))]
public void OffsetCount_EQ_Length_Plus_1()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION);
int offset = rndGen.Next(0, bufferLength);
int count = bufferLength + 1 - offset;
Type expectedException = typeof(ArgumentException);
VerifyWriteException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasNullModem))]
public void OffsetCount_GT_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION);
int offset = rndGen.Next(0, bufferLength);
int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyWriteException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasNullModem))]
public void Offset_GT_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION);
int offset = rndGen.Next(bufferLength, int.MaxValue);
int count = DEFAULT_BUFFER_COUNT;
Type expectedException = typeof(ArgumentException);
VerifyWriteException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasNullModem))]
public void Count_GT_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION);
int offset = DEFAULT_BUFFER_OFFSET;
int count = rndGen.Next(bufferLength + 1, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyWriteException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasNullModem))]
public void OffsetCount_EQ_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = rndGen.Next(0, bufferLength - 1);
int count = bufferLength - offset;
VerifyWrite(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasNullModem))]
public void Offset_EQ_Length_Minus_1()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = bufferLength - 1;
var count = 1;
VerifyWrite(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasNullModem))]
public void Count_EQ_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
var offset = 0;
int count = bufferLength;
VerifyWrite(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasNullModem))]
public void ASCIIEncoding()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyWrite(new byte[bufferLength], offset, count, new ASCIIEncoding());
}
[ConditionalFact(nameof(HasNullModem))]
public void UTF8Encoding()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyWrite(new byte[bufferLength], offset, count, new UTF8Encoding());
}
[ConditionalFact(nameof(HasNullModem))]
public void UTF32Encoding()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyWrite(new byte[bufferLength], offset, count, new UTF32Encoding());
}
[ConditionalFact(nameof(HasNullModem))]
public void UnicodeEncoding()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE);
int offset = rndGen.Next(0, bufferLength - 1);
int count = rndGen.Next(1, bufferLength - offset);
VerifyWrite(new byte[bufferLength], offset, count, new UnicodeEncoding());
}
[ConditionalFact(nameof(HasNullModem))]
public void LargeBuffer()
{
int bufferLength = LARGE_BUFFER_SIZE;
var offset = 0;
int count = bufferLength;
VerifyWrite(new byte[bufferLength], offset, count, 1);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void InBreak()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying Write throws InvalidOperationException while in a Break");
com1.Open();
com1.BreakState = true;
Assert.Throws<InvalidOperationException>(() => com1.BaseStream.Write(new byte[8], 0, 8));
}
}
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void Count_EQ_Zero()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying Write with count=0 returns immediately");
com1.Open();
com1.Handshake = Handshake.RequestToSend;
com1.BaseStream.Write(new byte[8], 0, 0);
}
}
#endregion
#region Verification for Test Cases
private void VerifyWriteException(byte[] buffer, int offset, int count, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int bufferLength = null == buffer ? 0 : buffer.Length;
Debug.WriteLine("Verifying write method throws {0} buffer.Lenght={1}, offset={2}, count={3}",
expectedException, bufferLength, offset, count);
com.Open();
Assert.Throws(expectedException, () => com.BaseStream.Write(buffer, offset, count));
}
}
private void VerifyWrite(byte[] buffer, int offset, int count)
{
VerifyWrite(buffer, offset, count, new ASCIIEncoding());
}
private void VerifyWrite(byte[] buffer, int offset, int count, int numWrites)
{
VerifyWrite(buffer, offset, count, new ASCIIEncoding(), numWrites);
}
private void VerifyWrite(byte[] buffer, int offset, int count, Encoding encoding)
{
VerifyWrite(buffer, offset, count, encoding, DEFAULT_NUM_WRITES);
}
private void VerifyWrite(byte[] buffer, int offset, int count, Encoding encoding, int numWrites)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
Debug.WriteLine("Verifying write method buffer.Lenght={0}, offset={1}, count={2}, endocing={3}",
buffer.Length, offset, count, encoding.EncodingName);
com1.Encoding = encoding;
com2.Encoding = encoding;
com1.Open();
com2.Open();
for (var i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)rndGen.Next(0, 256);
}
VerifyWriteByteArray(buffer, offset, count, com1, com2, numWrites);
}
}
private void VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPort com1, SerialPort com2, int numWrites)
{
var index = 0;
var oldBuffer = (byte[])buffer.Clone();
var expectedBytes = new byte[count];
var actualBytes = new byte[expectedBytes.Length * numWrites];
for (var i = 0; i < count; i++)
{
expectedBytes[i] = buffer[i + offset];
}
for (var i = 0; i < numWrites; i++)
{
com1.BaseStream.Write(buffer, offset, count);
}
com2.ReadTimeout = 500;
Thread.Sleep((int)(((expectedBytes.Length * numWrites * 10.0) / com1.BaudRate) * 1000) + 250);
// Make sure buffer was not altered during the write call
for (var i = 0; i < buffer.Length; i++)
{
if (buffer[i] != oldBuffer[i])
{
Fail("ERROR!!!: The contents of the buffer were changed from {0} to {1} at {2}", oldBuffer[i], buffer[i], i);
}
}
while (true)
{
int byteRead;
try
{
byteRead = com2.ReadByte();
}
catch (TimeoutException)
{
break;
}
if (actualBytes.Length <= index)
{
// If we have read in more bytes then we expect
Fail("ERROR!!!: We have received more bytes then were sent");
break;
}
actualBytes[index] = (byte)byteRead;
index++;
if (actualBytes.Length - index != com2.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead);
}
}
// Compare the bytes that were read with the ones we expected to read
for (var j = 0; j < numWrites; j++)
{
for (var i = 0; i < expectedBytes.Length; i++)
{
if (expectedBytes[i] != actualBytes[i + expectedBytes.Length * j])
{
Fail("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], (int)actualBytes[i + expectedBytes.Length * j], i);
}
}
}
if (com1.IsOpen)
com1.Close();
if (com2.IsOpen)
com2.Close();
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace IronAHK.Rusty
{
partial class Core
{
/// <summary>
/// Returns the Unicode value (an integer between 1 and 65535) for the specified character in a string.
/// </summary>
/// <param name="str">A string.</param>
/// <param name="n">The zero-based character position in the string.
/// If this is blank it is assumed to be <c>0</c>.</param>
/// <returns>The Unicode value.
/// If <paramref name="str"/> is empty or <paramref name="n"/> is specified out of bounds, <c>0</c> is returned.</returns>
public static int Asc(string str, int n = 0)
{
return string.IsNullOrEmpty(str) || n < 0 || n > str.Length ? 0 : (int)str[n];
}
/// <summary>
/// Encodes binary data to a base 64 character string.
/// </summary>
/// <param name="value">The data to encode.</param>
/// <returns>A base 64 string representation of the given binary data.</returns>
public static string Base64Encode(object value)
{
return Convert.ToBase64String(ToByteArray(value));
}
/// <summary>
/// Decodes a base 64 character string to binary data.
/// </summary>
/// <param name="s">The base 64 string to decode.</param>
/// <returns>A binary byte array of the given sequence.</returns>
public static byte[] Base64Decode(string s)
{
return Convert.FromBase64String(s);
}
/// <summary>
/// Returns the single character corresponding to a Unicode value.
/// </summary>
/// <param name="n">A Unicode value.</param>
/// <returns>A Unicode character whose value is <paramref name="n"/>.</returns>
public static string Chr(int n)
{
return ((char)n).ToString();
}
/// <summary>
/// Transforms a YYYYMMDDHH24MISS timestamp into the specified date/time format.
/// </summary>
/// <param name="output">The variable to store the result.</param>
/// <param name="stamp">Leave this parameter blank to use the current local date and time.
/// Otherwise, specify all or the leading part of a timestamp in the YYYYMMDDHH24MISS format.</param>
/// <param name="format">
/// <para>If omitted, it defaults to the time followed by the long date,
/// both of which will be formatted according to the current user's locale.</para>
/// <para>Otherwise, specify one or more of the date-time formats,
/// along with any literal spaces and punctuation in between.</para>
/// </param>
public static void FormatTime(out string output, string stamp, string format)
{
DateTime time;
if (stamp.Length == 0)
time = DateTime.Now;
else
{
try
{
time = ToDateTime(stamp);
}
catch (ArgumentOutOfRangeException)
{
output = null;
return;
}
}
switch (format.ToLowerInvariant())
{
case Keyword_Time:
format = "t";
break;
case Keyword_ShortDate:
format = "d";
break;
case Keyword_LongDate:
format = "D";
break;
case Keyword_YearMonth:
format = "Y";
break;
case Keyword_YDay:
output = time.DayOfYear.ToString();
return;
case Keyword_YDay0:
output = time.DayOfYear.ToString().PadLeft(3, '0');
return;
case Keyword_WDay:
output = time.DayOfWeek.ToString();
return;
case Keyword_YWeek:
{
int week = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
output = time.ToString("Y") + week;
return;
}
default:
if (format.Length == 0)
format = "f";
break;
}
try
{
output = time.ToString(format);
}
catch (FormatException)
{
output = null;
}
}
/// <summary>
/// Encodes binary data to a hexadecimal string.
/// </summary>
/// <param name="value">The data to encode.</param>
/// <returns>A hexadecimal string representation of the given binary data.</returns>
public static string HexEncode(object value)
{
return ToString(ToByteArray(value));
}
/// <summary>
/// Decodes a hexadecimal string to binary data.
/// </summary>
/// <param name="hex">The hexadecimal string to decode.</param>
/// <returns>A binary byte array of the given sequence.</returns>
public static byte[] HexDecode(string hex)
{
var binary = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
var n = new string(new[] { hex[i], hex[i + 1] });
binary[i / 2] = byte.Parse(n, NumberStyles.AllowHexSpecifier);
}
return binary;
}
/// <summary>
/// Returns the position of the first or last occurrence of the specified substring within a string.
/// </summary>
/// <param name="input">The string to check.</param>
/// <param name="needle">The substring to search for.</param>
/// <param name="caseSensitive"><c>true</c> to use a case sensitive comparison, <c>false</c> otherwise.</param>
/// <param name="index">The one-based starting character position.
/// Specify zero or leave blank to search in reverse, i.e. right to left.</param>
/// <returns>The one-based index of the position of <paramref name="needle"/> in <paramref name="input"/>.
/// A value of zero indicates no match.</returns>
public static int InStr(string input, string needle, bool caseSensitive = false, int index = 1)
{
var compare = caseSensitive ? StringComparison.Ordinal : A_StringComparison;
const int offset = 1;
if (index == 0)
return offset + input.LastIndexOf(needle, compare);
if (index < 0 || index > input.Length)
return 0;
return offset + input.IndexOf(needle, index - 1, compare);
}
/// <summary>
/// Determines whether a string contains a pattern (regular expression).
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="needle">The pattern to search for, which is a regular expression.</param>
/// <param name="output">The variable to store the result.</param>
/// <param name="index">The one-based starting character position.
/// If this is less than one it is considered an offset from the end of the string.</param>
/// <returns>The one-based index of the position of the first match.
/// A value of zero indicates no match.</returns>
public static int RegExMatch(string input, string needle, out string[] output, int index)
{
Regex exp;
bool reverse = index < 1;
try { exp = ParseRegEx(needle, reverse); }
catch (ArgumentException)
{
output = new string[] { };
ErrorLevel = 2;
return 0;
}
if (index < 0)
{
int l = input.Length - 1;
input = input.Substring(0, Math.Min(l, l + index));
index = 0;
}
index = Math.Max(0, index - 1);
Match res = exp.Match(input, index);
var matches = new string[res.Groups.Count];
for (int i = 0; i < res.Groups.Count; i++)
matches[i] = res.Groups[i].Value;
output = matches;
return matches.Length == 0 ? 0 : res.Groups[0].Index + 1;
}
/// <summary>
/// Replaces occurrences of a pattern (regular expression) inside a string.
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="needle">The pattern to search for, which is a regular expression.</param>
/// <param name="replace">The string to replace <paramref name="needle"/>.</param>
/// <param name="count">The variable to store the number of replacements that occurred.</param>
/// <param name="limit">The maximum number of replacements to perform.
/// If this is below one all matches will be replaced.</param>
/// <param name="index">The one-based starting character position.
/// If this is less than one it is considered an offset from the end of the string.</param>
/// <returns>The new string.</returns>
public static string RegExReplace(string input, string needle, string replace, out int count, int limit = -1, int index = 1)
{
Regex exp;
try
{
exp = ParseRegEx(needle, index < 1);
}
catch (ArgumentException)
{
count = 0;
ErrorLevel = 2;
return null;
}
if (limit < 1)
limit = int.MaxValue;
if (index < 1)
index = input.Length + index - 1;
index = Math.Min(Math.Max(0, index), input.Length);
var n = 0;
MatchEvaluator match = delegate(Match hit)
{
n++;
return replace;
};
count = n;
var result = exp.Replace(input, match, limit, index);
return result;
}
/// <summary>
/// Arranges a variable's contents in alphabetical, numerical, or random order optionally removing duplicates.
/// </summary>
/// <param name="input">The variable whose contents to use as the input.</param>
/// <param name="options">See the remarks.</param>
/// <remarks>
/// <list type="table">
/// <listheader>
/// <term>Name</term>
/// <description>Description</description>
/// </listheader>
/// <item>
/// <term>C</term>
/// <description>Case sensitive.</description>
/// </item>
/// <item>
/// <term>CL</term>
/// <description>Case sensitive based on current user's locale.</description>
/// </item>
/// <item>
/// <term>D<c>x</c></term>
/// <description>Specifies <c>x</c> as the delimiter character which is <c>`n</c> by default.</description>
/// </item>
/// <item>
/// <term>F <c>name</c></term>
/// <description>Use the return value of the specified function for comparing two items.</description>
/// </item>
/// <item>
/// <term>N</term>
/// <description>Numeric sorting.</description>
/// </item>
/// <item>
/// <term>P<c>n</c></term>
/// <description>Sorts items based on character position <c>n</c>.</description>
/// </item>
/// <item>
/// <term>R</term>
/// <description>Sort in reverse order.</description>
/// </item>
/// <item>
/// <term>Random</term>
/// <description>Sort in random order.</description>
/// </item>
/// <item>
/// <term>U</term>
/// <description>Remove any duplicate items.</description>
/// </item>
/// <item>
/// <term>Z</term>
/// <description>Considers a trailing delimiter as a boundary which otherwise would be ignored.</description>
/// </item>
/// <item>
/// <term>\</term>
/// <description>File path sorting.</description>
/// </item>
/// </list>
/// </remarks>
public static void Sort(ref string input, params string[] options)
{
var opts = KeyValues(string.Join(",", options), true, new[] { 'f' });
MethodInfo function = null;
if (opts.ContainsKey('f'))
{
function = FindLocalRoutine(opts['f']);
if (function == null)
return;
}
char split = '\n';
if (opts.ContainsKey('d'))
{
string s = opts['d'];
if (s.Length == 1)
split = s[0];
opts.Remove('d');
}
string[] list = input.Split(new[] { split }, StringSplitOptions.RemoveEmptyEntries);
if (split == '\n')
{
for (int i = 0; i < list.Length; i++)
{
int x = list[i].Length - 1;
if (list[i][x] == '\r')
list[i] = list[i].Substring(0, x);
}
}
if (opts.ContainsKey('z') && input[input.Length - 1] == split)
{
Array.Resize(ref list, list.Length + 1);
list[list.Length - 1] = string.Empty;
opts.Remove('z');
}
bool withcase = false;
if (opts.ContainsKey('c'))
{
string mode = opts['c'];
if (mode == "l" || mode == "L")
withcase = false;
else
withcase = true;
opts.Remove('c');
}
bool numeric = false;
if (opts.ContainsKey('n'))
{
numeric = true;
opts.Remove('n');
}
int sortAt = 1;
if (opts.ContainsKey('p'))
{
if (!int.TryParse(opts['p'], out sortAt))
sortAt = 1;
opts.Remove('p');
}
bool reverse = false, random = false;
if (opts.ContainsKey(Keyword_Random[0]))
{
if (opts[Keyword_Random[0]].Equals(Keyword_Random.Substring(1), StringComparison.OrdinalIgnoreCase)) // Random
random = true;
else
reverse = true;
opts.Remove(Keyword_Random[0]);
}
bool unique = false;
if (opts.ContainsKey('u'))
{
unique = true;
opts.Remove('u');
}
bool slash = false;
if (opts.ContainsKey('\\'))
{
slash = true;
opts.Remove('\\');
}
var comp = new CaseInsensitiveComparer();
var rand = new Random();
Array.Sort(list, delegate(string x, string y)
{
if (function != null)
{
object value = null;
try { value = function.Invoke(null, new object[] { new object[] { x, y } }); }
catch (Exception) { }
int result;
if (value is string && int.TryParse((string)value, out result))
return result;
return 0;
}
else if (x == y)
return 0;
else if (random)
return rand.Next(-1, 2);
else if (numeric)
{
int a, b;
return int.TryParse(x, out a) && int.TryParse(y, out b) ?
a.CompareTo(b) : x.CompareTo(y);
}
else
{
if (slash)
{
int z = x.LastIndexOf('\\');
if (z != -1)
x = x.Substring(z + 1);
z = y.LastIndexOf('\\');
if (z != -1)
y = y.Substring(z + 1);
if (x == y)
return 0;
}
return withcase ? x.CompareTo(y) : comp.Compare(x, y);
}
});
if (unique)
{
int error = 0;
var ulist = new List<string>(list.Length);
foreach (var item in list)
if (!ulist.Contains(item))
ulist.Add(item);
else
error++;
ErrorLevel = error;
list = ulist.ToArray();
}
if (reverse)
Array.Reverse(list);
input = string.Join(split.ToString(), list);
}
/// <summary>
/// Returns the length of a string.
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>The total length of the string, including any invisbile characters such as null.</returns>
public static int StrLen(string input)
{
return input.Length;
}
/// <summary>
/// Converts a string to lowercase.
/// </summary>
/// <param name="output">The variable to store the result.</param>
/// <param name="input">The variable whose contents to use as the input.</param>
/// <param name="title"><c>true</c> to use title casing, <c>false</c> otherwise.</param>
public static void StringLower(out string output, ref string input, bool title)
{
output = title ? CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input) : input.ToLowerInvariant();
}
/// <summary>
/// Replaces the specified substring with a new string.
/// </summary>
/// <param name="output">The variable to store the result.</param>
/// <param name="input">The variable whose contents to use as the input.</param>
/// <param name="search">The substring to search for.</param>
/// <param name="replace">The string to replace <paramref name="search"/>.</param>
/// <param name="all"><c>true</c> to replace all instances, <c>false</c> otherwise.</param>
/// <remarks>If <paramref name="all"/> is true and <see cref="A_StringCaseSense"/> is on a faster replacement algorithm is used.</remarks>
public static void StringReplace(out string output, ref string input, string search, string replace, bool all)
{
if (IsAnyBlank(input, search, replace))
{
output = string.Empty;
return;
}
var compare = _StringComparison ?? StringComparison.OrdinalIgnoreCase;
if (all && compare == StringComparison.Ordinal)
output = input.Replace(search, replace);
else
{
var buf = new StringBuilder(input.Length);
int z = 0, n = 0, l = search.Length;
while (z < input.Length && (z = input.IndexOf(search, z, compare)) != -1)
{
if (n < z)
buf.Append(input, n, z - n);
buf.Append(replace);
z += l;
n = z;
}
if (n < input.Length)
buf.Append(input, n, input.Length - n);
output = buf.ToString();
}
}
/// <summary>
/// Separates a string into an array of substrings using the specified delimiters.
/// </summary>
/// <param name="output">The variable to store the result.</param>
/// <param name="input">The variable whose contents to use as the input.</param>
/// <param name="delimiters">One or more characters (case sensitive), each of which is used to determine
/// where the boundaries between substrings occur in <paramref name="input"/>.
/// If this is blank each character of <paramref name="input"/> will be treated as a substring.</param>
/// <param name="trim">An optional list of characters (case sensitive) to exclude from the beginning and end of each array element.</param>
public static void StringSplit(out string[] output, ref string input, string delimiters, string trim)
{
if (delimiters.Length == 0)
{
var list = new List<string>(input.Length);
foreach (var letter in input)
if (trim.IndexOf(letter) == -1)
list.Add(letter.ToString());
output = list.ToArray();
return;
}
output = input.Split(delimiters.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (trim.Length != 0)
{
char[] omit = trim.ToCharArray();
for (int i = 0; i < output.Length; i++)
output[i] = output[i].Trim(omit);
}
}
/// <summary>
/// Converts a string to uppercase.
/// </summary>
/// <param name="output">The variable to store the result.</param>
/// <param name="input">The variable whose contents to use as the input.</param>
/// <param name="title"><c>true</c> to use title casing, <c>false</c> otherwise.</param>
public static void StringUpper(out string output, ref string input, bool title)
{
output = title ? CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input) : input.ToUpperInvariant();
}
/// <summary>
/// Retrieves one or more characters from the specified position in a string.
/// </summary>
/// <param name="input">The string to use.</param>
/// <param name="index">The one-based starting character position.
/// If this is less than one it is considered an offset from the end of the string.</param>
/// <param name="length">The maximum number of characters to retrieve.
/// Leave this parameter blank to return the entire leading part of the string.
/// Specify a negative value to omit that many characters from the end of the string.</param>
/// <returns>The new substring.</returns>
public static string SubStr(string input, int index, int length = int.MaxValue)
{
if (string.IsNullOrEmpty(input) || length == 0)
return string.Empty;
if (index < 1)
index += input.Length;
index--;
if (index < 0 || index >= input.Length)
return string.Empty;
int d = input.Length - index;
if (length < 0)
length += d;
length = Math.Min(length, d);
return input.Substring(index, length);
}
/// <summary>
/// Performs miscellaneous math functions, bitwise operations, and tasks such as ASCII to Unicode conversion.
/// This function is obsolete, please use the related newer syntax.
/// <seealso cref="Asc"/>
/// <seealso cref="Chr"/>
/// <seealso cref="Mod"/>
/// <seealso cref="Exp"/>
/// <seealso cref="Sqrt"/>
/// <seealso cref="Log"/>
/// <seealso cref="Ln"/>
/// <seealso cref="Round"/>
/// <seealso cref="Ceil"/>
/// <seealso cref="Floor"/>
/// <seealso cref="Abs"/>
/// <seealso cref="Sin"/>
/// <seealso cref="Cos"/>
/// <seealso cref="Tan"/>
/// <seealso cref="ASin"/>
/// <seealso cref="ACos"/>
/// <seealso cref="ATan"/>
/// <seealso cref="Floor"/>
/// <seealso cref="Floor"/>
/// </summary>
[Obsolete]
public static void Transform(ref string OutputVar, string Cmd, string Value1, string Value2)
{
OutputVar = string.Empty;
switch (Cmd.Trim().ToLowerInvariant())
{
case Keyword_Unicode:
if (Value1 == null)
OutputVar = Clipboard.GetText();
else OutputVar = Value1;
break;
case Keyword_Asc:
OutputVar = char.GetNumericValue(Value1, 0).ToString();
break;
case Keyword_Chr:
OutputVar = char.ConvertFromUtf32(int.Parse(Value1));
break;
case Keyword_Deref:
// TODO: dereference transform
break;
case "html":
OutputVar = Value1
.Replace("\"", """)
.Replace("&", "&")
.Replace("<", "<")
.Replace(">", ">")
.Replace("\n", "<br/>\n");
break;
case Keyword_Mod:
OutputVar = (double.Parse(Value1) % double.Parse(Value2)).ToString();
break;
case Keyword_Pow:
OutputVar = Math.Pow(double.Parse(Value1), double.Parse(Value2)).ToString();
break;
case Keyword_Exp:
OutputVar = Math.Pow(double.Parse(Value1), Math.E).ToString();
break;
case Keyword_Sqrt:
OutputVar = Math.Sqrt(double.Parse(Value1)).ToString();
break;
case Keyword_Log:
OutputVar = Math.Log10(double.Parse(Value1)).ToString();
break;
case Keyword_Ln:
OutputVar = Math.Log(double.Parse(Value1), Math.E).ToString();
break;
case Keyword_Round:
int p = int.Parse(Value2);
OutputVar = Math.Round(double.Parse(Value1), p == 0 ? 1 : p).ToString();
break;
case Keyword_Ceil:
OutputVar = Math.Ceiling(double.Parse(Value1)).ToString();
break;
case Keyword_Floor:
OutputVar = Math.Floor(double.Parse(Value1)).ToString();
break;
case Keyword_Abs:
double d = double.Parse(Value1);
OutputVar = (d < 0 ? d * -1 : d).ToString();
break;
case Keyword_Sin:
OutputVar = Math.Sin(double.Parse(Value1)).ToString();
break;
case Keyword_Cos:
OutputVar = Math.Cos(double.Parse(Value1)).ToString();
break;
case Keyword_Tan:
OutputVar = Math.Tan(double.Parse(Value1)).ToString();
break;
case Keyword_Asin:
OutputVar = Math.Asin(double.Parse(Value1)).ToString();
break;
case Keyword_Acos:
OutputVar = Math.Acos(double.Parse(Value1)).ToString();
break;
case Keyword_Atan:
OutputVar = Math.Atan(double.Parse(Value1)).ToString();
break;
case Keyword_BitNot:
OutputVar = (~int.Parse(Value1)).ToString();
break;
case Keyword_BitAnd:
OutputVar = (int.Parse(Value1) & int.Parse(Value2)).ToString();
break;
case Keyword_BitOr:
OutputVar = (int.Parse(Value1) | int.Parse(Value2)).ToString();
break;
case Keyword_BitXor:
OutputVar = (int.Parse(Value1) ^ int.Parse(Value2)).ToString();
break;
case Keyword_BitShiftLeft:
OutputVar = (int.Parse(Value1) << int.Parse(Value2)).ToString();
break;
case Keyword_BitShiftRight:
OutputVar = (int.Parse(Value1) >> int.Parse(Value2)).ToString();
break;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// This is where we group together all the internal calls.
//
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Internal.Runtime;
namespace System.Runtime
{
internal enum DispatchCellType
{
InterfaceAndSlot = 0x0,
MetadataToken = 0x1,
VTableOffset = 0x2,
}
internal struct DispatchCellInfo
{
public DispatchCellType CellType;
public EETypePtr InterfaceType;
public ushort InterfaceSlot;
public byte HasCache;
public uint MetadataToken;
public uint VTableOffset;
}
// Constants used with RhpGetClasslibFunction, to indicate which classlib function
// we are interested in.
// Note: make sure you change the def in ICodeManager.h if you change this!
internal enum ClassLibFunctionId
{
GetRuntimeException = 0,
FailFast = 1,
// UnhandledExceptionHandler = 2, // unused
AppendExceptionStackFrame = 3,
CheckStaticClassConstruction = 4,
GetSystemArrayEEType = 5,
OnFirstChance = 6,
DebugFuncEvalHelper = 7,
DebugFuncEvalAbortHelper = 8,
}
internal static class InternalCalls
{
//
// internalcalls for System.GC.
//
// Force a garbage collection.
[RuntimeExport("RhCollect")]
internal static void RhCollect(int generation, InternalGCCollectionMode mode)
{
RhpCollect(generation, mode);
}
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
private static extern void RhpCollect(int generation, InternalGCCollectionMode mode);
[RuntimeExport("RhGetGcTotalMemory")]
internal static long RhGetGcTotalMemory()
{
return RhpGetGcTotalMemory();
}
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
private static extern long RhpGetGcTotalMemory();
[RuntimeExport("RhStartNoGCRegion")]
internal static int RhStartNoGCRegion(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
{
return RhpStartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC);
}
[RuntimeExport("RhEndNoGCRegion")]
internal static int RhEndNoGCRegion()
{
return RhpEndNoGCRegion();
}
//
// internalcalls for System.Runtime.__Finalizer.
//
// Fetch next object which needs finalization or return null if we've reached the end of the list.
[RuntimeImport(Redhawk.BaseName, "RhpGetNextFinalizableObject")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern object RhpGetNextFinalizableObject();
//
// internalcalls for System.Runtime.InteropServices.GCHandle.
//
// Allocate handle.
[RuntimeImport(Redhawk.BaseName, "RhpHandleAlloc")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern IntPtr RhpHandleAlloc(object value, GCHandleType type);
// Allocate dependent handle.
[RuntimeImport(Redhawk.BaseName, "RhpHandleAllocDependent")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern IntPtr RhpHandleAllocDependent(object primary, object secondary);
// Allocate variable handle.
[RuntimeImport(Redhawk.BaseName, "RhpHandleAllocVariable")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern IntPtr RhpHandleAllocVariable(object value, uint type);
[RuntimeImport(Redhawk.BaseName, "RhHandleGet")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern object RhHandleGet(IntPtr handle);
[RuntimeImport(Redhawk.BaseName, "RhHandleSet")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern IntPtr RhHandleSet(IntPtr handle, object value);
//
// internal calls for allocation
//
[RuntimeImport(Redhawk.BaseName, "RhpNewFast")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewFast(EEType* pEEType); // BEWARE: not for finalizable objects!
[RuntimeImport(Redhawk.BaseName, "RhpNewFinalizable")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewFinalizable(EEType* pEEType);
[RuntimeImport(Redhawk.BaseName, "RhpNewArray")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewArray(EEType* pEEType, int length);
#if FEATURE_64BIT_ALIGNMENT
[RuntimeImport(Redhawk.BaseName, "RhpNewFastAlign8")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewFastAlign8(EEType * pEEType); // BEWARE: not for finalizable objects!
[RuntimeImport(Redhawk.BaseName, "RhpNewFinalizableAlign8")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewFinalizableAlign8(EEType* pEEType);
[RuntimeImport(Redhawk.BaseName, "RhpNewArrayAlign8")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewArrayAlign8(EEType* pEEType, int length);
[RuntimeImport(Redhawk.BaseName, "RhpNewFastMisalign")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe object RhpNewFastMisalign(EEType * pEEType);
#endif // FEATURE_64BIT_ALIGNMENT
[RuntimeImport(Redhawk.BaseName, "RhpBox")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe void RhpBox(object obj, ref byte data);
[RuntimeImport(Redhawk.BaseName, "RhUnbox")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Sometimes)]
internal extern static unsafe void RhUnbox(object obj, ref byte data, EEType* pUnboxToEEType);
[RuntimeImport(Redhawk.BaseName, "RhpCopyObjectContents")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpCopyObjectContents(object objDest, object objSrc);
[RuntimeImport(Redhawk.BaseName, "RhpCompareObjectContents")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static bool RhpCompareObjectContentsAndPadding(object obj1, object obj2);
[RuntimeImport(Redhawk.BaseName, "RhpAssignRef")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpAssignRef(ref object address, object obj);
#if FEATURE_GC_STRESS
//
// internal calls for GC stress
//
[RuntimeImport(Redhawk.BaseName, "RhpInitializeGcStress")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpInitializeGcStress();
#endif // FEATURE_GC_STRESS
[RuntimeImport(Redhawk.BaseName, "RhpEHEnumInitFromStackFrameIterator")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe bool RhpEHEnumInitFromStackFrameIterator(ref StackFrameIterator pFrameIter, byte** pMethodStartAddress, void* pEHEnum);
[RuntimeImport(Redhawk.BaseName, "RhpEHEnumNext")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe bool RhpEHEnumNext(void* pEHEnum, void* pEHClause);
[RuntimeImport(Redhawk.BaseName, "RhpGetArrayBaseType")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe EEType* RhpGetArrayBaseType(EEType* pEEType);
[RuntimeImport(Redhawk.BaseName, "RhpHasDispatchMap")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe bool RhpHasDispatchMap(EEType* pEETypen);
[RuntimeImport(Redhawk.BaseName, "RhpGetDispatchMap")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe DispatchResolve.DispatchMap* RhpGetDispatchMap(EEType* pEEType);
[RuntimeImport(Redhawk.BaseName, "RhpGetSealedVirtualSlot")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpGetSealedVirtualSlot(EEType* pEEType, ushort slot);
[RuntimeImport(Redhawk.BaseName, "RhpGetDispatchCellInfo")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpGetDispatchCellInfo(IntPtr pCell, out DispatchCellInfo newCellInfo);
[RuntimeImport(Redhawk.BaseName, "RhpSearchDispatchCellCache")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpSearchDispatchCellCache(IntPtr pCell, EEType* pInstanceType);
[RuntimeImport(Redhawk.BaseName, "RhpUpdateDispatchCellCache")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpUpdateDispatchCellCache(IntPtr pCell, IntPtr pTargetCode, EEType* pInstanceType, ref DispatchCellInfo newCellInfo);
[RuntimeImport(Redhawk.BaseName, "RhpGetClasslibFunctionFromCodeAddress")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void* RhpGetClasslibFunctionFromCodeAddress(IntPtr address, ClassLibFunctionId id);
[RuntimeImport(Redhawk.BaseName, "RhpGetClasslibFunctionFromEEType")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void* RhpGetClasslibFunctionFromEEType(IntPtr pEEType, ClassLibFunctionId id);
//
// StackFrameIterator
//
[RuntimeImport(Redhawk.BaseName, "RhpSfiInit")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern unsafe bool RhpSfiInit(ref StackFrameIterator pThis, void* pStackwalkCtx, bool instructionFault);
[RuntimeImport(Redhawk.BaseName, "RhpSfiNext")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern bool RhpSfiNext(ref StackFrameIterator pThis, out uint uExCollideClauseIdx, out bool fUnwoundReversePInvoke);
//
// DebugEventSource
//
[RuntimeImport(Redhawk.BaseName, "RhpGetRequestedExceptionEvents")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal static extern ExceptionEventKind RhpGetRequestedExceptionEvents();
[DllImport(Redhawk.BaseName)]
internal static extern unsafe void RhpSendExceptionEventToDebugger(ExceptionEventKind eventKind, byte* ip, UIntPtr sp);
//
// Miscellaneous helpers.
//
// Get the rarely used (optional) flags of an EEType. If they're not present 0 will be returned.
[RuntimeImport(Redhawk.BaseName, "RhpGetEETypeRareFlags")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe uint RhpGetEETypeRareFlags(EEType* pEEType);
// Retrieve the offset of the value embedded in a Nullable<T>.
[RuntimeImport(Redhawk.BaseName, "RhpGetNullableEETypeValueOffset")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe byte RhpGetNullableEETypeValueOffset(EEType* pEEType);
// Retrieve the target type T in a Nullable<T>.
[RuntimeImport(Redhawk.BaseName, "RhpGetNullableEEType")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe EEType* RhpGetNullableEEType(EEType* pEEType);
// For an ICastable type return a pointer to code that implements ICastable.IsInstanceOfInterface.
[RuntimeImport(Redhawk.BaseName, "RhpGetICastableIsInstanceOfInterfaceMethod")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpGetICastableIsInstanceOfInterfaceMethod(EEType* pEEType);
// For an ICastable type return a pointer to code that implements ICastable.GetImplType.
[RuntimeImport(Redhawk.BaseName, "RhpGetICastableGetImplTypeMethod")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpGetICastableGetImplTypeMethod(EEType* pEEType);
[RuntimeImport(Redhawk.BaseName, "RhpGetNextFinalizerInitCallback")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpGetNextFinalizerInitCallback();
[RuntimeImport(Redhawk.BaseName, "RhpCallCatchFunclet")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe IntPtr RhpCallCatchFunclet(
object exceptionObj, byte* pHandlerIP, void* pvRegDisplay, ref EH.ExInfo exInfo);
[RuntimeImport(Redhawk.BaseName, "RhpCallFinallyFunclet")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpCallFinallyFunclet(byte* pHandlerIP, void* pvRegDisplay);
[RuntimeImport(Redhawk.BaseName, "RhpCallFilterFunclet")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe bool RhpCallFilterFunclet(
object exceptionObj, byte* pFilterIP, void* pvRegDisplay);
[RuntimeImport(Redhawk.BaseName, "RhpFallbackFailFast")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpFallbackFailFast();
[RuntimeImport(Redhawk.BaseName, "RhpSetThreadDoNotTriggerGC")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static void RhpSetThreadDoNotTriggerGC();
[System.Diagnostics.Conditional("DEBUG")]
[RuntimeImport(Redhawk.BaseName, "RhpValidateExInfoStack")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static void RhpValidateExInfoStack();
[RuntimeImport(Redhawk.BaseName, "RhpCopyContextFromExInfo")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpCopyContextFromExInfo(void* pOSContext, int cbOSContext, EH.PAL_LIMITED_CONTEXT* pPalContext);
[RuntimeImport(Redhawk.BaseName, "RhpGetCastableObjectDispatchHelper")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetCastableObjectDispatchHelper();
[RuntimeImport(Redhawk.BaseName, "RhpGetCastableObjectDispatchHelper_TailCalled")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetCastableObjectDispatchHelper_TailCalled();
[RuntimeImport(Redhawk.BaseName, "RhpGetCastableObjectDispatch_CommonStub")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetCastableObjectDispatch_CommonStub();
[RuntimeImport(Redhawk.BaseName, "RhpGetTailCallTLSDispatchCell")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetTailCallTLSDispatchCell();
[RuntimeImport(Redhawk.BaseName, "RhpSetTLSDispatchCell")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static unsafe void RhpSetTLSDispatchCell(IntPtr pCell);
[RuntimeImport(Redhawk.BaseName, "RhpGetNumThunkBlocksPerMapping")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static int RhpGetNumThunkBlocksPerMapping();
[RuntimeImport(Redhawk.BaseName, "RhpGetNumThunksPerBlock")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static int RhpGetNumThunksPerBlock();
[RuntimeImport(Redhawk.BaseName, "RhpGetThunkSize")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static int RhpGetThunkSize();
[RuntimeImport(Redhawk.BaseName, "RhpGetThunkDataBlockAddress")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetThunkDataBlockAddress(IntPtr thunkStubAddress);
[RuntimeImport(Redhawk.BaseName, "RhpGetThunkStubsBlockAddress")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static IntPtr RhpGetThunkStubsBlockAddress(IntPtr thunkDataAddress);
[RuntimeImport(Redhawk.BaseName, "RhpGetThunkBlockSize")]
[MethodImpl(MethodImplOptions.InternalCall)]
[ManuallyManaged(GcPollPolicy.Never)]
internal extern static int RhpGetThunkBlockSize();
[RuntimeImport(Redhawk.BaseName, "RhpGetThreadAbortException")]
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static Exception RhpGetThreadAbortException();
//------------------------------------------------------------------------------------------------------------
// PInvoke-based internal calls
//
// These either do not need to be called in cooperative mode or, in some cases, MUST be called in preemptive
// mode. Note that they must use the Cdecl calling convention due to a limitation in our .obj file linking
// support.
//------------------------------------------------------------------------------------------------------------
// Block the current thread until at least one object needs to be finalized (returns true) or
// memory is low (returns false and the finalizer thread should initiate a garbage collection).
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern uint RhpWaitForFinalizerRequest();
// Indicate that the current round of finalizations is complete.
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RhpSignalFinalizationComplete();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RhpAcquireCastCacheLock();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RhpReleaseCastCacheLock();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal extern static long PalGetTickCount64();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RhpAcquireThunkPoolLock();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void RhpReleaseThunkPoolLock();
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr RhAllocateThunksMapping();
// Enters a no GC region, possibly doing a blocking GC if there is not enough
// memory available to satisfy the caller's request.
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int RhpStartNoGCRegion(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC);
// Exits a no GC region, possibly doing a GC to clean up the garbage that
// the caller allocated.
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int RhpEndNoGCRegion();
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Static methods to serialize and deserialize scene objects to and from XML
/// </summary>
public class SceneXmlLoader
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset)
{
XmlDocument doc = new XmlDocument();
XmlNode rootNode;
if (fileName.StartsWith("http:") || File.Exists(fileName))
{
XmlTextReader reader = new XmlTextReader(fileName);
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
rootNode = doc.FirstChild;
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = SceneObjectSerializer.FromOriginalXmlFormat(aPrimNode.OuterXml);
if (newIDS)
{
obj.ResetIDs();
}
//if we want this to be a import method then we need new uuids for the object to avoid any clashes
//obj.RegenerateFullIDs();
scene.AddNewSceneObject(obj, true);
}
}
else
{
throw new Exception("Could not open file " + fileName + " for reading");
}
}
public static void SavePrimsToXml(Scene scene, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
StreamWriter stream = new StreamWriter(file);
int primCount = 0;
stream.WriteLine("<scene>\n");
List<EntityBase> EntityList = scene.GetEntities();
foreach (EntityBase ent in EntityList)
{
if (ent is SceneObjectGroup)
{
stream.WriteLine(SceneObjectSerializer.ToOriginalXmlFormat((SceneObjectGroup)ent, StopScriptReason.None));
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Close();
file.Close();
}
public static string SaveGroupToXml2(SceneObjectGroup grp)
{
return SceneObjectSerializer.ToXml2Format(grp, false);
}
public static string SaveGroupToOriginalXml(SceneObjectGroup grp)
{
return SceneObjectSerializer.ToOriginalXmlFormat(grp, false);
}
public static SceneObjectGroup DeserializeGroupFromXml2(string xmlString)
{
XmlDocument doc = new XmlDocument();
XmlNode rootNode;
XmlTextReader reader = new XmlTextReader(new StringReader(xmlString));
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
rootNode = doc.FirstChild;
// This is to deal with neighbouring regions that are still surrounding the group xml with the <scene>
// tag. It should be possible to remove the first part of this if statement once we go past 0.5.9 (or
// when some other changes forces all regions to upgrade).
// This might seem rather pointless since prim crossing from this revision to an earlier revision remains
// broken. But it isn't much work to accomodate the old format here.
if (rootNode.LocalName.Equals("scene"))
{
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
// There is only ever one prim. This oddity should be removeable post 0.5.9
return SceneObjectSerializer.FromXml2Format(aPrimNode.OuterXml);
}
return null;
}
else
{
return SceneObjectSerializer.FromXml2Format(rootNode.OuterXml);
}
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="fileName"></param>
public static void LoadPrimsFromXml2(Scene scene, string fileName)
{
LoadPrimsFromXml2(scene, new XmlTextReader(fileName), false);
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
public static void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts)
{
LoadPrimsFromXml2(scene, new XmlTextReader(reader), startScripts);
}
/// <summary>
/// Load prims from the xml2 format. This method will close the reader
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
protected static void LoadPrimsFromXml2(Scene scene, XmlTextReader reader, bool startScripts)
{
XmlDocument doc = new XmlDocument();
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
XmlNode rootNode = doc.FirstChild;
ICollection<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = CreatePrimFromXml2(scene, aPrimNode.OuterXml);
if (obj != null && startScripts)
sceneObjects.Add(obj);
}
foreach (SceneObjectGroup sceneObject in sceneObjects)
{
sceneObject.CreateScriptInstances(0, ScriptStartFlags.PostOnRez, scene.DefaultScriptEngine, 0, null);
}
}
/// <summary>
/// Create a prim from the xml2 representation.
/// </summary>
/// <param name="scene"></param>
/// <param name="xmlData"></param>
/// <returns>The scene object created. null if the scene object already existed</returns>
protected static SceneObjectGroup CreatePrimFromXml2(Scene scene, string xmlData)
{
SceneObjectGroup obj = SceneObjectSerializer.FromXml2Format(xmlData);
if (scene.AddRestoredSceneObject(obj, true, false))
return obj;
else
return null;
}
public static void SavePrimsToXml2(Scene scene, string fileName)
{
List<EntityBase> EntityList = scene.GetEntities();
SavePrimListToXml2(EntityList, fileName);
}
public static void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max)
{
List<EntityBase> EntityList = scene.GetEntities();
SavePrimListToXml2(EntityList, stream, min, max);
}
public static void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName)
{
m_log.InfoFormat(
"[SERIALIZER]: Saving prims with name {0} in xml2 format for region {1} to {2}",
primName, scene.RegionInfo.RegionName, fileName);
List<EntityBase> entityList = scene.GetEntities();
List<EntityBase> primList = new List<EntityBase>();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
if (ent.Name == primName)
{
primList.Add(ent);
}
}
}
SavePrimListToXml2(primList, fileName);
}
public static void SavePrimListToXml2(List<EntityBase> entityList, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
try
{
StreamWriter stream = new StreamWriter(file);
try
{
SavePrimListToXml2(entityList, stream, Vector3.Zero, Vector3.Zero);
}
finally
{
stream.Close();
}
}
finally
{
file.Close();
}
}
public static void SavePrimListToXml2(List<EntityBase> entityList, TextWriter stream, Vector3 min, Vector3 max)
{
int primCount = 0;
stream.WriteLine("<scene>\n");
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup g = (SceneObjectGroup)ent;
if (!min.Equals(Vector3.Zero) || !max.Equals(Vector3.Zero))
{
Vector3 pos = g.RootPart.GetWorldPosition();
if (min.X > pos.X || min.Y > pos.Y || min.Z > pos.Z)
continue;
if (max.X < pos.X || max.Y < pos.Y || max.Z < pos.Z)
continue;
}
stream.WriteLine(SceneObjectSerializer.ToXml2Format(g, false));
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Flush();
}
}
}
| |
// --------------------------------------------------------------------------------------------
#region // Copyright (c) 2014, SIL International. All Rights Reserved.
// <copyright from='2003' to='2014' company='SIL International'>
// Copyright (c) 2014, SIL International. All Rights Reserved.
//
// Distributable under the terms of the MIT License (http://sil.mit-license.org/)
// </copyright>
#endregion
//
// This class originated in FieldWorks (under the GNU Lesser General Public License), but we
// have decided to make it avaialble in SIL.ScriptureUtils as part of Palaso so it will be more
// readily available to other projects.
// --------------------------------------------------------------------------------------------
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
namespace SIL.ScriptureUtils
{
#region ScrReferenceTests
/// ----------------------------------------------------------------------------------------
/// <summary>
/// Tests for the ScrReference class
/// </summary>
/// ----------------------------------------------------------------------------------------
[TestFixture]
public class ScrReferenceTests
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Initializes the VersificationTable class for tests.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void InitializeVersificationTable()
{
string vrsPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
File.WriteAllBytes(Path.Combine(vrsPath,
VersificationTable.GetFileNameForVersification(ScrVers.English)), Properties.Resources.eng);
File.WriteAllBytes(Path.Combine(vrsPath,
VersificationTable.GetFileNameForVersification(ScrVers.Septuagint)), Properties.Resources.lxx);
File.WriteAllBytes(Path.Combine(vrsPath,
VersificationTable.GetFileNameForVersification(ScrVers.Original)), Properties.Resources.org);
VersificationTable.Initialize(vrsPath);
}
public static void InitializeScrReferenceForTests()
{
InitializeVersificationTable();
BCVRef.SupportDeuterocanon = false;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Set up to initialize ScrReference
/// </summary>
/// ------------------------------------------------------------------------------------
[TestFixtureSetUp]
public void FixtureSetup()
{
InitializeScrReferenceForTests();
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Setup test
/// </summary>
/// ------------------------------------------------------------------------------------
[SetUp]
public void Setup()
{
BCVRef.SupportDeuterocanon = false;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test the constructors of ScrReference and the Valid and IsBookTitle properties
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ValidScrReferences()
{
ScrReference bcvRef = new ScrReference(1, 2, 3, ScrVers.English);
Assert.IsTrue(bcvRef.Valid);
Assert.IsFalse(bcvRef.IsBookTitle);
Assert.AreEqual(1002003, (int)bcvRef);
Assert.AreEqual(1, bcvRef.Book);
Assert.AreEqual(2, bcvRef.Chapter);
Assert.AreEqual(3, bcvRef.Verse);
Assert.AreEqual(ScrVers.English, bcvRef.Versification);
bcvRef = new ScrReference(4005006, ScrVers.Original);
Assert.IsTrue(bcvRef.Valid);
Assert.IsFalse(bcvRef.IsBookTitle);
Assert.AreEqual(4005006, (int)bcvRef);
Assert.AreEqual(4, bcvRef.Book);
Assert.AreEqual(5, bcvRef.Chapter);
Assert.AreEqual(6, bcvRef.Verse);
Assert.AreEqual(ScrVers.Original, bcvRef.Versification);
bcvRef = new ScrReference();
Assert.IsFalse(bcvRef.Valid);
Assert.IsFalse(bcvRef.IsBookTitle);
Assert.AreEqual(0, (int)bcvRef);
Assert.AreEqual(0, bcvRef.Book);
Assert.AreEqual(0, bcvRef.Chapter);
Assert.AreEqual(0, bcvRef.Verse);
bcvRef = new ScrReference(5, 0, 0, ScrVers.English);
Assert.IsFalse(bcvRef.Valid);
Assert.IsTrue(bcvRef.IsBookTitle);
Assert.AreEqual(5000000, (int)bcvRef);
Assert.AreEqual(5, bcvRef.Book);
Assert.AreEqual(0, bcvRef.Chapter);
Assert.AreEqual(0, bcvRef.Verse);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test invalid ScrReference values
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void InvalidScrReferences()
{
// Invalid BCVs
ScrReference scrRef = new ScrReference(7, 8, 1001, ScrVers.English);
Assert.IsFalse(scrRef.Valid);
scrRef.MakeValid();
Assert.AreEqual(7008035, (int)scrRef);
Assert.AreEqual(7, scrRef.Book);
Assert.AreEqual(8, scrRef.Chapter);
Assert.AreEqual(35, scrRef.Verse);
scrRef = new ScrReference(9, 1002, 10, ScrVers.English);
Assert.IsFalse(scrRef.Valid);
scrRef.MakeValid();
Assert.AreEqual(9031010, (int)scrRef);
Assert.AreEqual(9, scrRef.Book);
Assert.AreEqual(31, scrRef.Chapter);
Assert.AreEqual(10, scrRef.Verse);
scrRef = new ScrReference(101, 11, 12, ScrVers.English);
Assert.IsFalse(scrRef.Valid);
scrRef.MakeValid();
Assert.AreEqual(66011012, (int)scrRef);
Assert.AreEqual(66, scrRef.Book);
Assert.AreEqual(11, scrRef.Chapter);
Assert.AreEqual(12, scrRef.Verse);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests ScrReference.LastChapter property
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void GetLastChapterForBook()
{
ScrReference scrRef = new ScrReference("HAG 1:1", ScrVers.English);
Assert.AreEqual(2, scrRef.LastChapter);
scrRef.Book = ScrReference.BookToNumber("PSA");
Assert.AreEqual(150, scrRef.LastChapter);
scrRef.Book = 456;
Assert.AreEqual(0, scrRef.LastChapter);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the overload of the constructor that takes a reference string
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_InvalidVersification()
{
ScrReference reference = new ScrReference("GEN 1:1", ScrVers.Unknown);
Assert.IsFalse(reference.Valid);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests comparing 2 references with different versifications
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void Equal_DifferentVersification()
{
ScrReference ref1 = new ScrReference("GEN 31:55", ScrVers.English);
ScrReference ref2 = new ScrReference("GEN 32:1", ScrVers.Original);
Assert.IsTrue(ref1 == ref2);
ref1 = new ScrReference("JOB 41:9", ScrVers.English);
ref2 = new ScrReference("JOB 41:1", ScrVers.Original);
Assert.IsTrue(ref1 == ref2);
ref1 = new ScrReference("JOB 41:9", ScrVers.English);
ref2 = new ScrReference("JOB 41:2", ScrVers.Original);
Assert.IsFalse(ref1 == ref2);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests comparing 2 references with different versifications when one is of an unknown
/// versification
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void Equal_UnknownVersification()
{
ScrReference ref1 = new ScrReference("GEN 30:1", ScrVers.Unknown);
ScrReference ref2 = new ScrReference("GEN 30:1", ScrVers.Original);
Assert.IsTrue(ref1 == ref2);
ref1 = new ScrReference("GEN 19:1", ScrVers.Unknown);
ref2 = new ScrReference("GEN 21:1", ScrVers.English);
Assert.IsFalse(ref1 == ref2);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the less than with 2 references with different versifications when one is of
/// an unknown versification
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void LessThan_UnknownVersification()
{
ScrReference ref1 = new ScrReference("GEN 30:1", ScrVers.Unknown);
ScrReference ref2 = new ScrReference("GEN 30:1", ScrVers.Original);
Assert.IsFalse(ref1 < ref2);
ref1 = new ScrReference("GEN 19:1", ScrVers.Unknown);
ref2 = new ScrReference("GEN 21:1", ScrVers.English);
Assert.IsTrue(ref1 < ref2);
ref1 = new ScrReference("GEN 21:1", ScrVers.Unknown);
ref2 = new ScrReference("GEN 19:1", ScrVers.English);
Assert.IsFalse(ref1 < ref2);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the less than operator with an integer
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void LessThan_int()
{
ScrReference ref2 = new ScrReference("GEN 30:2", ScrVers.Original);
Assert.IsTrue(1030001 < ref2);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the CompareTo method with a ScrReference
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void CompareTo_ScrReference()
{
ScrReference ref1 = new ScrReference("GEN 30:1", ScrVers.Original);
ScrReference ref2 = new ScrReference("GEN 30:1", ScrVers.Original);
Assert.AreEqual(0, ref1.CompareTo(ref2));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the CompareTo method with a BCVRef
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void CompareTo_BCVRef()
{
ScrReference ref1 = new ScrReference("GEN 30:1", ScrVers.Original);
BCVRef ref2 = new BCVRef("GEN 30:1");
Assert.AreEqual(0, ref1.CompareTo(ref2));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the CompareTo method with an integer
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void CompareTo_int()
{
ScrReference ref1 = new ScrReference("GEN 30:1", ScrVers.Original);
Assert.AreEqual(0, ref1.CompareTo(1030001));
}
}
#endregion
#region ParseChapterVerseNumberTests
/// ----------------------------------------------------------------------------------------
/// <summary>
/// Tests for static methods on ScrReference that parse chapter and verse numbers.
/// </summary>
/// ----------------------------------------------------------------------------------------
[TestFixture]
public class ScrReference_ParseChapterVerseNumberTests
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Set up to initialize ScrReference
/// </summary>
/// ------------------------------------------------------------------------------------
[TestFixtureSetUp]
public void FixtureSetup()
{
ScrReferenceTests.InitializeScrReferenceForTests();
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the ChapterToInt method when dealing with large chapter numbers
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ChapterToInt_LargeChapterNumber()
{
// Test a really large number that will pass the Int16.MaxValue
Assert.AreEqual(Int16.MaxValue, ScrReference.ChapterToInt("5200000000000"));
// Test a verse number just under the limit
Assert.AreEqual(32766, ScrReference.ChapterToInt("32766"));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the VerseToInt method when dealing with large verse numbers
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void VerseToInt_LargeVerseNumber()
{
// Test a really large number that will pass the Int16.MaxValue
int firstVerse, secondVerse;
ScrReference.VerseToInt("5200000000000", out firstVerse, out secondVerse);
Assert.AreEqual(999, firstVerse);
Assert.AreEqual(999, secondVerse);
// Test a verse number just under the limit
ScrReference.VerseToInt("998", out firstVerse, out secondVerse);
Assert.AreEqual(998, firstVerse);
Assert.AreEqual(998, secondVerse);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests for converting verse number strings to verse number integers. These are similar
/// scenarios tested in ExportUsfm:VerseNumParse. All of them are successfully parsed
/// there. The scenarios which have problems converting verse number strings, are
/// commented out with a description of the incorrect result.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void VerseToIntTest()
{
int nVerseStart, nVerseEnd;
// Test invalid verse number strings
ScrReference.VerseToInt("-12",out nVerseStart, out nVerseEnd);
Assert.AreEqual(12, nVerseStart);
Assert.AreEqual(12, nVerseEnd);
ScrReference.VerseToInt("14-", out nVerseStart, out nVerseEnd);
Assert.AreEqual(14, nVerseStart);
Assert.AreEqual(14, nVerseEnd);
ScrReference.VerseToInt("a3", out nVerseStart, out nVerseEnd);
Assert.AreEqual(3, nVerseStart);
Assert.AreEqual(3, nVerseEnd);
ScrReference.VerseToInt("15b-a", out nVerseStart, out nVerseEnd);
Assert.AreEqual(15, nVerseStart);
Assert.AreEqual(15, nVerseEnd);
ScrReference.VerseToInt("3bb", out nVerseStart, out nVerseEnd);
Assert.AreEqual(3, nVerseStart);
Assert.AreEqual(3, nVerseEnd);
ScrReference.VerseToInt("0", out nVerseStart, out nVerseEnd);
Assert.AreEqual(0, nVerseStart);
Assert.AreEqual(0, nVerseEnd);
ScrReference.VerseToInt(" 12", out nVerseStart, out nVerseEnd);
Assert.AreEqual(12, nVerseStart);
Assert.AreEqual(12, nVerseEnd);
ScrReference.VerseToInt("14 ", out nVerseStart, out nVerseEnd);
Assert.AreEqual(14, nVerseStart);
Assert.AreEqual(14, nVerseEnd);
ScrReference.VerseToInt("12-10", out nVerseStart, out nVerseEnd);
Assert.AreEqual(12, nVerseStart);
//Assert.AreEqual(12, nVerseEnd); // end verse set to 12 instead of 10
ScrReference.VerseToInt("139-1140", out nVerseStart, out nVerseEnd);
Assert.AreEqual(139, nVerseStart);
//Assert.AreEqual(139, nVerseEnd); // end verse set to 999 instead of 139
ScrReference.VerseToInt("177-140", out nVerseStart, out nVerseEnd);
//Assert.AreEqual(140, nVerseStart); // start verse set to 177 instead of 140
Assert.AreEqual(140, nVerseEnd);
//Review: should this be a requirement?
// ScrReference.VerseToInt("177", out nVerseStart, out nVerseEnd);
// Assert.AreEqual(0, nVerseStart); // 177 is out of range of valid verse numbers
// Assert.AreEqual(0, nVerseEnd);
ScrReference.VerseToInt(String.Empty, out nVerseStart, out nVerseEnd);
Assert.AreEqual(0, nVerseStart);
Assert.AreEqual(0, nVerseEnd);
ScrReference.VerseToInt(String.Empty, out nVerseStart, out nVerseEnd);
Assert.AreEqual(0, nVerseStart);
Assert.AreEqual(0, nVerseEnd);
// Test valid verse number strings
ScrReference.VerseToInt("1a", out nVerseStart, out nVerseEnd);
Assert.AreEqual(1, nVerseStart);
Assert.AreEqual(1, nVerseEnd);
ScrReference.VerseToInt("2a-3b", out nVerseStart, out nVerseEnd);
Assert.AreEqual(2, nVerseStart);
Assert.AreEqual(3, nVerseEnd);
ScrReference.VerseToInt("4-5d", out nVerseStart, out nVerseEnd);
Assert.AreEqual(4, nVerseStart);
Assert.AreEqual(5, nVerseEnd);
ScrReference.VerseToInt("6", out nVerseStart, out nVerseEnd);
Assert.AreEqual(6, nVerseStart);
Assert.AreEqual(6, nVerseEnd);
ScrReference.VerseToInt("66", out nVerseStart, out nVerseEnd);
Assert.AreEqual(66, nVerseStart);
Assert.AreEqual(66, nVerseEnd);
ScrReference.VerseToInt("176", out nVerseStart, out nVerseEnd);
Assert.AreEqual(176, nVerseStart);
Assert.AreEqual(176, nVerseEnd);
//We expect this test to pass
//RTL verse bridge should be valid syntax
ScrReference.VerseToInt("6" + '\u200f' + "-" + '\u200f' + "8", out nVerseStart,
out nVerseEnd);
Assert.AreEqual(6, nVerseStart);
Assert.AreEqual(8, nVerseEnd);
}
}
#endregion
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ASCMD
{
using Microsoft.Protocols.TestSuites.Common;
using Response = Microsoft.Protocols.TestSuites.Common.Response;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net;
using Request = Microsoft.Protocols.TestSuites.Common.Request;
/// <summary>
/// This scenario is used to test the common status codes.
/// </summary>
[TestClass]
public class S21_CommonStatusCode : TestSuiteBase
{
#region Class initialize and clean up
/// <summary>
/// Initialize the class.
/// </summary>
/// <param name="testContext">VSTS test context.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Clear the class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test cases
/// <summary>
/// This test case is used to verify the server will return 166, when AccountId is invalid.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC01_CommonStatusCode_166()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Status value 166 is not returned when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Status value 166 is not returned when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Call method SendMail to send e-mail messages with invalid AccountID value.
string emailSubject = Common.GenerateResourceName(Site, "subject");
// Send email with invalid AccountID value
SendMailResponse sendMailResponse = this.SendPlainTextEmail("InvalidAccountID", emailSubject, this.User1Information.UserName, this.User2Information.UserName, null);
#endregion
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4956");
Site.Log.Add(LogEntryKind.Debug, "When sending mail with invalid AccountID, server returns status {0}", sendMailResponse.ResponseData.Status);
// Verify MS-ASCMD requirement: MS-ASCMD_R4956
Site.CaptureRequirementIfAreEqual<string>(
"166",
sendMailResponse.ResponseData.Status,
4956,
@"[In Common Status Codes] [The meaning of the status value 166 is] The AccountId (section 2.2.3.3) value is not valid.<100>");
#region Sync user2 mailbox changes
// Switch to user2's mailbox
this.SwitchUser(this.User2Information);
this.GetMailItem(this.User2Information.InboxCollectionId, emailSubject);
// Record user name, folder collectionId and item subject that is used in this case
TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, emailSubject);
#endregion
}
/// <summary>
/// This test case is used to verify server will return 173, when the picture does not exist.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC02_CommonStatusCode_173()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Status value 173 is not returned when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Status value 173 is not returned when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Call method ResolveRecipients to resolve a list of supplied recipients, to retrieve their free/busy information, or retrieve their S/MIME certificates so that clients can send encrypted S/MIME e-mail messages.
string displayName = this.User3Information.UserName;
ResolveRecipientsRequest resolveRecipientsRequest = new ResolveRecipientsRequest();
Request.ResolveRecipients requestResolveRecipients = new Request.ResolveRecipients();
Request.ResolveRecipientsOptions requestResolveRecipientsOption = new Request.ResolveRecipientsOptions
{
Picture = new Request.ResolveRecipientsOptionsPicture { MaxPictures = 3 }
};
requestResolveRecipients.Items = new object[] { requestResolveRecipientsOption, displayName };
resolveRecipientsRequest.RequestData = requestResolveRecipients;
ResolveRecipientsResponse resolveRecipientsResponse = this.CMDAdapter.ResolveRecipients(resolveRecipientsRequest);
#endregion
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4970");
Site.Log.Add(LogEntryKind.Debug, "When the contact picture does not exit, server returns status {0}", resolveRecipientsResponse.ResponseData.Response[0].Recipient[0].Picture[0].Status);
// Verify MS-ASCMD requirement: MS-ASCMD_R4970
Site.CaptureRequirementIfAreEqual<string>(
"173",
resolveRecipientsResponse.ResponseData.Response[0].Recipient[0].Picture[0].Status,
4970,
@"[In Common Status Codes] [The meaning of the status value 173 is] The user does not have a contact photo.<107>");
}
/// <summary>
/// This test case is used to verify the server will return 165, when the required DeviceInformation element is missing in the Provision request.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC03_CommonStatusCode_165()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Status value 165 is not returned when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Status value 165 is not returned when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region User calls Provision command without the DeviceInformation element
ProvisionRequest provisionRequest = TestSuiteBase.GenerateDefaultProvisionRequest();
provisionRequest.RequestData.DeviceInformation = null;
ProvisionResponse provisionResponse = this.CMDAdapter.Provision(provisionRequest);
#endregion
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4954");
// Verify MS-ASCMD requirement: MS-ASCMD_R4954
Site.CaptureRequirementIfAreEqual<byte>(
165,
provisionResponse.ResponseData.Status,
4954,
@"[In Common Status Codes] [The meaning of the status value 165 is] The required DeviceInformation element (as specified in [MS-ASPROV] section 2.2.2.52) is missing in the Provision request.<99>");
}
/// <summary>
/// This test case is used to verify the server will return 105, when the request contains a combination of parameters that is invalid.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC04_CommonStatusCode_105()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The DstFldId element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region User2 sends mail to User1 and do FolderSync in User1's mailbox.
string subject = this.SendMailAndFolderSync();
#endregion
#region Call method Sync to synchronize changes of Inbox folder in User1's mailbox between the client and the server, and get the ServerId of sent email item and the SyncKey
SyncResponse syncResponseInbox = this.GetMailItem(this.User1Information.InboxCollectionId, subject);
string serverId = TestSuiteBase.FindServerId(syncResponseInbox, "Subject", subject);
#endregion
#region Call method MoveItems with the email item's ServerId to move the email item from Inbox folder to recipient information cache.
Request.MoveItemsMove moveItemsMove = new Request.MoveItemsMove
{
DstFldId = this.User1Information.RecipientInformationCacheCollectionId,
SrcFldId = this.User1Information.InboxCollectionId,
SrcMsgId = serverId
};
MoveItemsRequest moveItemsRequest = Common.CreateMoveItemsRequest(new Request.MoveItemsMove[] { moveItemsMove });
MoveItemsResponse moveItemsResponse = this.CMDAdapter.MoveItems(moveItemsRequest);
#endregion
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4821");
// Verify MS-ASCMD requirement: MS-ASCMD_R4821
Site.CaptureRequirementIfAreEqual<int>(
105,
int.Parse(moveItemsResponse.ResponseData.Response[0].Status),
4821,
@"[In Common Status Codes] [The meaning of the status value 105 is] The request contains a combination of parameters that is invalid.");
}
/// <summary>
/// This test case is used to verify the server returns 164, when the BodyPartPreference node has an unsupported Type element value.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC05_CommonStatusCode_164()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Status value 164 is not returned when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Status value 164 is not returned when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region User calls Sync command with option element
// Set an unsupported Type element value in the BodyPartPreference node
Request.Options option = new Request.Options
{
Items = new object[]
{
new Request.BodyPartPreference()
{
// As specified in [MS-ASAIRS] section 2.2.2.22.3, only a value of 2 (HTML) SHOULD be used in the Type element of a BodyPartPreference element.
// Then '3' is an unsupported Type element value.
Type = 3
}
},
ItemsElementName = new Request.ItemsChoiceType1[] { Request.ItemsChoiceType1.BodyPartPreference }
};
SyncRequest syncRequest = TestSuiteBase.CreateEmptySyncRequest(this.User1Information.InboxCollectionId);
this.Sync(syncRequest);
syncRequest.RequestData.Collections[0].Options = new Request.Options[] { option };
syncRequest.RequestData.Collections[0].SyncKey = this.LastSyncKey;
SyncResponse syncResponse = this.Sync(syncRequest);
#endregion
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R5412");
// Verify MS-ASCMD requirement: MS-ASCMD_R5412
Site.CaptureRequirementIfAreEqual<int>(
164,
int.Parse(syncResponse.ResponseData.Status),
5412,
@"[In Common Status Codes] [The meaning of the status value 164 is] The BodyPartPreference node (as specified in [MS-ASAIRS] section 2.2.2.7) has an unsupported Type element (as specified in [MS-ASAIRS] section 2.2.2.22.4) value.<98>");
}
/// <summary>
/// This test case is used to verify the server returns 118, when the message was already sent in a previous request.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC06_CommonStatusCode_118()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "This test case is not supported when the MS-ASProtocolVersion header is set to 12.1.. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region User1 calls SendMail command to send email messages to user2.
string emailSubject = Common.GenerateResourceName(Site, "subject");
string from = Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain);
string to = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain);
string content = Common.GenerateResourceName(Site, "Default Email");
string mime = Common.CreatePlainTextMime(from, to, null, null, emailSubject, content);
SendMailRequest sendMailRequest = Common.CreateSendMailRequest(TestSuiteBase.ClientId, false, mime);
SendMailResponse responseSendMail = this.CMDAdapter.SendMail(sendMailRequest);
Site.Assert.AreEqual<string>(
string.Empty,
responseSendMail.ResponseDataXML,
"The server should return an empty xml response data to indicate SendMail command success.");
this.SwitchUser(this.User2Information);
TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, emailSubject);
this.GetMailItem(this.User2Information.InboxCollectionId, emailSubject);
this.SwitchUser(this.User1Information);
#endregion
#region User1 calls SendMail command with the same ClientId again.
// Use the same ClientId to call SendMail command again
responseSendMail = this.CMDAdapter.SendMail(sendMailRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4848");
// Verify MS-ASCMD requirement: MS-ASCMD_R4848
Site.CaptureRequirementIfAreEqual<string>(
"118",
responseSendMail.ResponseData.Status,
4848,
@"[In Common Status Codes] [The meaning of the status value 118 is] The message was already sent in a previous request.");
#endregion
}
/// <summary>
/// This test case is used to verify the server returns 102, when call FolderSync command containing a FileReference element which is not defined in FolderSync request.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC07_CommonStatusCode_102()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "This test case is not supported when the MS-ASProtocolVersion header is set to 12.1.. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region call FolderSync command containing a FileReference element which is not defined in FolderSync request.
FolderSyncRequest request = new FolderSyncRequest();
Request.FolderSync requestData = new Request.FolderSync { FileReference = "0", FileReferenceSpecified = true };
request.RequestData = requestData;
FolderSyncResponse folderSyncResponse = this.CMDAdapter.FolderSync(request);
this.Site.CaptureRequirementIfAreEqual<int>(
102,
int.Parse(folderSyncResponse.ResponseData.Status),
4815,
@"[In Common Status Codes] When the protocol version is 14.0, 14.1 or 16.0, [The meaning of the status value 102 is] The request contains WBXML but it could not be decoded into XML.");
#endregion
}
/// <summary>
/// This test case is used to verify the server returns 103, when The XML provided in the request does not follow the protocol requirements.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC08_CommonStatusCode_103()
{
#region Call SendMail command without Mime and AccountID.
Request.SendMail sendMail = new Request.SendMail
{
ClientId = TestSuiteBase.ClientId
};
SendMailRequest request = new SendMailRequest();
request.RequestData = sendMail;
if (Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("12.1"))
{
try
{
SendMailResponse response = this.CMDAdapter.SendMail(request);
}
catch (System.Net.WebException ex)
{
this.Site.CaptureRequirementIfAreEqual<HttpStatusCode>(
HttpStatusCode.BadRequest,
((HttpWebResponse)ex.Response).StatusCode,
7547,
@"[In Common Status Codes] When protocol version 2.5, 12.0, or 12.1 is used, an HTTP 400 response is returned instead of this status value [103].");
}
}
if (Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("14.0") ||
Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("14.1") ||
Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("16.0"))
{
SendMailResponse response = this.CMDAdapter.SendMail(request);
this.Site.CaptureRequirementIfAreEqual<int>(
103,
int.Parse(response.ResponseData.Status),
4817,
@"[In Common Status Codes] When the protocol version is 14.0, 14.1 or 16.0, [The meaning of the status value 103 is] The XML provided in the request does not follow the protocol requirements.");
}
#endregion
}
/// <summary>
/// This test case is used to verify the server returns 119, when message being sent contains no recipient.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC09_CommonStatusCode_119()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "This test case is not supported when the MS-ASProtocolVersion header is set to 12.1.. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Send message which contains no recipient.
string emailSubject = Common.GenerateResourceName(Site, "subject");
string body = Common.GenerateResourceName(Site, "Default Email");
string from = from = Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain);
string mime = Common.CreatePlainTextMime(from, string.Empty, null, null, emailSubject, body);
SendMailRequest sendMailRequest = Common.CreateSendMailRequest(TestSuiteBase.ClientId, false, mime);
SendMailResponse response = this.CMDAdapter.SendMail(sendMailRequest);
this.Site.CaptureRequirementIfAreEqual<int>(
119,
int.Parse(response.ResponseData.Status),
4853,
@"[In Common Status Codes] When the protocol version is 14.0, 14.1 or 16.0, [The meaning of the status value 119 is] The message being sent contains no recipient.");
#endregion
}
/// <summary>
/// This test case is used to verify the server returns 109, when the device type is either missing or has an invalid format.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC10_CommonStatusCode_109()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "This test case is not supported when the MS-ASProtocolVersion header is set to 12.1.. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Call FolderSync with a invaild format deviceType
this.CMDAdapter.ChangeHeaderEncodingType(QueryValueType.PlainText);
this.CMDAdapter.ChangeDeviceType("123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
FolderSyncResponse response = this.FolderSync();
this.Site.CaptureRequirementIfAreEqual<int>(
109,
int.Parse(response.ResponseData.Status),
4830,
@"[In Common Status Codes] When the protocol version is 14.0, 14.1 or 16.0, [The meaning of the status value 109 is] The device type is either missing or has an invalid format.");
this.CMDAdapter.ChangeDeviceType(Common.GetConfigurationPropertyValue("DeviceType", this.Site));
#endregion
}
/// <summary>
/// This test case is used to verify the server returns 108, when the device ID is either missing or has an invalid format.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC11_CommonStatusCode_108()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "This test case is not supported when the MS-ASProtocolVersion header is set to 12.1.. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Call FolderSync with a invaild format device ID
this.CMDAdapter.ChangeHeaderEncodingType(QueryValueType.PlainText);
this.CMDAdapter.ChangeDeviceID("123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
FolderSyncResponse response = this.FolderSync();
this.Site.CaptureRequirementIfAreEqual<int>(
108,
int.Parse(response.ResponseData.Status),
4828,
@"[In Common Status Codes] When the protocol version is 14.0, 14.1 or 16.0, [The meaning of the status value 108 is] The device ID is either missing or has an invalid format.");
this.CMDAdapter.ChangeDeviceID(Common.GetConfigurationPropertyValue("DeviceType", this.Site));
#endregion
}
/// <summary>
/// This test case is used to verify the server returns 126, when the user object in the directory service indicates that this user is not allowed to use ActiveSync.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC12_CommonStatusCode_126()
{
UserInformation disableUser=new UserInformation()
{
UserName = Common.GetConfigurationPropertyValue("User4Name", this.Site),
UserPassword = Common.GetConfigurationPropertyValue("User4Password", this.Site),
UserDomain = Common.GetConfigurationPropertyValue("Domain", this.Site)
};
this.CMDAdapter.SwitchUser(disableUser.UserName, disableUser.UserPassword, disableUser.UserDomain);
if (Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("12.1"))
{
try
{
FolderSyncResponse response = this.FolderSync();
}
catch (System.Net.WebException ex)
{
this.Site.CaptureRequirementIfAreEqual<HttpStatusCode>(
HttpStatusCode.Forbidden,
((HttpWebResponse)ex.Response).StatusCode,
7555,
@"[In Common Status Codes] When protocol version 2.5, 12.0, or 12.1 is used, an HTTP 403 response is returned instead of this status value [126].");
}
}
if (Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("14.0") ||
Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("14.1") ||
Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site).Equals("16.0"))
{
FolderSyncResponse response = this.FolderSync();
this.Site.CaptureRequirementIfAreEqual<int>(
126,
int.Parse(response.ResponseData.Status),
4869,
@"[In Common Status Codes] When the protocol version is 14.0, 14.1 or 16.0, [The meaning of the status value 126 is] The user object in the directory service indicates that this user is not allowed to use ActiveSync.");
}
}
/// <summary>
/// This test case is used to verify the server returns 150, when the value of either the ItemId element or the InstanceId element specified in the SmartReply or the SmartForward command request could not be found in the mailbox.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC13_CommonStatusCode_150()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "This test case is not supported when the MS-ASProtocolVersion header is set to 12.1.. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region Call SendMail command to send plain text email messages to user2.
string emailSubject = Common.GenerateResourceName(Site, "subject");
this.SendPlainTextEmail(null, emailSubject, this.User1Information.UserName, this.User2Information.UserName, null);
#endregion
#region Call Sync command to sync user2 mailbox changes
this.SwitchUser(this.User2Information);
SyncResponse syncChangeResponse = this.GetMailItem(this.User2Information.InboxCollectionId, emailSubject);
string originalServerID = TestSuiteBase.FindServerId(syncChangeResponse, "Subject", emailSubject);
string originalContent = TestSuiteBase.GetDataFromResponseBodyElement(syncChangeResponse, originalServerID);
#endregion
#region Record user name, folder collectionId and item subject that are used in this case
TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, emailSubject);
#endregion
#region Call Sync command to delete the email in user2's mailbox.
SyncRequest syncRequest = TestSuiteBase.CreateSyncDeleteRequest(this.LastSyncKey, this.User2Information.InboxCollectionId, originalServerID);
syncRequest.RequestData.Collections[0].DeletesAsMoves = false;
syncRequest.RequestData.Collections[0].DeletesAsMovesSpecified = true;
this.Sync(syncRequest);
#endregion
#region Call SmartForward command to forward messages without retrieving the full, original message from the server.
string forwardSubject = string.Format("FW:{0}", emailSubject);
string forwardFromUser = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain);
string forwardToUser = Common.GetMailAddress(this.User3Information.UserName, this.User3Information.UserDomain);
string forwardContent = Common.GenerateResourceName(Site, "forward:body");
SmartForwardRequest smartForwardRequest = this.CreateSmartForwardRequest(this.User2Information.InboxCollectionId, originalServerID, forwardFromUser, forwardToUser, string.Empty, string.Empty, forwardSubject, forwardContent);
SmartForwardResponse smartForwardResponse = this.CMDAdapter.SmartForward(smartForwardRequest);
#endregion
this.Site.CaptureRequirementIfAreEqual<int>(
150,
int.Parse(smartForwardResponse.ResponseData.Status),
4930,
@"[In Common Status Codes] When the protocol version is 14.0, 14.1 or 16.0, [The meaning of the status value 150 is] The value of either the ItemId element (section 2.2.3.88) or the InstanceId element (section 2.2.3.87.2) specified in the SmartReply (section 2.2.2.19) or the SmartForward (section 2.2.2.18) command request could not be found in the mailbox.");
}
/// <summary>
/// This test case is used to verify the server returns 145, when the The device claimed to be externally managed, but the server doesn't allow externally managed devices to sync.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S21_TC14_CommonStatusCode_145()
{
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "This test case is not supported when the MS-ASProtocolVersion header is set to 12.1.. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
#region User calls Provision command to download policies from server
// Calls Provision command to download policies
ProvisionRequest provisionRequest = TestSuiteBase.GenerateDefaultProvisionRequest();
ProvisionResponse provisionResponse = this.CMDAdapter.Provision(provisionRequest);
// Get policyKey, policyType and statusCode from server response
string policyKey = null;
if (null != provisionResponse.ResponseData.Policies)
{
Response.ProvisionPoliciesPolicy policyInResponse = provisionResponse.ResponseData.Policies.Policy;
if (policyInResponse != null)
{
policyKey = policyInResponse.PolicyKey;
}
}
string policyType = provisionResponse.ResponseData.Policies.Policy.PolicyType;
Response.ProvisionPoliciesPolicyData data = provisionResponse.ResponseData.Policies.Policy.Data;
byte statusCode = provisionResponse.ResponseData.Status;
#endregion
#region User calls Provision command to acknowledge policies.
// Set acknowledgeStatus value to 1, means accept the policy.
ProvisionRequest provisionAcknowledgeRequest = TestSuiteBase.GenerateDefaultProvisionRequest();
provisionAcknowledgeRequest.RequestData.Policies.Policy.PolicyKey = policyKey;
provisionAcknowledgeRequest.RequestData.Policies.Policy.Status = "4";
// Calls Provision command
ProvisionResponse provisionAcknowledgeResponse = this.CMDAdapter.Provision(provisionAcknowledgeRequest);
statusCode = provisionAcknowledgeResponse.ResponseData.Status;
this.Site.CaptureRequirementIfAreEqual<byte>(
145,
statusCode,
4917,
@"[In Common Status Codes] When the protocol version is 14.0, 14.1 or 16.0, [The meaning of the status value 145 is] The device claimed to be externally managed, but the server doesn't allow externally managed devices to sync.");
#endregion
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
public class FileVersionInfoTest
{
private const string NativeConsoleAppFileName = "NativeConsoleApp.exe";
private const string NativeLibraryFileName = "NativeLibrary.dll";
private const string SecondNativeLibraryFileName = "SecondNativeLibrary.dll";
private const string TestAssemblyFileName = "System.Diagnostics.FileVersionInfo.TestAssembly.dll";
private const string TestCsFileName = "Assembly1.cs";
private const string TestNotFoundFileName = "notfound.dll";
[Fact]
[PlatformSpecific(PlatformID.Windows)] // native PE files only supported on Windows
public void FileVersionInfo_Normal()
{
// NativeConsoleApp (English)
VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), NativeConsoleAppFileName), new MyFVI()
{
Comments = "",
CompanyName = "Microsoft Corporation",
FileBuildPart = 3,
FileDescription = "This is the description for the native console application.",
FileMajorPart = 5,
FileMinorPart = 4,
FileName = Path.Combine(Directory.GetCurrentDirectory(), NativeConsoleAppFileName),
FilePrivatePart = 2,
FileVersion = "5.4.3.2",
InternalName = NativeConsoleAppFileName,
IsDebug = false,
IsPatched = false,
IsPrivateBuild = false,
IsPreRelease = true,
IsSpecialBuild = true,
Language = GetFileVersionLanguage(0x0409), //English (United States)
LegalCopyright = "Copyright (C) 2050",
LegalTrademarks = "",
OriginalFilename = NativeConsoleAppFileName,
PrivateBuild = "",
ProductBuildPart = 3,
ProductMajorPart = 5,
ProductMinorPart = 4,
ProductName = Path.GetFileNameWithoutExtension(NativeConsoleAppFileName),
ProductPrivatePart = 2,
ProductVersion = "5.4.3.2",
SpecialBuild = ""
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // native PE files only supported on Windows
public void FileVersionInfo_Chinese()
{
// NativeLibrary.dll (Chinese)
VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), NativeLibraryFileName), new MyFVI()
{
Comments = "",
CompanyName = "A non-existent company",
FileBuildPart = 3,
FileDescription = "Here is the description of the native library.",
FileMajorPart = 9,
FileMinorPart = 9,
FileName = Path.Combine(Directory.GetCurrentDirectory(), NativeLibraryFileName),
FilePrivatePart = 3,
FileVersion = "9.9.3.3",
InternalName = "NativeLi.dll",
IsDebug = false,
IsPatched = true,
IsPrivateBuild = false,
IsPreRelease = true,
IsSpecialBuild = false,
Language = GetFileVersionLanguage(0x0004),//Chinese (Simplified)
Language2 = GetFileVersionLanguage(0x0804),//Chinese (Simplified, PRC) - changed, but not yet on all platforms
LegalCopyright = "None",
LegalTrademarks = "",
OriginalFilename = "NativeLi.dll",
PrivateBuild = "",
ProductBuildPart = 40,
ProductMajorPart = 20,
ProductMinorPart = 30,
ProductName = "I was never given a name.",
ProductPrivatePart = 50,
ProductVersion = "20.30.40.50",
SpecialBuild = "",
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // native PE files only supported on Windows
public void FileVersionInfo_DifferentFileVersionAndProductVersion()
{
// Mtxex.dll
VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), SecondNativeLibraryFileName), new MyFVI()
{
Comments = "",
CompanyName = "",
FileBuildPart = 0,
FileDescription = "",
FileMajorPart = 0,
FileMinorPart = 65535,
FileName = Path.Combine(Directory.GetCurrentDirectory(), SecondNativeLibraryFileName),
FilePrivatePart = 2,
FileVersion = "0.65535.0.2",
InternalName = "SecondNa.dll",
IsDebug = false,
IsPatched = false,
IsPrivateBuild = false,
IsPreRelease = false,
IsSpecialBuild = false,
Language = GetFileVersionLanguage(0x0400),//Process Default Language
LegalCopyright = "Copyright (C) 1 - 2014",
LegalTrademarks = "",
OriginalFilename = "SecondNa.dll",
PrivateBuild = "",
ProductBuildPart = 0,
ProductMajorPart = 1,
ProductMinorPart = 0,
ProductName = "Unknown_Product_Name",
ProductPrivatePart = 1,
ProductVersion = "1.0.0.1",
SpecialBuild = "",
});
}
[Fact]
public void FileVersionInfo_CustomManagedAssembly()
{
// Assembly1.dll
VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName), new MyFVI()
{
Comments = "Have you played a Contoso amusement device today?",
CompanyName = "The name of the company.",
FileBuildPart = 2,
FileDescription = "My File",
FileMajorPart = 4,
FileMinorPart = 3,
FileName = Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName),
FilePrivatePart = 1,
FileVersion = "4.3.2.1",
InternalName = TestAssemblyFileName,
IsDebug = false,
IsPatched = false,
IsPrivateBuild = false,
IsPreRelease = false,
IsSpecialBuild = false,
Language = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? GetFileVersionLanguage(0x0000) : "Language Neutral",
LegalCopyright = "Copyright, you betcha!",
LegalTrademarks = "TM",
OriginalFilename = TestAssemblyFileName,
PrivateBuild = "",
ProductBuildPart = 2,
ProductMajorPart = 4,
ProductMinorPart = 3,
ProductName = "The greatest product EVER",
ProductPrivatePart = 1,
ProductVersion = "4.3.2.1",
SpecialBuild = "",
});
}
[Fact]
public void FileVersionInfo_EmptyFVI()
{
// Assembly1.cs
VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestCsFileName), new MyFVI()
{
Comments = null,
CompanyName = null,
FileBuildPart = 0,
FileDescription = null,
FileMajorPart = 0,
FileMinorPart = 0,
FileName = Path.Combine(Directory.GetCurrentDirectory(), TestCsFileName),
FilePrivatePart = 0,
FileVersion = null,
InternalName = null,
IsDebug = false,
IsPatched = false,
IsPrivateBuild = false,
IsPreRelease = false,
IsSpecialBuild = false,
Language = null,
LegalCopyright = null,
LegalTrademarks = null,
OriginalFilename = null,
PrivateBuild = null,
ProductBuildPart = 0,
ProductMajorPart = 0,
ProductMinorPart = 0,
ProductName = null,
ProductPrivatePart = 0,
ProductVersion = null,
SpecialBuild = null,
});
}
[Fact]
public void FileVersionInfo_FileNotFound()
{
Assert.Throws<FileNotFoundException>(() =>
FileVersionInfo.GetVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestNotFoundFileName)));
}
// Additional Tests Wanted:
// [] File exists but we don't have permission to read it
// [] DLL has unknown codepage info
// [] DLL language/codepage is 8-hex-digits (locale > 0x999) (different codepath)
private void VerifyVersionInfo(String filePath, MyFVI expected)
{
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(filePath);
Assert.Equal(expected.Comments, fvi.Comments);
Assert.Equal(expected.CompanyName, fvi.CompanyName);
Assert.Equal(expected.FileBuildPart, fvi.FileBuildPart);
Assert.Equal(expected.FileDescription, fvi.FileDescription);
Assert.Equal(expected.FileMajorPart, fvi.FileMajorPart);
Assert.Equal(expected.FileMinorPart, fvi.FileMinorPart);
Assert.Equal(expected.FileName, fvi.FileName);
Assert.Equal(expected.FilePrivatePart, fvi.FilePrivatePart);
Assert.Equal(expected.FileVersion, fvi.FileVersion);
Assert.Equal(expected.InternalName, fvi.InternalName);
Assert.Equal(expected.IsDebug, fvi.IsDebug);
Assert.Equal(expected.IsPatched, fvi.IsPatched);
Assert.Equal(expected.IsPrivateBuild, fvi.IsPrivateBuild);
Assert.Equal(expected.IsPreRelease, fvi.IsPreRelease);
Assert.Equal(expected.IsSpecialBuild, fvi.IsSpecialBuild);
Assert.Contains(fvi.Language, new[] { expected.Language, expected.Language2 });
Assert.Equal(expected.LegalCopyright, fvi.LegalCopyright);
Assert.Equal(expected.LegalTrademarks, fvi.LegalTrademarks);
Assert.Equal(expected.OriginalFilename, fvi.OriginalFilename);
Assert.Equal(expected.PrivateBuild, fvi.PrivateBuild);
Assert.Equal(expected.ProductBuildPart, fvi.ProductBuildPart);
Assert.Equal(expected.ProductMajorPart, fvi.ProductMajorPart);
Assert.Equal(expected.ProductMinorPart, fvi.ProductMinorPart);
Assert.Equal(expected.ProductName, fvi.ProductName);
Assert.Equal(expected.ProductPrivatePart, fvi.ProductPrivatePart);
Assert.Equal(expected.ProductVersion, fvi.ProductVersion);
Assert.Equal(expected.SpecialBuild, fvi.SpecialBuild);
//ToString
String nl = Environment.NewLine;
Assert.Equal("File: " + fvi.FileName + nl +
"InternalName: " + fvi.InternalName + nl +
"OriginalFilename: " + fvi.OriginalFilename + nl +
"FileVersion: " + fvi.FileVersion + nl +
"FileDescription: " + fvi.FileDescription + nl +
"Product: " + fvi.ProductName + nl +
"ProductVersion: " + fvi.ProductVersion + nl +
"Debug: " + fvi.IsDebug.ToString() + nl +
"Patched: " + fvi.IsPatched.ToString() + nl +
"PreRelease: " + fvi.IsPreRelease.ToString() + nl +
"PrivateBuild: " + fvi.IsPrivateBuild.ToString() + nl +
"SpecialBuild: " + fvi.IsSpecialBuild.ToString() + nl +
"Language: " + fvi.Language + nl,
fvi.ToString());
}
internal class MyFVI
{
public string Comments;
public string CompanyName;
public int FileBuildPart;
public string FileDescription;
public int FileMajorPart;
public int FileMinorPart;
public string FileName;
public int FilePrivatePart;
public string FileVersion;
public string InternalName;
public bool IsDebug;
public bool IsPatched;
public bool IsPrivateBuild;
public bool IsPreRelease;
public bool IsSpecialBuild;
public string Language;
public string Language2;
public string LegalCopyright;
public string LegalTrademarks;
public string OriginalFilename;
public string PrivateBuild;
public int ProductBuildPart;
public int ProductMajorPart;
public int ProductMinorPart;
public string ProductName;
public int ProductPrivatePart;
public string ProductVersion;
public string SpecialBuild;
}
static string GetUnicodeString(String str)
{
if (str == null)
return "<null>";
StringBuilder buffer = new StringBuilder();
buffer.Append("\"");
for (int i = 0; i < str.Length; i++)
{
char ch = str[i];
if (ch == '\r')
{
buffer.Append("\\r");
}
else if (ch == '\n')
{
buffer.Append("\\n");
}
else if (ch == '\\')
{
buffer.Append("\\");
}
else if (ch == '\"')
{
buffer.Append("\\\"");
}
else if (ch == '\'')
{
buffer.Append("\\\'");
}
else if (ch < 0x20 || ch >= 0x7f)
{
buffer.Append("\\u");
buffer.Append(((int)ch).ToString("x4"));
}
else
{
buffer.Append(ch);
}
}
buffer.Append("\"");
return (buffer.ToString());
}
private static string GetFileVersionLanguage(uint langid)
{
var lang = new StringBuilder(256);
Interop.mincore.VerLanguageName(langid, lang, (uint)lang.Capacity);
return lang.ToString();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace System.Tests
{
public static partial class AttributeTests
{
[Fact]
public static void DefaultEquality()
{
var a1 = new ParentAttribute { Prop = 1 };
var a2 = new ParentAttribute { Prop = 42 };
var a3 = new ParentAttribute { Prop = 1 };
var d1 = new ChildAttribute { Prop = 1 };
var d2 = new ChildAttribute { Prop = 42 };
var d3 = new ChildAttribute { Prop = 1 };
var s1 = new GrandchildAttribute { Prop = 1 };
var s2 = new GrandchildAttribute { Prop = 42 };
var s3 = new GrandchildAttribute { Prop = 1 };
var f1 = new ChildAttributeWithField { Prop = 1 };
var f2 = new ChildAttributeWithField { Prop = 42 };
var f3 = new ChildAttributeWithField { Prop = 1 };
Assert.NotEqual(a1, a2);
Assert.NotEqual(a2, a3);
Assert.Equal(a1, a3);
// The implementation of Attribute.Equals uses reflection to
// enumerate fields. On .NET core, we add `BindingFlags.DeclaredOnly`
// to fix a bug where an instance of a subclass of an attribute can
// be equal to an instance of the parent class.
// See https://github.com/dotnet/coreclr/pull/6240
Assert.False(d1.Equals(d2));
Assert.False(d2.Equals(d3));
Assert.Equal(d1, d3);
Assert.False(s1.Equals(s2));
Assert.False(s2.Equals(s3));
Assert.Equal(s1, s3);
Assert.False(f1.Equals(f2));
Assert.False(f2.Equals(f3));
Assert.Equal(f1, f3);
Assert.NotEqual(d1, a1);
Assert.NotEqual(d2, a2);
Assert.NotEqual(d3, a3);
Assert.NotEqual(d1, a3);
Assert.NotEqual(d3, a1);
Assert.NotEqual(d1, s1);
Assert.NotEqual(d2, s2);
Assert.NotEqual(d3, s3);
Assert.NotEqual(d1, s3);
Assert.NotEqual(d3, s1);
Assert.NotEqual(f1, a1);
Assert.NotEqual(f2, a2);
Assert.NotEqual(f3, a3);
Assert.NotEqual(f1, a3);
Assert.NotEqual(f3, a1);
}
[Fact]
public static void DefaultHashCode()
{
var a1 = new ParentAttribute { Prop = 1 };
var a2 = new ParentAttribute { Prop = 42 };
var a3 = new ParentAttribute { Prop = 1 };
var d1 = new ChildAttribute { Prop = 1 };
var d2 = new ChildAttribute { Prop = 42 };
var d3 = new ChildAttribute { Prop = 1 };
var s1 = new GrandchildAttribute { Prop = 1 };
var s2 = new GrandchildAttribute { Prop = 42 };
var s3 = new GrandchildAttribute { Prop = 1 };
var f1 = new ChildAttributeWithField { Prop = 1 };
var f2 = new ChildAttributeWithField { Prop = 42 };
var f3 = new ChildAttributeWithField { Prop = 1 };
Assert.NotEqual(0, a1.GetHashCode());
Assert.NotEqual(0, a2.GetHashCode());
Assert.NotEqual(0, a3.GetHashCode());
Assert.NotEqual(0, d1.GetHashCode());
Assert.NotEqual(0, d2.GetHashCode());
Assert.NotEqual(0, d3.GetHashCode());
Assert.NotEqual(0, s1.GetHashCode());
Assert.NotEqual(0, s2.GetHashCode());
Assert.NotEqual(0, s3.GetHashCode());
Assert.Equal(0, f1.GetHashCode());
Assert.Equal(0, f2.GetHashCode());
Assert.Equal(0, f3.GetHashCode());
Assert.NotEqual(a1.GetHashCode(), a2.GetHashCode());
Assert.NotEqual(a2.GetHashCode(), a3.GetHashCode());
Assert.Equal(a1.GetHashCode(), a3.GetHashCode());
// The implementation of Attribute.GetHashCode uses reflection to
// enumerate fields. On .NET core, we add `BindingFlags.DeclaredOnly`
// to fix a bug where the hash code of a subclass of an attribute can
// be equal to an instance of the parent class.
// See https://github.com/dotnet/coreclr/pull/6240
Assert.False(s1.GetHashCode().Equals(s2.GetHashCode()));
Assert.False(s2.GetHashCode().Equals(s3.GetHashCode()));
Assert.Equal(s1.GetHashCode(), s3.GetHashCode());
Assert.False(d1.GetHashCode().Equals(d2.GetHashCode()));
Assert.False(d2.GetHashCode().Equals(d3.GetHashCode()));
Assert.Equal(d1.GetHashCode(), d3.GetHashCode());
Assert.Equal(f1.GetHashCode(), f2.GetHashCode());
Assert.Equal(f2.GetHashCode(), f3.GetHashCode());
Assert.Equal(f1.GetHashCode(), f3.GetHashCode());
Assert.True(d1.GetHashCode().Equals(a1.GetHashCode()));
Assert.True(d2.GetHashCode().Equals(a2.GetHashCode()));
Assert.True(d3.GetHashCode().Equals(a3.GetHashCode()));
Assert.True(d1.GetHashCode().Equals(a3.GetHashCode()));
Assert.True(d3.GetHashCode().Equals(a1.GetHashCode()));
Assert.True(d1.GetHashCode().Equals(s1.GetHashCode()));
Assert.True(d2.GetHashCode().Equals(s2.GetHashCode()));
Assert.True(d3.GetHashCode().Equals(s3.GetHashCode()));
Assert.True(d1.GetHashCode().Equals(s3.GetHashCode()));
Assert.True(d3.GetHashCode().Equals(s1.GetHashCode()));
Assert.NotEqual(f1.GetHashCode(), a1.GetHashCode());
Assert.NotEqual(f2.GetHashCode(), a2.GetHashCode());
Assert.NotEqual(f3.GetHashCode(), a3.GetHashCode());
Assert.NotEqual(f1.GetHashCode(), a3.GetHashCode());
Assert.NotEqual(f3.GetHashCode(), a1.GetHashCode());
}
class ParentAttribute : Attribute
{
public int Prop {get;set;}
}
class ChildAttribute : ParentAttribute { }
class GrandchildAttribute : ChildAttribute { }
class ChildAttributeWithField : ParentAttribute
{
public int Field = 0;
}
[Fact]
[StringValue("\uDFFF")]
public static void StringArgument_InvalidCodeUnits_FallbackUsed()
{
MethodInfo thisMethod = typeof(AttributeTests).GetTypeInfo().GetDeclaredMethod("StringArgument_InvalidCodeUnits_FallbackUsed");
Assert.NotNull(thisMethod);
CustomAttributeData cad = thisMethod.CustomAttributes.Where(ca => ca.AttributeType == typeof(StringValueAttribute)).FirstOrDefault();
Assert.NotNull(cad);
string stringArg = cad.ConstructorArguments[0].Value as string;
Assert.NotNull(stringArg);
Assert.Equal("\uFFFD\uFFFD", stringArg);
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { new StringValueAttribute("hello"), new StringValueAttribute("hello"), true, true };
yield return new object[] { new StringValueAttribute("hello"), new StringValueAttribute("foo"), false, false };
yield return new object[] { new StringValueIntValueAttribute("hello", 1), new StringValueIntValueAttribute("hello", 1), true, true };
yield return new object[] { new StringValueIntValueAttribute("hello", 1), new StringValueIntValueAttribute("hello", 2), false, true }; // GetHashCode() ignores the int value
yield return new object[] { new EmptyAttribute(), new EmptyAttribute(), true, true };
yield return new object[] { new StringValueAttribute("hello"), new StringValueIntValueAttribute("hello", 1), false, true }; // GetHashCode() ignores the int value
yield return new object[] { new StringValueAttribute("hello"), "hello", false, false };
yield return new object[] { new StringValueAttribute("hello"), null, false, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public static void Equals(Attribute attr1, object obj, bool expected, bool hashEqualityExpected)
{
Assert.Equal(expected, attr1.Equals(obj));
Attribute attr2 = obj as Attribute;
if (attr2 != null)
{
Assert.Equal(hashEqualityExpected, attr1.GetHashCode() == attr2.GetHashCode());
}
}
[AttributeUsage(AttributeTargets.Method)]
private sealed class StringValueAttribute : Attribute
{
public string StringValue;
public StringValueAttribute(string stringValue)
{
StringValue = stringValue;
}
}
private sealed class StringValueIntValueAttribute : Attribute
{
public string StringValue;
private int IntValue;
public StringValueIntValueAttribute(string stringValue, int intValue)
{
StringValue = stringValue;
IntValue = intValue;
}
}
[AttributeUsage(AttributeTargets.Method)]
private sealed class EmptyAttribute : Attribute { }
[Fact]
public static void ValidateDefaults()
{
StringValueAttribute sav = new StringValueAttribute("test");
Assert.False(sav.IsDefaultAttribute());
Assert.Equal(sav.GetType(), sav.TypeId);
Assert.True(sav.Match(sav));
}
}
}
| |
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 NLogReader.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Messaging;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using UnitTests.StorageTests;
using Xunit;
namespace UnitTests.MembershipTests
{
public abstract class MembershipTableTestsBase : IDisposable, IClassFixture<ConnectionStringFixture>
{
private static readonly string hostName = Dns.GetHostName();
private readonly TraceLogger logger;
private readonly IMembershipTable membershipTable;
private readonly IGatewayListProvider gatewayListProvider;
private readonly string deploymentId;
protected const string testDatabaseName = "OrleansMembershipTest";//for relational storage
protected MembershipTableTestsBase(ConnectionStringFixture fixture)
{
TraceLogger.Initialize(new NodeConfiguration());
logger = TraceLogger.GetLogger(GetType().Name, TraceLogger.LoggerType.Application);
deploymentId = "test-" + Guid.NewGuid();
logger.Info("DeploymentId={0}", deploymentId);
lock (fixture.SyncRoot)
{
if (fixture.ConnectionString == null)
fixture.ConnectionString = GetConnectionString();
}
var globalConfiguration = new GlobalConfiguration
{
DeploymentId = deploymentId,
AdoInvariant = GetAdoInvariant(),
DataConnectionString = fixture.ConnectionString
};
membershipTable = CreateMembershipTable(logger);
membershipTable.InitializeMembershipTable(globalConfiguration, true, logger).WithTimeout(TimeSpan.FromMinutes(1)).Wait();
var clientConfiguration = new ClientConfiguration
{
DeploymentId = globalConfiguration.DeploymentId,
AdoInvariant = globalConfiguration.AdoInvariant,
DataConnectionString = globalConfiguration.DataConnectionString
};
gatewayListProvider = CreateGatewayListProvider(logger);
gatewayListProvider.InitializeGatewayListProvider(clientConfiguration, logger).WithTimeout(TimeSpan.FromMinutes(1)).Wait();
}
public void Dispose()
{
if (membershipTable != null && SiloInstanceTableTestConstants.DeleteEntriesAfterTest)
{
membershipTable.DeleteMembershipTableEntries(deploymentId).Wait();
}
}
protected abstract IGatewayListProvider CreateGatewayListProvider(TraceLogger logger);
protected abstract IMembershipTable CreateMembershipTable(TraceLogger logger);
protected abstract string GetConnectionString();
protected virtual string GetAdoInvariant()
{
return null;
}
protected async Task MembershipTable_GetGateways()
{
var membershipEntries = Enumerable.Range(0, 10).Select(i => CreateMembershipEntryForTest()).ToArray();
membershipEntries[3].Status = SiloStatus.Active;
membershipEntries[3].ProxyPort = 0;
membershipEntries[5].Status = SiloStatus.Active;
membershipEntries[9].Status = SiloStatus.Active;
var data = await membershipTable.ReadAll();
Assert.NotNull(data);
Assert.Equal(0, data.Members.Count);
var version = data.Version;
foreach (var membershipEntry in membershipEntries)
{
Assert.True(await membershipTable.InsertRow(membershipEntry, version));
version = (await membershipTable.ReadRow(membershipEntry.SiloAddress)).Version;
}
var gateways = await gatewayListProvider.GetGateways();
var entries = new List<string>(gateways.Select(g => g.ToString()));
Assert.True(entries.Contains(membershipEntries[5].SiloAddress.ToGatewayUri().ToString()));
Assert.True(entries.Contains(membershipEntries[9].SiloAddress.ToGatewayUri().ToString()));
}
protected async Task MembershipTable_ReadAll_EmptyTable()
{
var data = await membershipTable.ReadAll();
Assert.NotNull(data);
logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data);
Assert.Equal(0, data.Members.Count);
Assert.NotNull(data.Version.VersionEtag);
Assert.Equal(0, data.Version.Version);
}
protected async Task MembershipTable_InsertRow()
{
var membershipEntry = CreateMembershipEntryForTest();
var data = await membershipTable.ReadAll();
Assert.NotNull(data);
Assert.Equal(0, data.Members.Count);
bool ok = await membershipTable.InsertRow(membershipEntry, data.Version.Next());
Assert.True(ok, "InsertRow failed");
data = await membershipTable.ReadAll();
Assert.Equal(1, data.Version.Version);
Assert.Equal(1, data.Members.Count);
}
protected async Task MembershipTable_ReadRow_Insert_Read()
{
MembershipTableData data = await membershipTable.ReadAll();
logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data);
Assert.Equal(0, data.Members.Count);
TableVersion newTableVersion = data.Version.Next();
MembershipEntry newEntry = CreateMembershipEntryForTest();
bool ok = await membershipTable.InsertRow(newEntry, newTableVersion);
Assert.True(ok, "InsertRow failed");
ok = await membershipTable.InsertRow(newEntry, newTableVersion);
Assert.False(ok, "InsertRow should have failed - same entry, old table version");
ok = await membershipTable.InsertRow(CreateMembershipEntryForTest(), newTableVersion);
Assert.False(ok, "InsertRow should have failed - new entry, old table version");
data = await membershipTable.ReadAll();
Assert.Equal(1, data.Version.Version);
var nextTableVersion = data.Version.Next();
ok = await membershipTable.InsertRow(newEntry, nextTableVersion);
Assert.False(ok, "InsertRow should have failed - duplicate entry");
data = await membershipTable.ReadAll();
Assert.Equal(1, data.Members.Count);
data = await membershipTable.ReadRow(newEntry.SiloAddress);
Assert.Equal(newTableVersion.Version, data.Version.Version);
logger.Info("Membership.ReadRow returned VableVersion={0} Data={1}", data.Version, data);
Assert.Equal(1, data.Members.Count);
Assert.NotNull(data.Version.VersionEtag);
Assert.NotEqual(newTableVersion.VersionEtag, data.Version.VersionEtag);
Assert.Equal(newTableVersion.Version, data.Version.Version);
var membershipEntry = data.Members[0].Item1;
string eTag = data.Members[0].Item2;
logger.Info("Membership.ReadRow returned MembershipEntry ETag={0} Entry={1}", eTag, membershipEntry);
Assert.NotNull(eTag);
Assert.NotNull(membershipEntry);
}
protected async Task MembershipTable_ReadAll_Insert_ReadAll()
{
MembershipTableData data = await membershipTable.ReadAll();
logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data);
Assert.Equal(0, data.Members.Count);
TableVersion newTableVersion = data.Version.Next();
MembershipEntry newEntry = CreateMembershipEntryForTest();
bool ok = await membershipTable.InsertRow(newEntry, newTableVersion);
Assert.True(ok, "InsertRow failed");
data = await membershipTable.ReadAll();
logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data);
Assert.Equal(1, data.Members.Count);
Assert.NotNull(data.Version.VersionEtag);
Assert.NotEqual(newTableVersion.VersionEtag, data.Version.VersionEtag);
Assert.Equal(newTableVersion.Version, data.Version.Version);
var membershipEntry = data.Members[0].Item1;
string eTag = data.Members[0].Item2;
logger.Info("Membership.ReadAll returned MembershipEntry ETag={0} Entry={1}", eTag, membershipEntry);
Assert.NotNull(eTag);
Assert.NotNull(membershipEntry);
}
protected async Task MembershipTable_UpdateRow()
{
var tableData = await membershipTable.ReadAll();
Assert.NotNull(tableData.Version);
Assert.Equal(0, tableData.Version.Version);
Assert.Equal(0, tableData.Members.Count);
for (int i = 1; i < 10; i++)
{
var siloEntry = CreateMembershipEntryForTest();
siloEntry.SuspectTimes =
new List<Tuple<SiloAddress, DateTime>>
{
new Tuple<SiloAddress, DateTime>(CreateSiloAddressForTest(), GetUtcNowWithSecondsResolution().AddSeconds(1)),
new Tuple<SiloAddress, DateTime>(CreateSiloAddressForTest(), GetUtcNowWithSecondsResolution().AddSeconds(2))
};
TableVersion tableVersion = tableData.Version.Next();
logger.Info("Calling InsertRow with Entry = {0} TableVersion = {1}", siloEntry, tableVersion);
bool ok = await membershipTable.InsertRow(siloEntry, tableVersion);
Assert.True(ok, "InsertRow failed");
tableData = await membershipTable.ReadAll();
var etagBefore = tableData.Get(siloEntry.SiloAddress).Item2;
Assert.NotNull(etagBefore);
logger.Info("Calling UpdateRow with Entry = {0} correct eTag = {1} old version={2}", siloEntry,
etagBefore, tableVersion);
ok = await membershipTable.UpdateRow(siloEntry, etagBefore, tableVersion);
Assert.False(ok, $"row update should have failed - Table Data = {tableData}");
tableData = await membershipTable.ReadAll();
tableVersion = tableData.Version.Next();
logger.Info("Calling UpdateRow with Entry = {0} correct eTag = {1} correct version={2}", siloEntry,
etagBefore, tableVersion);
ok = await membershipTable.UpdateRow(siloEntry, etagBefore, tableVersion);
Assert.True(ok, $"UpdateRow failed - Table Data = {tableData}");
logger.Info("Calling UpdateRow with Entry = {0} old eTag = {1} old version={2}", siloEntry,
etagBefore, tableVersion);
ok = await membershipTable.UpdateRow(siloEntry, etagBefore, tableVersion);
Assert.False(ok, $"row update should have failed - Table Data = {tableData}");
tableData = await membershipTable.ReadAll();
var tuple = tableData.Get(siloEntry.SiloAddress);
Assert.Equal(tuple.Item1.ToFullString(true), siloEntry.ToFullString(true));
var etagAfter = tuple.Item2;
logger.Info("Calling UpdateRow with Entry = {0} correct eTag = {1} old version={2}", siloEntry,
etagAfter, tableVersion);
ok = await membershipTable.UpdateRow(siloEntry, etagAfter, tableVersion);
Assert.False(ok, $"row update should have failed - Table Data = {tableData}");
//var nextTableVersion = tableData.Version.Next();
//logger.Info("Calling UpdateRow with Entry = {0} old eTag = {1} correct version={2}", siloEntry,
// etagBefore, nextTableVersion);
//ok = await membershipTable.UpdateRow(siloEntry, etagBefore, nextTableVersion);
//Assert.False(ok, $"row update should have failed - Table Data = {tableData}");
tableData = await membershipTable.ReadAll();
etagBefore = etagAfter;
etagAfter = tableData.Get(siloEntry.SiloAddress).Item2;
Assert.Equal(etagBefore, etagAfter);
Assert.NotNull(tableData.Version);
Assert.Equal(tableVersion.Version, tableData.Version.Version);
Assert.Equal(i, tableData.Members.Count);
}
}
protected async Task MembershipTable_UpdateRowInParallel()
{
var tableData = await membershipTable.ReadAll();
var data = CreateMembershipEntryForTest();
var newTableVer = tableData.Version.Next();
var insertions = Task.WhenAll(Enumerable.Range(1, 20).Select(i => membershipTable.InsertRow(data, newTableVer)));
Assert.True((await insertions).Single(x => x), "InsertRow failed");
await Task.WhenAll(Enumerable.Range(1, 19).Select(async i =>
{
bool done;
do
{
var updatedTableData = await membershipTable.ReadAll();
var updatedRow = updatedTableData.Get(data.SiloAddress);
var tableVersion = updatedTableData.Version.Next();
await Task.Delay(10);
done = await membershipTable.UpdateRow(updatedRow.Item1, updatedRow.Item2, tableVersion);
} while (!done);
})).WithTimeout(TimeSpan.FromSeconds(30));
tableData = await membershipTable.ReadAll();
Assert.NotNull(tableData.Version);
Assert.Equal(20, tableData.Version.Version);
Assert.Equal(1, tableData.Members.Count);
}
private static int generation;
// Utility methods
private static MembershipEntry CreateMembershipEntryForTest()
{
SiloAddress siloAddress = CreateSiloAddressForTest();
var membershipEntry = new MembershipEntry
{
SiloAddress = siloAddress,
HostName = hostName,
Status = SiloStatus.Joining,
ProxyPort = siloAddress.Endpoint.Port,
StartTime = GetUtcNowWithSecondsResolution(),
IAmAliveTime = GetUtcNowWithSecondsResolution()
};
return membershipEntry;
}
private static DateTime GetUtcNowWithSecondsResolution()
{
var now = DateTime.UtcNow;
return new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
}
private static SiloAddress CreateSiloAddressForTest()
{
var siloAddress = SiloAddress.NewLocalAddress(Interlocked.Increment(ref generation));
siloAddress.Endpoint.Port = 12345;
return siloAddress;
}
}
}
| |
using System.Collections.Generic;
using System.Text;
namespace Lucene.Net.Search
{
/*
* 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using BooleanWeight = Lucene.Net.Search.BooleanQuery.BooleanWeight;
/* Description from Doug Cutting (excerpted from
* LUCENE-1483):
*
* BooleanScorer uses an array to score windows of
* 2K docs. So it scores docs 0-2K first, then docs 2K-4K,
* etc. For each window it iterates through all query terms
* and accumulates a score in table[doc%2K]. It also stores
* in the table a bitmask representing which terms
* contributed to the score. Non-zero scores are chained in
* a linked list. At the end of scoring each window it then
* iterates through the linked list and, if the bitmask
* matches the boolean constraints, collects a hit. For
* boolean queries with lots of frequent terms this can be
* much faster, since it does not need to update a priority
* queue for each posting, instead performing constant-time
* operations per posting. The only downside is that it
* results in hits being delivered out-of-order within the
* window, which means it cannot be nested within other
* scorers. But it works well as a top-level scorer.
*
* The new BooleanScorer2 implementation instead works by
* merging priority queues of postings, albeit with some
* clever tricks. For example, a pure conjunction (all terms
* required) does not require a priority queue. Instead it
* sorts the posting streams at the start, then repeatedly
* skips the first to to the last. If the first ever equals
* the last, then there's a hit. When some terms are
* required and some terms are optional, the conjunction can
* be evaluated first, then the optional terms can all skip
* to the match and be added to the score. Thus the
* conjunction can reduce the number of priority queue
* updates for the optional terms. */
public sealed class BooleanScorer : BulkScorer
{
private sealed class BooleanScorerCollector : Collector
{
internal BucketTable BucketTable;
internal int Mask;
internal Scorer Scorer_Renamed;
public BooleanScorerCollector(int mask, BucketTable bucketTable)
{
this.Mask = mask;
this.BucketTable = bucketTable;
}
public override void Collect(int doc)
{
BucketTable table = BucketTable;
int i = doc & BucketTable.MASK;
Bucket bucket = table.Buckets[i];
if (bucket.Doc != doc) // invalid bucket
{
bucket.Doc = doc; // set doc
bucket.Score = Scorer_Renamed.Score(); // initialize score
bucket.Bits = Mask; // initialize mask
bucket.Coord = 1; // initialize coord
bucket.Next = table.First; // push onto valid list
table.First = bucket;
} // valid bucket
else
{
bucket.Score += Scorer_Renamed.Score(); // increment score
bucket.Bits |= Mask; // add bits in mask
bucket.Coord++; // increment coord
}
}
public override AtomicReaderContext NextReader
{
set
{
// not needed by this implementation
}
}
public override Scorer Scorer
{
set
{
this.Scorer_Renamed = value;
}
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
internal sealed class Bucket
{
internal int Doc = -1; // tells if bucket is valid
internal double Score; // incremental score
// TODO: break out bool anyProhibited, int
// numRequiredMatched; then we can remove 32 limit on
// required clauses
internal int Bits; // used for bool constraints
internal int Coord; // count of terms in score
internal Bucket Next; // next valid bucket
}
/// <summary>
/// A simple hash table of document scores within a range. </summary>
internal sealed class BucketTable
{
public static readonly int SIZE = 1 << 11;
public static readonly int MASK = SIZE - 1;
internal readonly Bucket[] Buckets = new Bucket[SIZE];
internal Bucket First = null; // head of valid list
public BucketTable()
{
// Pre-fill to save the lazy init when collecting
// each sub:
for (int idx = 0; idx < SIZE; idx++)
{
Buckets[idx] = new Bucket();
}
}
public Collector NewCollector(int mask)
{
return new BooleanScorerCollector(mask, this);
}
public int Size()
{
return SIZE;
}
}
internal sealed class SubScorer
{
public BulkScorer Scorer;
// TODO: re-enable this if BQ ever sends us required clauses
//public boolean required = false;
public bool Prohibited;
public Collector Collector;
public SubScorer Next;
public bool More;
public SubScorer(BulkScorer scorer, bool required, bool prohibited, Collector collector, SubScorer next)
{
if (required)
{
throw new System.ArgumentException("this scorer cannot handle required=true");
}
this.Scorer = scorer;
this.More = true;
// TODO: re-enable this if BQ ever sends us required clauses
//this.required = required;
this.Prohibited = prohibited;
this.Collector = collector;
this.Next = next;
}
}
private SubScorer Scorers = null;
private BucketTable bucketTable = new BucketTable();
private readonly float[] CoordFactors;
// TODO: re-enable this if BQ ever sends us required clauses
//private int requiredMask = 0;
private readonly int MinNrShouldMatch;
private int End;
private Bucket Current;
// Any time a prohibited clause matches we set bit 0:
private const int PROHIBITED_MASK = 1;
private readonly Weight Weight;
public BooleanScorer(BooleanWeight weight, bool disableCoord, int minNrShouldMatch, IList<BulkScorer> optionalScorers, IList<BulkScorer> prohibitedScorers, int maxCoord)
{
this.MinNrShouldMatch = minNrShouldMatch;
this.Weight = weight;
foreach (BulkScorer scorer in optionalScorers)
{
Scorers = new SubScorer(scorer, false, false, bucketTable.NewCollector(0), Scorers);
}
foreach (BulkScorer scorer in prohibitedScorers)
{
Scorers = new SubScorer(scorer, false, true, bucketTable.NewCollector(PROHIBITED_MASK), Scorers);
}
CoordFactors = new float[optionalScorers.Count + 1];
for (int i = 0; i < CoordFactors.Length; i++)
{
CoordFactors[i] = disableCoord ? 1.0f : weight.Coord(i, maxCoord);
}
}
public override bool Score(Collector collector, int max)
{
bool more;
Bucket tmp;
FakeScorer fs = new FakeScorer();
// The internal loop will set the score and doc before calling collect.
collector.Scorer = fs;
do
{
bucketTable.First = null;
while (Current != null) // more queued
{
// check prohibited & required
if ((Current.Bits & PROHIBITED_MASK) == 0)
{
// TODO: re-enable this if BQ ever sends us required
// clauses
//&& (current.bits & requiredMask) == requiredMask) {
// NOTE: Lucene always passes max =
// Integer.MAX_VALUE today, because we never embed
// a BooleanScorer inside another (even though
// that should work)... but in theory an outside
// app could pass a different max so we must check
// it:
if (Current.Doc >= max)
{
tmp = Current;
Current = Current.Next;
tmp.Next = bucketTable.First;
bucketTable.First = tmp;
continue;
}
if (Current.Coord >= MinNrShouldMatch)
{
fs.score = (float)(Current.Score * CoordFactors[Current.Coord]);
fs.doc = Current.Doc;
fs.freq = Current.Coord;
collector.Collect(Current.Doc);
}
}
Current = Current.Next; // pop the queue
}
if (bucketTable.First != null)
{
Current = bucketTable.First;
bucketTable.First = Current.Next;
return true;
}
// refill the queue
more = false;
End += BucketTable.SIZE;
for (SubScorer sub = Scorers; sub != null; sub = sub.Next)
{
if (sub.More)
{
sub.More = sub.Scorer.Score(sub.Collector, End);
more |= sub.More;
}
}
Current = bucketTable.First;
} while (Current != null || more);
return false;
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("boolean(");
for (SubScorer sub = Scorers; sub != null; sub = sub.Next)
{
buffer.Append(sub.Scorer.ToString());
buffer.Append(" ");
}
buffer.Append(")");
return buffer.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Overflow.Test.Fakes;
using Overflow.Test.TestingInfrastructure;
using Overflow.Utilities;
using Xunit;
namespace Overflow.Test
{
public class OperationTests : TestBase
{
[Fact]
public void Executing_an_operation_calls_the_OnExecute_method()
{
var sut = new FakeOperation();
sut.Execute();
Assert.True(sut.HasExecuted);
}
[Fact]
public void Executing_an_that_does_not_override_the_OnExecute_method_does_nothing()
{
var sut = new TestOperation();
sut.Execute();
}
[Fact]
public void Operations_do_not_have_any_child_operations_by_default()
{
var sut = new TestOperation();
var result = sut.GetChildOperations();
Assert.False(result.Any());
}
[Fact]
public void Executing_an_operation_executes_each_child_operation_as_well()
{
var op1 = new FakeOperation();
var op2 = new FakeOperation();
var sut = new FakeOperation(op1, op2);
sut.Execute();
Assert.Equal(3, FakeOperation.ExecutedOperations.Count);
Assert.Equal(sut, FakeOperation.ExecutedOperations[0]);
Assert.Equal(op1, FakeOperation.ExecutedOperations[1]);
Assert.Equal(op2, FakeOperation.ExecutedOperations[2]);
}
[Theory, AutoMoqData]
public void You_can_create_operation_with_a_configuration_containing_a_resolver(IOperationResolver resolver)
{
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = resolver };
var result = Operation.Create<TestOperation>(correctConfiguration);
Assert.NotNull(result);
}
[Fact]
public void Creating_an_operation_initializes_it_with_the_configuration_of_the_parent_operation()
{
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = new SimpleOperationResolver() };
var result = (TestOperation)Operation.Create<TestOperation>(correctConfiguration);
Assert.Equal(correctConfiguration, result.Configuration);
}
[Fact]
public void You_cannot_create_operations_when_the_workflow_configuration_is_not_set()
{
Assert.Throws<InvalidOperationException>(() => Operation.Create<TestOperation>(null));
}
[Theory, AutoMoqData]
public void You_cannot_create_operations_when_the_operation_resolver_is_not_set(WorkflowConfiguration configuration)
{
Assert.Throws<InvalidOperationException>(() => Operation.Create<TestOperation>(configuration));
}
[Fact]
public void You_can_create_a_new_operation_from_an_initialized_operation_instance()
{
var resolver = new SimpleOperationResolver();
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = resolver };
var sut = new FakeOperation();
sut.Initialize(correctConfiguration);
var result = sut.PublicCreate<TestOperation>() as TestOperation;
Assert.NotNull(result);
}
[Theory, AutoMoqData]
public void You_can_create_a_new_input_operation_from_an_initialized_operation_instance(object input)
{
var resolver = new SimpleOperationResolver();
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = resolver };
var sut = new FakeOperation();
sut.Initialize(correctConfiguration);
var result = sut.PublicCreate<TestInputOperation, object>(input) as TestInputOperation;
Assert.NotNull(result);
}
[Theory, AutoMoqData]
public void Created_input_operations_are_provided_with_one_input_value(object input)
{
var resolver = new SimpleOperationResolver();
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = resolver };
var sut = new FakeOperation();
sut.Initialize(correctConfiguration);
var result = sut.PublicCreate<TestInputOperation, object>(input) as TestInputOperation;
Assert.NotNull(result.InputValue);
Assert.Equal(input, result.InputValue);
}
[Theory, AutoMoqData]
public void Created_input_operations_are_provided_with_one_property_input_value(object input)
{
var resolver = new SimpleOperationResolver();
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = resolver };
var sut = new FakeOperation();
sut.Initialize(correctConfiguration);
var result = sut.PublicCreate<SimpleTestPropertyInputOperation, object>(input) as SimpleTestPropertyInputOperation;
Assert.NotNull(result.Input);
Assert.Equal(input, result.Input);
}
[Theory, AutoMoqData]
public void Created_input_operations_are_provided_with_two_input_values(Tuple<object> input1, Tuple<object, object> input2)
{
var resolver = new SimpleOperationResolver();
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = resolver };
var sut = new FakeOperation();
sut.Initialize(correctConfiguration);
var result = sut.PublicCreate<SimpleTestPropertyInputOperation<Tuple<object>, Tuple<object, object>, object>, Tuple<object>, Tuple<object, object>>(input1, input2) as SimpleTestPropertyInputOperation<Tuple<object>, Tuple<object, object>, object>;
Assert.NotNull(result.Input1);
Assert.Equal(input1, result.Input1);
Assert.NotNull(result.Input2);
Assert.Equal(input2, result.Input2);
Assert.Null(result.Input3);
}
[Theory, AutoMoqData]
public void Created_input_operations_are_provided_with_three_input_values(Tuple<object> input1, Tuple<object, object> input2, Tuple<object, object, object> input3)
{
var resolver = new SimpleOperationResolver();
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = resolver };
var sut = new FakeOperation();
sut.Initialize(correctConfiguration);
var result = sut.PublicCreate<SimpleTestPropertyInputOperation<Tuple<object>, Tuple<object, object>, Tuple<object, object, object>>, Tuple<object>, Tuple<object, object>, Tuple<object, object, object>>(input1, input2, input3) as SimpleTestPropertyInputOperation<Tuple<object>, Tuple<object, object>, Tuple<object, object, object>>;
Assert.NotNull(result.Input1);
Assert.Equal(input1, result.Input1);
Assert.NotNull(result.Input2);
Assert.Equal(input2, result.Input2);
Assert.NotNull(result.Input3);
Assert.Equal(input3, result.Input3);
}
[Theory, AutoMoqData]
public void Created_input_operations_are_provided_with_input_values_when_having_behaviors(object input)
{
var resolver = new SimpleOperationResolver();
var factory = new FakeOperationBehaviorFactory();
factory.OperationBehaviors.Add(new FakeOperationBehavior());
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = resolver }.WithBehaviorFactory(factory);
var sut = new FakeOperation();
sut.Initialize(correctConfiguration);
var result = sut.PublicCreate<SimpleTestPropertyInputOperation, object>(input).GetInnermostOperation() as SimpleTestPropertyInputOperation;
Assert.NotNull(result.Input);
Assert.Equal(input, result.Input);
}
[Theory, AutoMoqData]
public void You_cannot_create_an_operation_with_an_input_value_without_specifying_an_input_property_with_the_proper_type(IEnumerable<string> input)
{
var resolver = new SimpleOperationResolver();
var factory = new FakeOperationBehaviorFactory();
factory.OperationBehaviors.Add(new FakeOperationBehavior());
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = resolver }.WithBehaviorFactory(factory);
var sut = new FakeOperation();
sut.Initialize(correctConfiguration);
Assert.Throws<ArgumentException>(() => sut.PublicCreate<SimpleTestPropertyInputOperation, IEnumerable<string>>(input));
}
[Theory, AutoMoqData]
public void Data_flows_between_child_operations_from_interface_input_and_output(object output)
{
var inputOperation = new FakeInputOperation<object>();
var outpuOperation = new FakeOutputOperation<object> { OutputValue = output };
var sut = new FakeOperation(outpuOperation, inputOperation);
sut.Execute();
Assert.Equal(outpuOperation.OutputValue, inputOperation.ProvidedInput);
}
[Theory, AutoMoqData]
public void Data_flows_between_child_operations_from_property_input_and_output(object data)
{
var inputOperation = new TestPropertyInputOperation();
var outputOperation = new TestPropertyOutputOperation(inputOperation) { Output = data };
var sut = new FakeOperation(outputOperation, inputOperation);
sut.Execute();
Assert.Equal(data, outputOperation.Output);
Assert.Equal(data, inputOperation.Input);
}
[Theory, AutoMoqData]
public void Data_is_piped_to_child_operations_when_creating_the_piping_operation_using_explicit_input_values(object data)
{
var sut = new ParentInputOperation<TestPipedPropertyInputOperation<SimpleTestPropertyInputOperation>> { Input = data };
var correctConfiguration = new FakeWorkflowConfiguration { Resolver = new SimpleOperationResolver() };
sut.Initialize(correctConfiguration);
sut.Execute();
var childOperation = (SimpleTestPropertyInputOperation) ((Operation)sut.ExecutedChildOperations.First().Operation).ExecutedChildOperations.First().Operation;
Assert.Equal(data, childOperation.Input);
}
[Theory, AutoMoqData]
public void You_can_get_outputted_values_from_within_the_operation(object output)
{
var sut = new OutputtingOperation { ExpectedOutput = output };
sut.Execute();
Assert.Equal(sut.ExpectedOutput, sut.ActualOutput);
}
[Theory, AutoMoqData]
public void You_can_get_outputted_collection_values_from_within_the_operation(IEnumerable<object> output)
{
var sut = new OutputtingEnumerableOperation { ExpectedOutput = output };
sut.Execute();
Assert.Equal(output, sut.ActualOutput);
}
[Theory, AutoMoqData]
public void You_can_get_outputted_collection_values_from_within_the_operation2(List<object> output)
{
var sut = new OutputtingListOperation { ExpectedOutput = output };
sut.Execute();
Assert.Equal(output, sut.ActualOutput);
}
[Theory, AutoMoqData]
public void Input_data_automatically_flows_to_child_operations_when_consumed_in_parent_operation(object output)
{
var outputOperation = new FakeOutputOperation<object> { OutputValue = output };
var childInputOperation = new FakeInputOperation<object>();
var parentInputOperation = new FakeInputOperation<object>(childInputOperation);
var sut = new FakeOperation(outputOperation, parentInputOperation);
sut.Execute();
Assert.Equal(outputOperation.OutputValue, childInputOperation.ProvidedInput);
}
[Theory, AutoMoqData]
public void Input_propery_data_automatically_flows_to_child_operations_when_consumed_in_parent_operation(object output)
{
var outputOperation = new FakeOutputOperation<object> { OutputValue = output };
var childInputOperation = new TestPropertyInputOperation();
var parentInputOperation = new TestPropertyInputOperation(childInputOperation);
var sut = new FakeOperation(outputOperation, parentInputOperation);
sut.Execute();
Assert.Equal(outputOperation.OutputValue, childInputOperation.Input);
}
[Theory, AutoMoqData]
public void Input_data_flow_is_cut_off_from_child_operations_if_not_consumed_by_parent_operation(object output)
{
var outputOperation = new FakeOutputOperation<object> { OutputValue = output };
var childInputOperation = new FakeInputOperation<object>();
var parentInputOperation = new FakeOperation(childInputOperation);
var sut = new FakeOperation(outputOperation, parentInputOperation);
sut.Execute();
Assert.Null(childInputOperation.ProvidedInput);
}
[Theory, AutoMoqData]
public void Executed_child_operations_are_added_to_the_execution_info_list(IOperation childOperation)
{
var sut = new FakeOperation(childOperation);
sut.Execute();
Assert.Equal(1, sut.ExecutedChildOperations.Count());
Assert.Equal(childOperation, sut.ExecutedChildOperations.ElementAt(0).Operation);
}
[Theory, AutoMoqData]
public void Child_operation_execution_info_contains_error_info(Exception error)
{
var childOperation = new FakeOperation { ThrowOnExecute = error };
var sut = new FakeOperation(childOperation);
ExecuteIgnoringErrors(sut.Execute);
Assert.Equal(1, sut.ExecutedChildOperations.Count());
Assert.Equal(childOperation.ThrowOnExecute, sut.ExecutedChildOperations.ElementAt(0).Error);
}
[Fact]
public void Child_execution_info_contains_the_start_and_end_times_of_the_execution()
{
var childOperation = new FakeOperation { ExecuteAction = () => Time.Wait(TimeSpan.FromSeconds(1))};
var sut = new FakeOperation(childOperation);
Time.Stop();
var started = Time.OffsetUtcNow;
sut.Execute();
var executionInfo = sut.ExecutedChildOperations.ElementAt(0);
Assert.Equal(started, executionInfo.Started);
Assert.Equal(started.AddSeconds(1), executionInfo.Completed);
}
[Fact]
public void Errors_creating_operations_are_wrapped_in_an_OperationCreationException()
{
Assert.Throws<OperationCreationException<ErrorOperation>>(() => Operation.Create<ErrorOperation>(new FakeWorkflowConfiguration().WithResolver(new SimpleOperationResolver())));
}
[Theory, AutoMoqData]
public void You_can_make_data_available_to_child_operations(object input)
{
var childInputOperation = new FakeInputOperation<object>();
var sut = new FakeOperation(childInputOperation);
sut.ExecuteAction = () => sut.PublicPipeInputToChildOperations(input);
sut.Execute();
Assert.Equal(input, childInputOperation.ProvidedInput);
}
[Theory, AutoMoqData]
public void You_can_only_make_data_available_to_child_operations_during_execution(object input)
{
var sut = new FakeOperation();
Assert.Throws<InvalidOperationException>(() => sut.PublicPipeInputToChildOperations(input));
}
[Theory, AutoMoqData]
public void You_can_only_get_child_output_during_execution(object input)
{
var sut = new FakeOperation();
Assert.Throws<InvalidOperationException>(() => sut.PublicGetChildOutputValue<object>());
}
private class ErrorOperation: Operation
{
public ErrorOperation()
{
throw new Exception();
}
}
private class TestOperation : Operation {
public WorkflowConfiguration Configuration { get; private set; }
public override void Initialize(WorkflowConfiguration configuration) =>
Configuration = configuration;
}
private class OutputtingOperation : Operation
{
public object ExpectedOutput { get; set; }
public object ActualOutput { get; private set; }
public override IEnumerable<IOperation> GetChildOperations()
{
yield return new FakeOutputOperation<object> { OutputValue = ExpectedOutput };
ActualOutput = GetChildOutputValue<object>();
}
}
private class OutputtingEnumerableOperation : Operation
{
public IEnumerable<object> ExpectedOutput { get; set; }
public IEnumerable<object> ActualOutput { get; private set; }
protected override void OnExecute() { }
public override IEnumerable<IOperation> GetChildOperations()
{
yield return new FakeOutputOperation<IEnumerable<object>> { OutputValue = ExpectedOutput };
ActualOutput = GetChildOutputValues<object>();
}
}
private class OutputtingListOperation : Operation
{
public List<object> ExpectedOutput { get; set; }
public IEnumerable<object> ActualOutput { get; private set; }
protected override void OnExecute() { }
public override IEnumerable<IOperation> GetChildOperations()
{
yield return new FakeOutputOperation<List<object>> { OutputValue = ExpectedOutput };
ActualOutput = GetChildOutputValues<object>();
}
}
private class TestInputOperation : Operation, IInputOperation<object>
{
public object InputValue { get; private set; }
public void Input(object input) =>
InputValue = input;
}
private class TestPropertyInputOperation : FakeOperation
{
[Input]
public object Input { get; set; }
public TestPropertyInputOperation(params IOperation[] childOperations)
: base(childOperations)
{
}
}
private class ParentInputOperation<TOperation> : Operation
where TOperation : IOperation
{
public object Input { get; set; }
public override IEnumerable<IOperation> GetChildOperations()
{
yield return Create<TOperation, object>(Input);
}
}
private class TestPipedPropertyInputOperation<TOperation> : FakeOperation
where TOperation : IOperation
{
[Input,Pipe]
public object Input { get; set; }
public override IEnumerable<IOperation> GetChildOperations()
{
yield return Create<TOperation>();
}
}
private class SimpleTestPropertyInputOperation : Operation
{
[Input]
public object Input { get; set; }
public SimpleTestPropertyInputOperation() { }
}
private class SimpleTestPropertyInputOperation<TInput1, TInput2, TInput3> : Operation
{
[Input]
public TInput1 Input1 { get; set; }
[Input]
public TInput2 Input2 { get; set; }
[Input]
public TInput3 Input3 { get; set; }
public SimpleTestPropertyInputOperation() { }
}
private class TestPropertyOutputOperation : FakeOperation
{
[Output]
public object Output { get; set; }
public TestPropertyOutputOperation(params IOperation[] childOperations)
: base(childOperations)
{
}
}
}
}
| |
// Copyright 2009-2012 Matvei Stefarov <me@matvei.org>
using System;
using System.IO;
using System.IO.Compression;
using System.Net;
using JetBrains.Annotations;
namespace fCraft.MapConversion {
public sealed class MapD3 : IMapConverter {
static readonly byte[] Mapping = new byte[256];
static MapD3() {
// 0-49 default
Mapping[50] = (byte)Block.TNT; // Torch
Mapping[51] = (byte)Block.StillLava; // Fire
Mapping[52] = (byte)Block.Blue; // Water Source
Mapping[53] = (byte)Block.Red; // Lava Source
Mapping[54] = (byte)Block.TNT; // Chest
Mapping[55] = (byte)Block.TNT; // Gear
Mapping[56] = (byte)Block.Glass; // Diamond Ore
Mapping[57] = (byte)Block.Glass; // Diamond
Mapping[58] = (byte)Block.TNT; // Workbench
Mapping[59] = (byte)Block.Leaves; // Crops
Mapping[60] = (byte)Block.Obsidian; // Soil
Mapping[61] = (byte)Block.Cobblestone; // Furnace
Mapping[62] = (byte)Block.StillLava; // Burning Furnace
// 63-199 unused
Mapping[200] = (byte)Block.Lava; // Kill Lava
Mapping[201] = (byte)Block.Stone; // Kill Lava
// 202 unused
Mapping[203] = (byte)Block.Stair; // Still Stair
// 204-205 unused
Mapping[206] = (byte)Block.Water; // Original Water
Mapping[207] = (byte)Block.Lava; // Original Lava
// 208 Invisible
Mapping[209] = (byte)Block.Water; // Acid
Mapping[210] = (byte)Block.Sand; // Still Sand
Mapping[211] = (byte)Block.Water; // Still Acid
Mapping[212] = (byte)Block.RedFlower; // Kill Rose
Mapping[213] = (byte)Block.Gravel; // Still Gravel
// 214 No Entry
Mapping[215] = (byte)Block.White; // Snow
Mapping[216] = (byte)Block.Lava; // Fast Lava
Mapping[217] = (byte)Block.White; // Kill Glass
// 218 Invisible Sponge
Mapping[219] = (byte)Block.Sponge; // Drain Sponge
Mapping[220] = (byte)Block.Sponge; // Super Drain Sponge
Mapping[221] = (byte)Block.Gold; // Spark
Mapping[222] = (byte)Block.TNT; // Rocket
Mapping[223] = (byte)Block.Gold; // Short Spark
Mapping[224] = (byte)Block.TNT; // Mega Rocket
Mapping[225] = (byte)Block.Lava; // Red Spark
Mapping[226] = (byte)Block.TNT; // Fire Fountain
Mapping[227] = (byte)Block.TNT; // Admin TNT
Mapping[228] = (byte)Block.Iron; // Fan
Mapping[229] = (byte)Block.Iron; // Door
Mapping[230] = (byte)Block.Lava; // Campfire
Mapping[231] = (byte)Block.Red; // Laser
Mapping[232] = (byte)Block.Black; // Ash
// 233-234 unused
Mapping[235] = (byte)Block.Water; // Sea
Mapping[236] = (byte)Block.White; // Flasher
// 237-243 unused
Mapping[244] = (byte)Block.Leaves; // Vines
Mapping[245] = (byte)Block.Lava; // Flamethrower
// 246 unused
Mapping[247] = (byte)Block.Iron; // Cannon
Mapping[248] = (byte)Block.Obsidian; // Blob
// all others default to 0/air
}
public string ServerName {
get { return "D3"; }
}
public MapStorageType StorageType {
get { return MapStorageType.SingleFile; }
}
public MapFormat Format {
get { return MapFormat.D3; }
}
public bool ClaimsName( [NotNull] string fileName ) {
if( fileName == null ) throw new ArgumentNullException( "fileName" );
return fileName.EndsWith( ".map", StringComparison.OrdinalIgnoreCase );
}
public bool Claims( [NotNull] string fileName ) {
if( fileName == null ) throw new ArgumentNullException( "fileName" );
try {
using( FileStream mapStream = File.OpenRead( fileName ) ) {
using( GZipStream gs = new GZipStream( mapStream, CompressionMode.Decompress ) ) {
BinaryReader bs = new BinaryReader( gs );
int formatVersion = IPAddress.NetworkToHostOrder( bs.ReadInt32() );
return (formatVersion == 1000 || formatVersion == 1010 || formatVersion == 1020 ||
formatVersion == 1030 || formatVersion == 1040 || formatVersion == 1050);
}
}
} catch( Exception ) {
return false;
}
}
public Map LoadHeader( [NotNull] string fileName ) {
if( fileName == null ) throw new ArgumentNullException( "fileName" );
using( FileStream mapStream = File.OpenRead( fileName ) ) {
return LoadHeaderInternal( mapStream );
}
}
static Map LoadHeaderInternal( Stream stream ) {
if( stream == null ) throw new ArgumentNullException( "stream" );
// Setup a GZipStream to decompress and read the map file
using( GZipStream gs = new GZipStream( stream, CompressionMode.Decompress, true ) ) {
BinaryReader bs = new BinaryReader( gs );
int formatVersion = IPAddress.NetworkToHostOrder( bs.ReadInt32() );
// Read in the map dimesions
int width = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
int length = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
int height = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
Map map = new Map( null, width, length, height, false );
Position spawn = new Position();
switch( formatVersion ) {
case 1000:
case 1010:
break;
case 1020:
spawn.X = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
spawn.Y = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
spawn.Z = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
map.Spawn = spawn;
break;
//case 1030:
//case 1040:
//case 1050:
default:
spawn.X = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
spawn.Y = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
spawn.Z = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
spawn.R = (byte)IPAddress.NetworkToHostOrder( bs.ReadInt16() );
spawn.L = (byte)IPAddress.NetworkToHostOrder( bs.ReadInt16() );
map.Spawn = spawn;
break;
}
return map;
}
}
public Map Load( [NotNull] string fileName ) {
if( fileName == null ) throw new ArgumentNullException( "fileName" );
using( FileStream mapStream = File.OpenRead( fileName ) ) {
Map map = LoadHeaderInternal( mapStream );
if( !map.ValidateHeader() ) {
throw new MapFormatException( "One or more of the map dimensions are invalid." );
}
// Read in the map data
map.Blocks = new byte[map.Volume];
mapStream.Read( map.Blocks, 0, map.Blocks.Length );
map.ConvertBlockTypes( Mapping );
return map;
}
}
public bool Save( [NotNull] Map mapToSave, [NotNull] string fileName ) {
if( mapToSave == null ) throw new ArgumentNullException( "mapToSave" );
if( fileName == null ) throw new ArgumentNullException( "fileName" );
using( FileStream mapStream = File.Create( fileName ) ) {
using( GZipStream gs = new GZipStream( mapStream, CompressionMode.Compress ) ) {
BinaryWriter bs = new BinaryWriter( gs );
// Write the magic number
bs.Write( IPAddress.HostToNetworkOrder( 1050 ) );
bs.Write( (byte)0 );
bs.Write( (byte)0 );
// Write the map dimensions
bs.Write( IPAddress.NetworkToHostOrder( mapToSave.Width ) );
bs.Write( IPAddress.NetworkToHostOrder( mapToSave.Length ) );
bs.Write( IPAddress.NetworkToHostOrder( mapToSave.Height ) );
// Write the map data
bs.Write( mapToSave.Blocks, 0, mapToSave.Blocks.Length );
bs.Close();
return true;
}
}
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace DocuSign.eSign.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class Note : IEquatable<Note>
{
/// <summary>
/// Width of the tab in pixels.
/// </summary>
/// <value>Width of the tab in pixels.</value>
[DataMember(Name="width", EmitDefaultValue=false)]
public int? Width { get; set; }
/// <summary>
/// Height of the tab in pixels.
/// </summary>
/// <value>Height of the tab in pixels.</value>
[DataMember(Name="height", EmitDefaultValue=false)]
public int? Height { get; set; }
/// <summary>
/// When set to **true**, this custom tab is shared.
/// </summary>
/// <value>When set to **true**, this custom tab is shared.</value>
[DataMember(Name="shared", EmitDefaultValue=false)]
public string Shared { get; set; }
/// <summary>
/// Specifies the value of the tab.
/// </summary>
/// <value>Specifies the value of the tab.</value>
[DataMember(Name="value", EmitDefaultValue=false)]
public string Value { get; set; }
/// <summary>
/// Specifies the tool tip text for the tab.
/// </summary>
/// <value>Specifies the tool tip text for the tab.</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// The label string associated with the tab.
/// </summary>
/// <value>The label string associated with the tab.</value>
[DataMember(Name="tabLabel", EmitDefaultValue=false)]
public string TabLabel { get; set; }
/// <summary>
/// The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default.
/// </summary>
/// <value>The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default.</value>
[DataMember(Name="font", EmitDefaultValue=false)]
public string Font { get; set; }
/// <summary>
/// When set to **true**, the information in the tab is bold.
/// </summary>
/// <value>When set to **true**, the information in the tab is bold.</value>
[DataMember(Name="bold", EmitDefaultValue=false)]
public string Bold { get; set; }
/// <summary>
/// When set to **true**, the information in the tab is italic.
/// </summary>
/// <value>When set to **true**, the information in the tab is italic.</value>
[DataMember(Name="italic", EmitDefaultValue=false)]
public string Italic { get; set; }
/// <summary>
/// When set to **true**, the information in the tab is underlined.
/// </summary>
/// <value>When set to **true**, the information in the tab is underlined.</value>
[DataMember(Name="underline", EmitDefaultValue=false)]
public string Underline { get; set; }
/// <summary>
/// The font color used for the information in the tab.\n\nPossible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White.
/// </summary>
/// <value>The font color used for the information in the tab.\n\nPossible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White.</value>
[DataMember(Name="fontColor", EmitDefaultValue=false)]
public string FontColor { get; set; }
/// <summary>
/// The font size used for the information in the tab.\n\nPossible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72.
/// </summary>
/// <value>The font size used for the information in the tab.\n\nPossible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72.</value>
[DataMember(Name="fontSize", EmitDefaultValue=false)]
public string FontSize { get; set; }
/// <summary>
/// Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.
/// </summary>
/// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.</value>
[DataMember(Name="documentId", EmitDefaultValue=false)]
public string DocumentId { get; set; }
/// <summary>
/// Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.
/// </summary>
/// <value>Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.</value>
[DataMember(Name="recipientId", EmitDefaultValue=false)]
public string RecipientId { get; set; }
/// <summary>
/// Specifies the page number on which the tab is located.
/// </summary>
/// <value>Specifies the page number on which the tab is located.</value>
[DataMember(Name="pageNumber", EmitDefaultValue=false)]
public string PageNumber { get; set; }
/// <summary>
/// This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.
/// </summary>
/// <value>This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.</value>
[DataMember(Name="xPosition", EmitDefaultValue=false)]
public string XPosition { get; set; }
/// <summary>
/// This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.
/// </summary>
/// <value>This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.</value>
[DataMember(Name="yPosition", EmitDefaultValue=false)]
public string YPosition { get; set; }
/// <summary>
/// Anchor text information for a radio button.
/// </summary>
/// <value>Anchor text information for a radio button.</value>
[DataMember(Name="anchorString", EmitDefaultValue=false)]
public string AnchorString { get; set; }
/// <summary>
/// Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.
/// </summary>
/// <value>Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.</value>
[DataMember(Name="anchorXOffset", EmitDefaultValue=false)]
public string AnchorXOffset { get; set; }
/// <summary>
/// Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.
/// </summary>
/// <value>Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.</value>
[DataMember(Name="anchorYOffset", EmitDefaultValue=false)]
public string AnchorYOffset { get; set; }
/// <summary>
/// Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.
/// </summary>
/// <value>Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.</value>
[DataMember(Name="anchorUnits", EmitDefaultValue=false)]
public string AnchorUnits { get; set; }
/// <summary>
/// When set to **true**, this tab is ignored if anchorString is not found in the document.
/// </summary>
/// <value>When set to **true**, this tab is ignored if anchorString is not found in the document.</value>
[DataMember(Name="anchorIgnoreIfNotPresent", EmitDefaultValue=false)]
public string AnchorIgnoreIfNotPresent { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="anchorCaseSensitive", EmitDefaultValue=false)]
public string AnchorCaseSensitive { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="anchorMatchWholeWord", EmitDefaultValue=false)]
public string AnchorMatchWholeWord { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="anchorHorizontalAlignment", EmitDefaultValue=false)]
public string AnchorHorizontalAlignment { get; set; }
/// <summary>
/// The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call].
/// </summary>
/// <value>The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call].</value>
[DataMember(Name="tabId", EmitDefaultValue=false)]
public string TabId { get; set; }
/// <summary>
/// When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients.
/// </summary>
/// <value>When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients.</value>
[DataMember(Name="templateLocked", EmitDefaultValue=false)]
public string TemplateLocked { get; set; }
/// <summary>
/// When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.
/// </summary>
/// <value>When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.</value>
[DataMember(Name="templateRequired", EmitDefaultValue=false)]
public string TemplateRequired { get; set; }
/// <summary>
/// For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.
/// </summary>
/// <value>For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.</value>
[DataMember(Name="conditionalParentLabel", EmitDefaultValue=false)]
public string ConditionalParentLabel { get; set; }
/// <summary>
/// For conditional fields, this is the value of the parent tab that controls the tab's visibility.\n\nIf the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active.
/// </summary>
/// <value>For conditional fields, this is the value of the parent tab that controls the tab's visibility.\n\nIf the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active.</value>
[DataMember(Name="conditionalParentValue", EmitDefaultValue=false)]
public string ConditionalParentValue { get; set; }
/// <summary>
/// The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties.
/// </summary>
/// <value>The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties.</value>
[DataMember(Name="customTabId", EmitDefaultValue=false)]
public string CustomTabId { get; set; }
/// <summary>
/// Gets or Sets MergeField
/// </summary>
[DataMember(Name="mergeField", EmitDefaultValue=false)]
public MergeField MergeField { get; set; }
/// <summary>
/// Indicates the envelope status. Valid values are:\n\n* sent - The envelope is sent to the recipients. \n* created - The envelope is saved as a draft and can be modified and sent later.
/// </summary>
/// <value>Indicates the envelope status. Valid values are:\n\n* sent - The envelope is sent to the recipients. \n* created - The envelope is saved as a draft and can be modified and sent later.</value>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Note {\n");
sb.Append(" Width: ").Append(Width).Append("\n");
sb.Append(" Height: ").Append(Height).Append("\n");
sb.Append(" Shared: ").Append(Shared).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" TabLabel: ").Append(TabLabel).Append("\n");
sb.Append(" Font: ").Append(Font).Append("\n");
sb.Append(" Bold: ").Append(Bold).Append("\n");
sb.Append(" Italic: ").Append(Italic).Append("\n");
sb.Append(" Underline: ").Append(Underline).Append("\n");
sb.Append(" FontColor: ").Append(FontColor).Append("\n");
sb.Append(" FontSize: ").Append(FontSize).Append("\n");
sb.Append(" DocumentId: ").Append(DocumentId).Append("\n");
sb.Append(" RecipientId: ").Append(RecipientId).Append("\n");
sb.Append(" PageNumber: ").Append(PageNumber).Append("\n");
sb.Append(" XPosition: ").Append(XPosition).Append("\n");
sb.Append(" YPosition: ").Append(YPosition).Append("\n");
sb.Append(" AnchorString: ").Append(AnchorString).Append("\n");
sb.Append(" AnchorXOffset: ").Append(AnchorXOffset).Append("\n");
sb.Append(" AnchorYOffset: ").Append(AnchorYOffset).Append("\n");
sb.Append(" AnchorUnits: ").Append(AnchorUnits).Append("\n");
sb.Append(" AnchorIgnoreIfNotPresent: ").Append(AnchorIgnoreIfNotPresent).Append("\n");
sb.Append(" AnchorCaseSensitive: ").Append(AnchorCaseSensitive).Append("\n");
sb.Append(" AnchorMatchWholeWord: ").Append(AnchorMatchWholeWord).Append("\n");
sb.Append(" AnchorHorizontalAlignment: ").Append(AnchorHorizontalAlignment).Append("\n");
sb.Append(" TabId: ").Append(TabId).Append("\n");
sb.Append(" TemplateLocked: ").Append(TemplateLocked).Append("\n");
sb.Append(" TemplateRequired: ").Append(TemplateRequired).Append("\n");
sb.Append(" ConditionalParentLabel: ").Append(ConditionalParentLabel).Append("\n");
sb.Append(" ConditionalParentValue: ").Append(ConditionalParentValue).Append("\n");
sb.Append(" CustomTabId: ").Append(CustomTabId).Append("\n");
sb.Append(" MergeField: ").Append(MergeField).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Note);
}
/// <summary>
/// Returns true if Note instances are equal
/// </summary>
/// <param name="other">Instance of Note to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Note other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Width == other.Width ||
this.Width != null &&
this.Width.Equals(other.Width)
) &&
(
this.Height == other.Height ||
this.Height != null &&
this.Height.Equals(other.Height)
) &&
(
this.Shared == other.Shared ||
this.Shared != null &&
this.Shared.Equals(other.Shared)
) &&
(
this.Value == other.Value ||
this.Value != null &&
this.Value.Equals(other.Value)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.TabLabel == other.TabLabel ||
this.TabLabel != null &&
this.TabLabel.Equals(other.TabLabel)
) &&
(
this.Font == other.Font ||
this.Font != null &&
this.Font.Equals(other.Font)
) &&
(
this.Bold == other.Bold ||
this.Bold != null &&
this.Bold.Equals(other.Bold)
) &&
(
this.Italic == other.Italic ||
this.Italic != null &&
this.Italic.Equals(other.Italic)
) &&
(
this.Underline == other.Underline ||
this.Underline != null &&
this.Underline.Equals(other.Underline)
) &&
(
this.FontColor == other.FontColor ||
this.FontColor != null &&
this.FontColor.Equals(other.FontColor)
) &&
(
this.FontSize == other.FontSize ||
this.FontSize != null &&
this.FontSize.Equals(other.FontSize)
) &&
(
this.DocumentId == other.DocumentId ||
this.DocumentId != null &&
this.DocumentId.Equals(other.DocumentId)
) &&
(
this.RecipientId == other.RecipientId ||
this.RecipientId != null &&
this.RecipientId.Equals(other.RecipientId)
) &&
(
this.PageNumber == other.PageNumber ||
this.PageNumber != null &&
this.PageNumber.Equals(other.PageNumber)
) &&
(
this.XPosition == other.XPosition ||
this.XPosition != null &&
this.XPosition.Equals(other.XPosition)
) &&
(
this.YPosition == other.YPosition ||
this.YPosition != null &&
this.YPosition.Equals(other.YPosition)
) &&
(
this.AnchorString == other.AnchorString ||
this.AnchorString != null &&
this.AnchorString.Equals(other.AnchorString)
) &&
(
this.AnchorXOffset == other.AnchorXOffset ||
this.AnchorXOffset != null &&
this.AnchorXOffset.Equals(other.AnchorXOffset)
) &&
(
this.AnchorYOffset == other.AnchorYOffset ||
this.AnchorYOffset != null &&
this.AnchorYOffset.Equals(other.AnchorYOffset)
) &&
(
this.AnchorUnits == other.AnchorUnits ||
this.AnchorUnits != null &&
this.AnchorUnits.Equals(other.AnchorUnits)
) &&
(
this.AnchorIgnoreIfNotPresent == other.AnchorIgnoreIfNotPresent ||
this.AnchorIgnoreIfNotPresent != null &&
this.AnchorIgnoreIfNotPresent.Equals(other.AnchorIgnoreIfNotPresent)
) &&
(
this.AnchorCaseSensitive == other.AnchorCaseSensitive ||
this.AnchorCaseSensitive != null &&
this.AnchorCaseSensitive.Equals(other.AnchorCaseSensitive)
) &&
(
this.AnchorMatchWholeWord == other.AnchorMatchWholeWord ||
this.AnchorMatchWholeWord != null &&
this.AnchorMatchWholeWord.Equals(other.AnchorMatchWholeWord)
) &&
(
this.AnchorHorizontalAlignment == other.AnchorHorizontalAlignment ||
this.AnchorHorizontalAlignment != null &&
this.AnchorHorizontalAlignment.Equals(other.AnchorHorizontalAlignment)
) &&
(
this.TabId == other.TabId ||
this.TabId != null &&
this.TabId.Equals(other.TabId)
) &&
(
this.TemplateLocked == other.TemplateLocked ||
this.TemplateLocked != null &&
this.TemplateLocked.Equals(other.TemplateLocked)
) &&
(
this.TemplateRequired == other.TemplateRequired ||
this.TemplateRequired != null &&
this.TemplateRequired.Equals(other.TemplateRequired)
) &&
(
this.ConditionalParentLabel == other.ConditionalParentLabel ||
this.ConditionalParentLabel != null &&
this.ConditionalParentLabel.Equals(other.ConditionalParentLabel)
) &&
(
this.ConditionalParentValue == other.ConditionalParentValue ||
this.ConditionalParentValue != null &&
this.ConditionalParentValue.Equals(other.ConditionalParentValue)
) &&
(
this.CustomTabId == other.CustomTabId ||
this.CustomTabId != null &&
this.CustomTabId.Equals(other.CustomTabId)
) &&
(
this.MergeField == other.MergeField ||
this.MergeField != null &&
this.MergeField.Equals(other.MergeField)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Width != null)
hash = hash * 57 + this.Width.GetHashCode();
if (this.Height != null)
hash = hash * 57 + this.Height.GetHashCode();
if (this.Shared != null)
hash = hash * 57 + this.Shared.GetHashCode();
if (this.Value != null)
hash = hash * 57 + this.Value.GetHashCode();
if (this.Name != null)
hash = hash * 57 + this.Name.GetHashCode();
if (this.TabLabel != null)
hash = hash * 57 + this.TabLabel.GetHashCode();
if (this.Font != null)
hash = hash * 57 + this.Font.GetHashCode();
if (this.Bold != null)
hash = hash * 57 + this.Bold.GetHashCode();
if (this.Italic != null)
hash = hash * 57 + this.Italic.GetHashCode();
if (this.Underline != null)
hash = hash * 57 + this.Underline.GetHashCode();
if (this.FontColor != null)
hash = hash * 57 + this.FontColor.GetHashCode();
if (this.FontSize != null)
hash = hash * 57 + this.FontSize.GetHashCode();
if (this.DocumentId != null)
hash = hash * 57 + this.DocumentId.GetHashCode();
if (this.RecipientId != null)
hash = hash * 57 + this.RecipientId.GetHashCode();
if (this.PageNumber != null)
hash = hash * 57 + this.PageNumber.GetHashCode();
if (this.XPosition != null)
hash = hash * 57 + this.XPosition.GetHashCode();
if (this.YPosition != null)
hash = hash * 57 + this.YPosition.GetHashCode();
if (this.AnchorString != null)
hash = hash * 57 + this.AnchorString.GetHashCode();
if (this.AnchorXOffset != null)
hash = hash * 57 + this.AnchorXOffset.GetHashCode();
if (this.AnchorYOffset != null)
hash = hash * 57 + this.AnchorYOffset.GetHashCode();
if (this.AnchorUnits != null)
hash = hash * 57 + this.AnchorUnits.GetHashCode();
if (this.AnchorIgnoreIfNotPresent != null)
hash = hash * 57 + this.AnchorIgnoreIfNotPresent.GetHashCode();
if (this.AnchorCaseSensitive != null)
hash = hash * 57 + this.AnchorCaseSensitive.GetHashCode();
if (this.AnchorMatchWholeWord != null)
hash = hash * 57 + this.AnchorMatchWholeWord.GetHashCode();
if (this.AnchorHorizontalAlignment != null)
hash = hash * 57 + this.AnchorHorizontalAlignment.GetHashCode();
if (this.TabId != null)
hash = hash * 57 + this.TabId.GetHashCode();
if (this.TemplateLocked != null)
hash = hash * 57 + this.TemplateLocked.GetHashCode();
if (this.TemplateRequired != null)
hash = hash * 57 + this.TemplateRequired.GetHashCode();
if (this.ConditionalParentLabel != null)
hash = hash * 57 + this.ConditionalParentLabel.GetHashCode();
if (this.ConditionalParentValue != null)
hash = hash * 57 + this.ConditionalParentValue.GetHashCode();
if (this.CustomTabId != null)
hash = hash * 57 + this.CustomTabId.GetHashCode();
if (this.MergeField != null)
hash = hash * 57 + this.MergeField.GetHashCode();
if (this.Status != null)
hash = hash * 57 + this.Status.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 57 + this.ErrorDetails.GetHashCode();
return hash;
}
}
}
}
| |
//
// Mono.Data.SqliteClient.SqliteCommand.cs
//
// Represents a Transact-SQL statement or stored procedure to execute against
// a Sqlite database file.
//
// Author(s): Vladimir Vukicevic <vladimir@pobox.com>
// Everaldo Canuto <everaldo_canuto@yahoo.com.br>
// Chris Turchin <chris@turchin.net>
// Jeroen Zwartepoorte <jeroen@xs4all.nl>
// Thomas Zoechling <thomas.zoechling@gmx.at>
// Joshua Tauberer <tauberer@for.net>
//
// Copyright (C) 2002 Vladimir Vukicevic
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Text;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Data;
using System.Diagnostics;
using Group = System.Text.RegularExpressions.Group;
namespace Mono.Data.SqliteClient
{
public class SqliteCommand : IDbCommand
{
#region Fields
private SqliteConnection parent_conn;
//private SqliteTransaction transaction;
private IDbTransaction transaction;
private string sql;
private int timeout;
private CommandType type;
private UpdateRowSource upd_row_source;
private SqliteParameterCollection sql_params;
private bool prepared = false;
#endregion
#region Constructors and destructors
public SqliteCommand ()
{
sql = "";
}
public SqliteCommand (string sqlText)
{
sql = sqlText;
}
public SqliteCommand (string sqlText, SqliteConnection dbConn)
{
sql = sqlText;
parent_conn = dbConn;
}
public SqliteCommand (string sqlText, SqliteConnection dbConn, IDbTransaction trans)
{
sql = sqlText;
parent_conn = dbConn;
transaction = trans;
}
public void Dispose ()
{
}
#endregion
#region Properties
public string CommandText
{
get { return sql; }
set { sql = value; prepared = false; }
}
public int CommandTimeout
{
get { return timeout; }
set { timeout = value; }
}
public CommandType CommandType
{
get { return type; }
set { type = value; }
}
IDbConnection IDbCommand.Connection
{
get
{
return parent_conn;
}
set
{
if (!(value is SqliteConnection))
{
throw new InvalidOperationException ("Can't set Connection to something other than a SqliteConnection");
}
parent_conn = (SqliteConnection) value;
}
}
public SqliteConnection Connection
{
get { return parent_conn; }
set { parent_conn = value; }
}
IDataParameterCollection IDbCommand.Parameters
{
get { return Parameters; }
}
public SqliteParameterCollection Parameters
{
get
{
if (sql_params == null) sql_params = new SqliteParameterCollection();
return sql_params;
}
}
public IDbTransaction Transaction
{
get { return transaction; }
set { transaction = value; }
}
public UpdateRowSource UpdatedRowSource
{
get { return upd_row_source; }
set { upd_row_source = value; }
}
#endregion
#region Internal Methods
internal int NumChanges ()
{
if (parent_conn.Version == 3)
return Sqlite.sqlite3_changes(parent_conn.Handle);
else
return Sqlite.sqlite_changes(parent_conn.Handle);
}
private void BindParameters3 (IntPtr pStmt)
{
if (sql_params == null) return;
if (sql_params.Count == 0) return;
int pcount = Sqlite.sqlite3_bind_parameter_count (pStmt);
for (int i = 1; i <= pcount; i++)
{
String name = Sqlite.HeapToString (Sqlite.sqlite3_bind_parameter_name (pStmt, i), Encoding.UTF8);
SqliteParameter param = null;
if (name != null)
param = sql_params[name];
else
param = sql_params[i-1];
if (param.Value == null) {
Sqlite.sqlite3_bind_null (pStmt, i);
continue;
}
Type ptype = param.Value.GetType ();
if (ptype.IsEnum)
ptype = Enum.GetUnderlyingType (ptype);
SqliteError err;
if (ptype.Equals (typeof (String)))
{
String s = (String)param.Value;
err = Sqlite.sqlite3_bind_text16 (pStmt, i, s, -1, (IntPtr)(-1));
}
else if (ptype.Equals (typeof (DBNull)))
{
err = Sqlite.sqlite3_bind_null (pStmt, i);
}
else if (ptype.Equals (typeof (Boolean)))
{
bool b = (bool)param.Value;
err = Sqlite.sqlite3_bind_int (pStmt, i, b ? 1 : 0);
} else if (ptype.Equals (typeof (Byte)))
{
err = Sqlite.sqlite3_bind_int (pStmt, i, (Byte)param.Value);
}
else if (ptype.Equals (typeof (Char)))
{
err = Sqlite.sqlite3_bind_int (pStmt, i, (Char)param.Value);
}
else if (ptype.IsEnum)
{
err = Sqlite.sqlite3_bind_int (pStmt, i, (Int32)param.Value);
}
else if (ptype.Equals (typeof (Int16)))
{
err = Sqlite.sqlite3_bind_int (pStmt, i, (Int16)param.Value);
}
else if (ptype.Equals (typeof (Int32)))
{
err = Sqlite.sqlite3_bind_int (pStmt, i, (Int32)param.Value);
}
else if (ptype.Equals (typeof (SByte)))
{
err = Sqlite.sqlite3_bind_int (pStmt, i, (SByte)param.Value);
}
else if (ptype.Equals (typeof (UInt16)))
{
err = Sqlite.sqlite3_bind_int (pStmt, i, (UInt16)param.Value);
}
else if (ptype.Equals (typeof (DateTime)))
{
DateTime dt = (DateTime)param.Value;
err = Sqlite.sqlite3_bind_int64 (pStmt, i, dt.ToFileTime ());
}
else if (ptype.Equals (typeof (Double)))
{
err = Sqlite.sqlite3_bind_double (pStmt, i, (Double)param.Value);
}
else if (ptype.Equals (typeof (Single)))
{
err = Sqlite.sqlite3_bind_double (pStmt, i, (Single)param.Value);
}
else if (ptype.Equals (typeof (UInt32)))
{
err = Sqlite.sqlite3_bind_int64 (pStmt, i, (UInt32)param.Value);
}
else if (ptype.Equals (typeof (Int64)))
{
err = Sqlite.sqlite3_bind_int64 (pStmt, i, (Int64)param.Value);
}
else if (ptype.Equals (typeof (Byte[])))
{
err = Sqlite.sqlite3_bind_blob (pStmt, i, (Byte[])param.Value, ((Byte[])param.Value).Length, (IntPtr)(-1));
}
else
{
throw new ApplicationException("Unkown Parameter Type");
}
if (err != SqliteError.OK)
{
throw new ApplicationException ("Sqlite error in bind " + err);
}
}
}
private void GetNextStatement (IntPtr pzStart, out IntPtr pzTail, out IntPtr pStmt)
{
if (parent_conn.Version == 3)
{
SqliteError err = Sqlite.sqlite3_prepare16 (parent_conn.Handle, pzStart, -1, out pStmt, out pzTail);
if (err != SqliteError.OK)
throw new SqliteSyntaxException (GetError3());
}
else
{
IntPtr errMsg;
SqliteError err = Sqlite.sqlite_compile (parent_conn.Handle, pzStart, out pzTail, out pStmt, out errMsg);
if (err != SqliteError.OK)
{
string msg = "unknown error";
if (errMsg != IntPtr.Zero)
{
msg = Marshal.PtrToStringAnsi (errMsg);
Sqlite.sqliteFree (errMsg);
}
throw new SqliteSyntaxException (msg);
}
}
}
// Executes a statement and ignores its result.
private void ExecuteStatement (IntPtr pStmt) {
int cols;
IntPtr pazValue, pazColName;
ExecuteStatement (pStmt, out cols, out pazValue, out pazColName);
}
// Executes a statement and returns whether there is more data available.
internal bool ExecuteStatement (IntPtr pStmt, out int cols, out IntPtr pazValue, out IntPtr pazColName) {
SqliteError err;
if (parent_conn.Version == 3)
{
err = Sqlite.sqlite3_step (pStmt);
if (err == SqliteError.ERROR)
throw new SqliteExecutionException (GetError3());
pazValue = IntPtr.Zero; pazColName = IntPtr.Zero; // not used for v=3
cols = Sqlite.sqlite3_column_count (pStmt);
}
else
{
err = Sqlite.sqlite_step (pStmt, out cols, out pazValue, out pazColName);
if (err == SqliteError.ERROR)
throw new SqliteExecutionException ();
}
if (err == SqliteError.BUSY)
throw new SqliteBusyException();
if (err == SqliteError.MISUSE)
throw new SqliteExecutionException();
// err is either ROW or DONE.
return err == SqliteError.ROW;
}
#endregion
#region Public Methods
public void Cancel ()
{
}
public string BindParameters2()
{
string text = sql;
// There used to be a crazy regular expression here, but it caused Mono
// to go into an infinite loop of some sort when there were no parameters
// in the SQL string. That was too complicated anyway.
// Here we search for substrings of the form [:?]wwwww where w is a letter or digit
// (not sure what a legitimate Sqlite3 identifier is), except those within quotes.
char inquote = (char)0;
int counter = 0;
for (int i = 0; i < text.Length; i++) {
char c = text[i];
if (c == inquote) {
inquote = (char)0;
} else if (inquote == (char)0 && (c == '\'' || c == '"')) {
inquote = c;
} else if (inquote == (char)0 && (c == ':' || c == '?')) {
int start = i;
while (++i < text.Length && char.IsLetterOrDigit(text[i])) { } // scan to end
string name = text.Substring(start, i-start);
SqliteParameter p;
if (name.Length > 1)
p = Parameters[name];
else
p = Parameters[counter];
string value = "'" + Convert.ToString(p.Value).Replace("'", "''") + "'";
text = text.Remove(start, name.Length).Insert(start, value);
i += value.Length - name.Length - 1;
counter++;
}
}
return text;
}
public void Prepare ()
{
// There isn't much we can do here. If a table schema
// changes after preparing a statement, Sqlite bails,
// so we can only compile statements right before we
// want to run them.
if (prepared) return;
if (Parameters.Count > 0 && parent_conn.Version == 2)
{
sql = BindParameters2();
}
prepared = true;
}
IDbDataParameter IDbCommand.CreateParameter()
{
return CreateParameter ();
}
public SqliteParameter CreateParameter ()
{
return new SqliteParameter ();
}
public int ExecuteNonQuery ()
{
int rows_affected;
ExecuteReader (CommandBehavior.Default, false, out rows_affected);
return rows_affected;
}
public object ExecuteScalar ()
{
SqliteDataReader r = ExecuteReader ();
if (r == null || !r.Read ()) {
return null;
}
object o = r[0];
r.Close ();
return o;
}
IDataReader IDbCommand.ExecuteReader ()
{
return ExecuteReader ();
}
IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
{
return ExecuteReader (behavior);
}
public SqliteDataReader ExecuteReader ()
{
return ExecuteReader (CommandBehavior.Default);
}
public SqliteDataReader ExecuteReader (CommandBehavior behavior)
{
int r;
return ExecuteReader (behavior, true, out r);
}
public SqliteDataReader ExecuteReader (CommandBehavior behavior, bool want_results, out int rows_affected)
{
Prepare ();
// The SQL string may contain multiple sql commands, so the main
// thing to do is have Sqlite iterate through the commands.
// If want_results, only the last command is returned as a
// DataReader. Otherwise, no command is returned as a
// DataReader.
IntPtr psql; // pointer to SQL command
// Sqlite 2 docs say this: By default, SQLite assumes that all data uses a fixed-size 8-bit
// character (iso8859). But if you give the --enable-utf8 option to the configure script, then the
// library assumes UTF-8 variable sized characters. This makes a difference for the LIKE and GLOB
// operators and the LENGTH() and SUBSTR() functions. The static string sqlite_encoding will be set
// to either "UTF-8" or "iso8859" to indicate how the library was compiled. In addition, the sqlite.h
// header file will define one of the macros SQLITE_UTF8 or SQLITE_ISO8859, as appropriate.
//
// We have no way of knowing whether Sqlite 2 expects ISO8859 or UTF-8, but ISO8859 seems to be the
// default. Therefore, we need to use an ISO8859(-1) compatible encoding, like ANSI.
// OTOH, the user may want to specify the encoding of the bytes stored in the database, regardless
// of what Sqlite is treating them as,
// For Sqlite 3, we use the UTF-16 prepare function, so we need a UTF-16 string.
if (parent_conn.Version == 2)
psql = Sqlite.StringToHeap (sql.Trim(), parent_conn.Encoding);
else
psql = Marshal.StringToHGlobalUni (sql.Trim());
IntPtr pzTail = psql;
IntPtr errMsgPtr;
parent_conn.StartExec ();
rows_affected = 0;
try {
while (true) {
IntPtr pStmt;
GetNextStatement(pzTail, out pzTail, out pStmt);
if (pStmt == IntPtr.Zero)
throw new Exception();
// pzTail is positioned after the last byte in the
// statement, which will be the NULL character if
// this was the last statement.
bool last = Marshal.ReadByte(pzTail) == 0;
try {
if (parent_conn.Version == 3)
BindParameters3 (pStmt);
if (last && want_results)
return new SqliteDataReader (this, pStmt, parent_conn.Version);
ExecuteStatement(pStmt);
if (last) // rows_affected is only used if !want_results
rows_affected = NumChanges ();
} finally {
if (parent_conn.Version == 3)
Sqlite.sqlite3_finalize (pStmt);
else
Sqlite.sqlite_finalize (pStmt, out errMsgPtr);
}
if (last) break;
}
return null;
} finally {
parent_conn.EndExec ();
Marshal.FreeHGlobal (psql);
}
}
public int LastInsertRowID ()
{
return parent_conn.LastInsertRowId;
}
private string GetError3() {
return Marshal.PtrToStringUni (Sqlite.sqlite3_errmsg16 (parent_conn.Handle));
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "OfflineMessageModule")]
public class OfflineMessageModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool enabled = true;
private List<Scene> m_SceneList = new List<Scene>();
private string m_RestURL = String.Empty;
IMessageTransferModule m_TransferModule = null;
private bool m_ForwardOfflineGroupMessages = true;
public void Initialise(IConfigSource config)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf == null)
{
enabled = false;
return;
}
if (cnf != null && cnf.GetString("OfflineMessageModule", "None") !=
"OfflineMessageModule")
{
enabled = false;
return;
}
m_RestURL = cnf.GetString("OfflineMessageURL", "");
if (m_RestURL == "")
{
m_log.Error("[OFFLINE MESSAGING] Module was enabled, but no URL is given, disabling");
enabled = false;
return;
}
m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", m_ForwardOfflineGroupMessages);
}
public void AddRegion(Scene scene)
{
if (!enabled)
return;
lock (m_SceneList)
{
m_SceneList.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
}
}
public void RegionLoaded(Scene scene)
{
if (!enabled)
return;
if (m_TransferModule == null)
{
m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
{
scene.EventManager.OnNewClient -= OnNewClient;
enabled = false;
m_SceneList.Clear();
m_log.Error("[OFFLINE MESSAGING] No message transfer module is enabled. Diabling offline messages");
}
m_TransferModule.OnUndeliveredMessage += UndeliveredMessage;
}
}
public void RemoveRegion(Scene scene)
{
if (!enabled)
return;
lock (m_SceneList)
{
m_SceneList.Remove(scene);
}
}
public void PostInitialise()
{
if (!enabled)
return;
m_log.Debug("[OFFLINE MESSAGING] Offline messages enabled");
}
public string Name
{
get { return "OfflineMessageModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Close()
{
}
private Scene FindScene(UUID agentID)
{
foreach (Scene s in m_SceneList)
{
ScenePresence presence = s.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return s;
}
return null;
}
private IClientAPI FindClient(UUID agentID)
{
foreach (Scene s in m_SceneList)
{
ScenePresence presence = s.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return presence.ControllingClient;
}
return null;
}
private void OnNewClient(IClientAPI client)
{
client.OnRetrieveInstantMessages += RetrieveInstantMessages;
}
private void RetrieveInstantMessages(IClientAPI client)
{
if (m_RestURL != "")
{
m_log.DebugFormat("[OFFLINE MESSAGING]: Retrieving stored messages for {0}", client.AgentId);
List<GridInstantMessage> msglist
= SynchronousRestObjectRequester.MakeRequest<UUID, List<GridInstantMessage>>(
"POST", m_RestURL + "/RetrieveMessages/", client.AgentId);
if (msglist == null)
{
m_log.WarnFormat("[OFFLINE MESSAGING]: WARNING null message list.");
return;
}
foreach (GridInstantMessage im in msglist)
{
if (im.dialog == (byte)InstantMessageDialog.InventoryOffered)
// send it directly or else the item will be given twice
client.SendInstantMessage(im);
else
{
// Send through scene event manager so all modules get a chance
// to look at this message before it gets delivered.
//
// Needed for proper state management for stored group
// invitations
//
Scene s = FindScene(client.AgentId);
if (s != null)
s.EventManager.TriggerIncomingInstantMessage(im);
}
}
}
}
private void UndeliveredMessage(GridInstantMessage im)
{
if (im.dialog != (byte)InstantMessageDialog.MessageFromObject &&
im.dialog != (byte)InstantMessageDialog.MessageFromAgent &&
im.dialog != (byte)InstantMessageDialog.GroupNotice &&
im.dialog != (byte)InstantMessageDialog.GroupInvitation &&
im.dialog != (byte)InstantMessageDialog.InventoryOffered)
{
return;
}
if (!m_ForwardOfflineGroupMessages)
{
if (im.dialog == (byte)InstantMessageDialog.GroupNotice ||
im.dialog == (byte)InstantMessageDialog.GroupInvitation)
return;
}
bool success = SynchronousRestObjectRequester.MakeRequest<GridInstantMessage, bool>(
"POST", m_RestURL+"/SaveMessage/", im, 10000);
if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
{
IClientAPI client = FindClient(new UUID(im.fromAgentID));
if (client == null)
return;
client.SendInstantMessage(new GridInstantMessage(
null, new UUID(im.toAgentID),
"System", new UUID(im.fromAgentID),
(byte)InstantMessageDialog.MessageFromAgent,
"User is not logged in. "+
(success ? "Message saved." : "Message not saved"),
false, new Vector3()));
}
}
}
}
| |
using J2N;
using System;
using System.Runtime.CompilerServices;
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.
*/
/* some code derived from jodk: http://code.google.com/p/jodk/ (apache 2.0)
* asin() derived from fdlibm: http://www.netlib.org/fdlibm/e_asin.c (public domain):
* =============================================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* =============================================================================
*/
/// <summary>
/// Math functions that trade off accuracy for speed. </summary>
public static class SloppyMath // LUCENENET: Changed to static
{
/// <summary>
/// Returns the distance in kilometers between two points
/// specified in decimal degrees (latitude/longitude). </summary>
/// <param name="lat1"> Latitude of the first point. </param>
/// <param name="lon1"> Longitude of the first point. </param>
/// <param name="lat2"> Latitude of the second point. </param>
/// <param name="lon2"> Longitude of the second point. </param>
/// <returns> distance in kilometers. </returns>
public static double Haversin(double lat1, double lon1, double lat2, double lon2)
{
double x1 = lat1 * TO_RADIANS;
double x2 = lat2 * TO_RADIANS;
double h1 = 1 - Cos(x1 - x2);
double h2 = 1 - Cos((lon1 - lon2) * TO_RADIANS);
double h = (h1 + Cos(x1) * Cos(x2) * h2) / 2;
double avgLat = (x1 + x2) / 2d;
double diameter = EarthDiameter(avgLat);
return diameter * Asin(Math.Min(1, Math.Sqrt(h)));
}
/// <summary>
/// Returns the trigonometric cosine of an angle.
/// <para/>
/// Error is around 1E-15.
/// <para/>
/// Special cases:
/// <list type="bullet">
/// <item><description>If the argument is <see cref="double.NaN"/> or an infinity, then the result is <see cref="double.NaN"/>.</description></item>
/// </list>
/// </summary>
/// <param name="a"> An angle, in radians. </param>
/// <returns> The cosine of the argument. </returns>
/// <seealso cref="Math.Cos(double)"/>
public static double Cos(double a)
{
if (a < 0.0)
{
a = -a;
}
if (a > SIN_COS_MAX_VALUE_FOR_INT_MODULO)
{
return Math.Cos(a);
}
// index: possibly outside tables range.
int index = (int)(a * SIN_COS_INDEXER + 0.5);
double delta = (a - index * SIN_COS_DELTA_HI) - index * SIN_COS_DELTA_LO;
// Making sure index is within tables range.
// Last value of each table is the same than first, so we ignore it (tabs size minus one) for modulo.
index &= (SIN_COS_TABS_SIZE - 2); // index % (SIN_COS_TABS_SIZE-1)
double indexCos = cosTab[index];
double indexSin = sinTab[index];
return indexCos + delta * (-indexSin + delta * (-indexCos * ONE_DIV_F2 + delta * (indexSin * ONE_DIV_F3 + delta * indexCos * ONE_DIV_F4)));
}
/// <summary>
/// Returns the arc sine of a value.
/// <para/>
/// The returned angle is in the range <i>-pi</i>/2 through <i>pi</i>/2.
/// Error is around 1E-7.
/// <para/>
/// Special cases:
/// <list type="bullet">
/// <item><description>If the argument is <see cref="double.NaN"/> or its absolute value is greater than 1, then the result is <see cref="double.NaN"/>.</description></item>
/// </list>
/// </summary>
/// <param name="a"> the value whose arc sine is to be returned. </param>
/// <returns> arc sine of the argument </returns>
/// <seealso cref="Math.Asin(double)"/>
// because asin(-x) = -asin(x), asin(x) only needs to be computed on [0,1].
// ---> we only have to compute asin(x) on [0,1].
// For values not close to +-1, we use look-up tables;
// for values near +-1, we use code derived from fdlibm.
public static double Asin(double a)
{
bool negateResult;
if (a < 0.0)
{
a = -a;
negateResult = true;
}
else
{
negateResult = false;
}
if (a <= ASIN_MAX_VALUE_FOR_TABS)
{
int index = (int)(a * ASIN_INDEXER + 0.5);
double delta = a - index * ASIN_DELTA;
double result = asinTab[index] + delta * (asinDer1DivF1Tab[index] + delta * (asinDer2DivF2Tab[index] + delta * (asinDer3DivF3Tab[index] + delta * asinDer4DivF4Tab[index])));
return negateResult ? -result : result;
} // value > ASIN_MAX_VALUE_FOR_TABS, or value is NaN
else
{
// this part is derived from fdlibm.
if (a < 1.0)
{
double t = (1.0 - a) * 0.5;
double p = t * (ASIN_PS0 + t * (ASIN_PS1 + t * (ASIN_PS2 + t * (ASIN_PS3 + t * (ASIN_PS4 + t * ASIN_PS5)))));
double q = 1.0 + t * (ASIN_QS1 + t * (ASIN_QS2 + t * (ASIN_QS3 + t * ASIN_QS4)));
double s = Math.Sqrt(t);
double z = s + s * (p / q);
double result = ASIN_PIO2_HI - ((z + z) - ASIN_PIO2_LO);
return negateResult ? -result : result;
} // value >= 1.0, or value is NaN
else
{
if (a == 1.0)
{
return negateResult ? -Math.PI / 2 : Math.PI / 2;
}
else
{
return double.NaN;
}
}
}
}
/// <summary>
/// Return an approximate value of the diameter of the earth at the given latitude, in kilometers. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double EarthDiameter(double latitude)
{
if(double.IsNaN(latitude))
return double.NaN;
int index = (int)(Math.Abs(latitude) * RADIUS_INDEXER + 0.5) % earthDiameterPerLatitude.Length;
return earthDiameterPerLatitude[index];
}
// haversin
private const double TO_RADIANS = Math.PI / 180D;
// cos/asin
private const double ONE_DIV_F2 = 1 / 2.0;
private const double ONE_DIV_F3 = 1 / 6.0;
private const double ONE_DIV_F4 = 1 / 24.0;
private static readonly double PIO2_HI = J2N.BitConversion.Int64BitsToDouble(0x3FF921FB54400000L); // 1.57079632673412561417e+00 first 33 bits of pi/2
private static readonly double PIO2_LO = J2N.BitConversion.Int64BitsToDouble(0x3DD0B4611A626331L); // 6.07710050650619224932e-11 pi/2 - PIO2_HI
private static readonly double TWOPI_HI = 4 * PIO2_HI;
private static readonly double TWOPI_LO = 4 * PIO2_LO;
private const int SIN_COS_TABS_SIZE = (1 << 11) + 1;
private static readonly double SIN_COS_DELTA_HI = TWOPI_HI / (SIN_COS_TABS_SIZE - 1);
private static readonly double SIN_COS_DELTA_LO = TWOPI_LO / (SIN_COS_TABS_SIZE - 1);
private static readonly double SIN_COS_INDEXER = 1 / (SIN_COS_DELTA_HI + SIN_COS_DELTA_LO);
private static readonly double[] sinTab = new double[SIN_COS_TABS_SIZE];
private static readonly double[] cosTab = new double[SIN_COS_TABS_SIZE];
// Max abs value for fast modulo, above which we use regular angle normalization.
// this value must be < (Integer.MAX_VALUE / SIN_COS_INDEXER), to stay in range of int type.
// The higher it is, the higher the error, but also the faster it is for lower values.
// If you set it to ((Integer.MAX_VALUE / SIN_COS_INDEXER) * 0.99), worse accuracy on double range is about 1e-10.
internal static readonly double SIN_COS_MAX_VALUE_FOR_INT_MODULO = ((int.MaxValue >> 9) / SIN_COS_INDEXER) * 0.99;
// Supposed to be >= sin(77.2deg), as fdlibm code is supposed to work with values > 0.975,
// but seems to work well enough as long as value >= sin(25deg).
private static readonly double ASIN_MAX_VALUE_FOR_TABS = Math.Sin(73.0.ToRadians());
private const int ASIN_TABS_SIZE = (1 << 13) + 1;
private static readonly double ASIN_DELTA = ASIN_MAX_VALUE_FOR_TABS / (ASIN_TABS_SIZE - 1);
private static readonly double ASIN_INDEXER = 1 / ASIN_DELTA;
private static readonly double[] asinTab = new double[ASIN_TABS_SIZE];
private static readonly double[] asinDer1DivF1Tab = new double[ASIN_TABS_SIZE];
private static readonly double[] asinDer2DivF2Tab = new double[ASIN_TABS_SIZE];
private static readonly double[] asinDer3DivF3Tab = new double[ASIN_TABS_SIZE];
private static readonly double[] asinDer4DivF4Tab = new double[ASIN_TABS_SIZE];
private static readonly double ASIN_PIO2_HI = J2N.BitConversion.Int64BitsToDouble(0x3FF921FB54442D18L); // 1.57079632679489655800e+00
private static readonly double ASIN_PIO2_LO = J2N.BitConversion.Int64BitsToDouble(0x3C91A62633145C07L); // 6.12323399573676603587e-17
private static readonly double ASIN_PS0 = J2N.BitConversion.Int64BitsToDouble(0x3fc5555555555555L); // 1.66666666666666657415e-01
private static readonly double ASIN_PS1 = J2N.BitConversion.Int64BitsToDouble(unchecked((long)0xbfd4d61203eb6f7dL)); // -3.25565818622400915405e-01
private static readonly double ASIN_PS2 = J2N.BitConversion.Int64BitsToDouble(0x3fc9c1550e884455L); // 2.01212532134862925881e-01
private static readonly double ASIN_PS3 = J2N.BitConversion.Int64BitsToDouble(unchecked((long)0xbfa48228b5688f3bL)); // -4.00555345006794114027e-02
private static readonly double ASIN_PS4 = J2N.BitConversion.Int64BitsToDouble(0x3f49efe07501b288L); // 7.91534994289814532176e-04
private static readonly double ASIN_PS5 = J2N.BitConversion.Int64BitsToDouble(0x3f023de10dfdf709L); // 3.47933107596021167570e-05
private static readonly double ASIN_QS1 = J2N.BitConversion.Int64BitsToDouble(unchecked((long)0xc0033a271c8a2d4bL)); // -2.40339491173441421878e+00
private static readonly double ASIN_QS2 = J2N.BitConversion.Int64BitsToDouble(0x40002ae59c598ac8L); // 2.02094576023350569471e+00
private static readonly double ASIN_QS3 = J2N.BitConversion.Int64BitsToDouble(unchecked((long)0xbfe6066c1b8d0159L)); // -6.88283971605453293030e-01
private static readonly double ASIN_QS4 = J2N.BitConversion.Int64BitsToDouble(0x3fb3b8c5b12e9282L); // 7.70381505559019352791e-02
private const int RADIUS_TABS_SIZE = (1 << 10) + 1;
private const double RADIUS_DELTA = (Math.PI / 2d) / (RADIUS_TABS_SIZE - 1);
private const double RADIUS_INDEXER = 1d / RADIUS_DELTA;
private static readonly double[] earthDiameterPerLatitude = new double[RADIUS_TABS_SIZE];
/// <summary>
/// Initializes look-up tables. </summary>
static SloppyMath()
{
// sin and cos
int SIN_COS_PI_INDEX = (SIN_COS_TABS_SIZE - 1) / 2;
int SIN_COS_PI_MUL_2_INDEX = 2 * SIN_COS_PI_INDEX;
int SIN_COS_PI_MUL_0_5_INDEX = SIN_COS_PI_INDEX / 2;
int SIN_COS_PI_MUL_1_5_INDEX = 3 * SIN_COS_PI_INDEX / 2;
for (int i = 0; i < SIN_COS_TABS_SIZE; i++)
{
// angle: in [0,2*PI].
double angle = i * SIN_COS_DELTA_HI + i * SIN_COS_DELTA_LO;
double sinAngle = Math.Sin(angle);
double cosAngle = Math.Cos(angle);
// For indexes corresponding to null cosine or sine, we make sure the value is zero
// and not an epsilon. this allows for a much better accuracy for results close to zero.
if (i == SIN_COS_PI_INDEX)
{
sinAngle = 0.0;
}
else if (i == SIN_COS_PI_MUL_2_INDEX)
{
sinAngle = 0.0;
}
else if (i == SIN_COS_PI_MUL_0_5_INDEX)
{
cosAngle = 0.0;
}
else if (i == SIN_COS_PI_MUL_1_5_INDEX)
{
cosAngle = 0.0;
}
sinTab[i] = sinAngle;
cosTab[i] = cosAngle;
}
// asin
for (int i = 0; i < ASIN_TABS_SIZE; i++)
{
// x: in [0,ASIN_MAX_VALUE_FOR_TABS].
double x = i * ASIN_DELTA;
asinTab[i] = Math.Asin(x);
double oneMinusXSqInv = 1.0 / (1 - x * x);
double oneMinusXSqInv0_5 = Math.Sqrt(oneMinusXSqInv);
double oneMinusXSqInv1_5 = oneMinusXSqInv0_5 * oneMinusXSqInv;
double oneMinusXSqInv2_5 = oneMinusXSqInv1_5 * oneMinusXSqInv;
double oneMinusXSqInv3_5 = oneMinusXSqInv2_5 * oneMinusXSqInv;
asinDer1DivF1Tab[i] = oneMinusXSqInv0_5;
asinDer2DivF2Tab[i] = (x * oneMinusXSqInv1_5) * ONE_DIV_F2;
asinDer3DivF3Tab[i] = ((1 + 2 * x * x) * oneMinusXSqInv2_5) * ONE_DIV_F3;
asinDer4DivF4Tab[i] = ((5 + 2 * x * (2 + x * (5 - 2 * x))) * oneMinusXSqInv3_5) * ONE_DIV_F4;
}
// WGS84 earth-ellipsoid major (a) and minor (b) radius
const double a = 6378137; // [m]
const double b = 6356752.31420; // [m]
double a2 = a * a;
double b2 = b * b;
earthDiameterPerLatitude[0] = 2 * a / 1000d;
earthDiameterPerLatitude[RADIUS_TABS_SIZE - 1] = 2 * b / 1000d;
// earth radius
for (int i = 1; i < RADIUS_TABS_SIZE - 1; i++)
{
double lat = Math.PI * i / (2d * RADIUS_TABS_SIZE - 1);
double one = Math.Pow(a2 * Math.Cos(lat), 2);
double two = Math.Pow(b2 * Math.Sin(lat), 2);
double three = Math.Pow(a * Math.Cos(lat), 2);
double four = Math.Pow(b * Math.Sin(lat), 2);
double radius = Math.Sqrt((one + two) / (three + four));
earthDiameterPerLatitude[i] = 2 * radius / 1000d;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using XamarinAzure.Backend.Areas.HelpPage.ModelDescriptions;
using XamarinAzure.Backend.Areas.HelpPage.Models;
namespace XamarinAzure.Backend.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
internal sealed class WebSocketHandle
{
/// <summary>GUID appended by the server as part of the security key response. Defined in the RFC.</summary>
private const string WSServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private readonly CancellationTokenSource _abortSource = new CancellationTokenSource();
private WebSocketState _state = WebSocketState.Connecting;
private WebSocket _webSocket;
public static WebSocketHandle Create() => new WebSocketHandle();
public static bool IsValid(WebSocketHandle handle) => handle != null;
public WebSocketCloseStatus? CloseStatus => _webSocket?.CloseStatus;
public string CloseStatusDescription => _webSocket?.CloseStatusDescription;
public WebSocketState State => _webSocket?.State ?? _state;
public string SubProtocol => _webSocket?.SubProtocol;
public static void CheckPlatformSupport() { /* nop */ }
public void Dispose()
{
_state = WebSocketState.Closed;
_webSocket?.Dispose();
}
public void Abort()
{
_abortSource.Cancel();
_webSocket?.Abort();
}
public Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) =>
_webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
public Task SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) =>
_webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
public Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) =>
_webSocket.ReceiveAsync(buffer, cancellationToken);
public ValueTask<ValueWebSocketReceiveResult> ReceiveAsync(Memory<byte> buffer, CancellationToken cancellationToken) =>
_webSocket.ReceiveAsync(buffer, cancellationToken);
public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken);
public Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
private sealed class DirectManagedHttpClientHandler : HttpClientHandler
{
private const string ManagedHandlerEnvVar = "COMPlus_UseManagedHttpClientHandler";
private static readonly LocalDataStoreSlot s_managedHandlerSlot = GetSlot();
private static readonly object s_true = true;
private static LocalDataStoreSlot GetSlot()
{
LocalDataStoreSlot slot = Thread.GetNamedDataSlot(ManagedHandlerEnvVar);
if (slot != null)
{
return slot;
}
try
{
return Thread.AllocateNamedDataSlot(ManagedHandlerEnvVar);
}
catch (ArgumentException) // in case of a race condition where multiple threads all try to allocate the slot concurrently
{
return Thread.GetNamedDataSlot(ManagedHandlerEnvVar);
}
}
public static DirectManagedHttpClientHandler CreateHandler()
{
Thread.SetData(s_managedHandlerSlot, s_true);
try
{
return new DirectManagedHttpClientHandler();
}
finally { Thread.SetData(s_managedHandlerSlot, null); }
}
public new Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken) =>
base.SendAsync(request, cancellationToken);
}
public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
HttpResponseMessage response = null;
try
{
// Create the request message, including a uri with ws{s} switched to http{s}.
uri = new UriBuilder(uri) { Scheme = (uri.Scheme == UriScheme.Ws) ? UriScheme.Http : UriScheme.Https }.Uri;
var request = new HttpRequestMessage(HttpMethod.Get, uri);
if (options._requestHeaders?.Count > 0) // use field to avoid lazily initializing the collection
{
foreach (string key in options.RequestHeaders)
{
request.Headers.Add(key, options.RequestHeaders[key]);
}
}
// Create the security key and expected response, then build all of the request headers
KeyValuePair<string, string> secKeyAndSecWebSocketAccept = CreateSecKeyAndSecWebSocketAccept();
AddWebSocketHeaders(request, secKeyAndSecWebSocketAccept.Key, options);
// Create the handler for this request and populate it with all of the options.
DirectManagedHttpClientHandler handler = DirectManagedHttpClientHandler.CreateHandler();
handler.UseDefaultCredentials = options.UseDefaultCredentials;
handler.Credentials = options.Credentials;
handler.Proxy = options.Proxy;
handler.CookieContainer = options.Cookies;
if (options._clientCertificates?.Count > 0) // use field to avoid lazily initializing the collection
{
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.AddRange(options.ClientCertificates);
}
// Issue the request. The response must be status code 101.
CancellationTokenSource linkedCancellation, externalAndAbortCancellation;
if (cancellationToken.CanBeCanceled) // avoid allocating linked source if external token is not cancelable
{
linkedCancellation =
externalAndAbortCancellation =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _abortSource.Token);
}
else
{
linkedCancellation = null;
externalAndAbortCancellation = _abortSource;
}
using (linkedCancellation)
{
response = await handler.SendAsync(request, externalAndAbortCancellation.Token).ConfigureAwait(false);
externalAndAbortCancellation.Token.ThrowIfCancellationRequested(); // poll in case sends/receives in request/response didn't observe cancellation
}
if (response.StatusCode != HttpStatusCode.SwitchingProtocols)
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
// The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values.
ValidateHeader(response.Headers, HttpKnownHeaderNames.Connection, "Upgrade");
ValidateHeader(response.Headers, HttpKnownHeaderNames.Upgrade, "websocket");
ValidateHeader(response.Headers, HttpKnownHeaderNames.SecWebSocketAccept, secKeyAndSecWebSocketAccept.Value);
// The SecWebSocketProtocol header is optional. We should only get it with a non-empty value if we requested subprotocols,
// and then it must only be one of the ones we requested. If we got a subprotocol other than one we requested (or if we
// already got one in a previous header), fail. Otherwise, track which one we got.
string subprotocol = null;
IEnumerable<string> subprotocolEnumerableValues;
if (response.Headers.TryGetValues(HttpKnownHeaderNames.SecWebSocketProtocol, out subprotocolEnumerableValues))
{
Debug.Assert(subprotocolEnumerableValues is string[]);
string[] subprotocolArray = (string[])subprotocolEnumerableValues;
if (subprotocolArray.Length > 0 && !string.IsNullOrEmpty(subprotocolArray[0]))
{
subprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, subprotocolArray[0], StringComparison.OrdinalIgnoreCase));
if (subprotocol == null)
{
throw new WebSocketException(
WebSocketError.UnsupportedProtocol,
SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol, string.Join(", ", options.RequestedSubProtocols), string.Join(", ", subprotocolArray)));
}
}
}
// Get or create the buffer to use
const int MinBufferSize = 14; // from ManagedWebSocket.MaxMessageHeaderLength
ArraySegment<byte> optionsBuffer = options.Buffer.GetValueOrDefault();
Memory<byte> buffer =
optionsBuffer.Count >= MinBufferSize ? optionsBuffer : // use the provided buffer if it's big enough
options.ReceiveBufferSize >= MinBufferSize ? new byte[options.ReceiveBufferSize] : // or use the requested size if it's big enough
Memory<byte>.Empty; // or let WebSocket.CreateFromStream use its default
// Get the response stream and wrap it in a web socket.
Stream connectedStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
Debug.Assert(connectedStream.CanWrite);
Debug.Assert(connectedStream.CanRead);
_webSocket = WebSocket.CreateFromStream(
connectedStream,
isServer: false,
subprotocol,
options.KeepAliveInterval,
buffer);
}
catch (Exception exc)
{
if (_state < WebSocketState.Closed)
{
_state = WebSocketState.Closed;
}
Abort();
response?.Dispose();
if (exc is WebSocketException)
{
throw;
}
throw new WebSocketException(SR.net_webstatus_ConnectFailure, exc);
}
}
/// <param name="secKey">The generated security key to send in the Sec-WebSocket-Key header.</param>
private static void AddWebSocketHeaders(HttpRequestMessage request, string secKey, ClientWebSocketOptions options)
{
request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Upgrade, "websocket");
request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.SecWebSocketVersion, "13");
request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.SecWebSocketKey, secKey);
if (options._requestedSubProtocols?.Count > 0)
{
request.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, string.Join(", ", options.RequestedSubProtocols));
}
}
/// <summary>
/// Creates a pair of a security key for sending in the Sec-WebSocket-Key header and
/// the associated response we expect to receive as the Sec-WebSocket-Accept header value.
/// </summary>
/// <returns>A key-value pair of the request header security key and expected response header value.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "Required by RFC6455")]
private static KeyValuePair<string, string> CreateSecKeyAndSecWebSocketAccept()
{
string secKey = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
using (SHA1 sha = SHA1.Create())
{
return new KeyValuePair<string, string>(
secKey,
Convert.ToBase64String(sha.ComputeHash(Encoding.ASCII.GetBytes(secKey + WSServerGuid))));
}
}
private static void ValidateHeader(HttpHeaders headers, string name, string expectedValue)
{
if (!headers.TryGetValues(name, out IEnumerable<string> values))
{
ThrowConnectFailure();
}
Debug.Assert(values is string[]);
string[] array = (string[])values;
if (array.Length != 1 || !string.Equals(array[0], expectedValue, StringComparison.OrdinalIgnoreCase))
{
throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidResponseHeader, name, string.Join(", ", array)));
}
}
private static void ThrowConnectFailure() => throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
}
| |
/***************************************************************************
* MusicFile.cs
*
* Copyright (C) 2007 Alan McGovern
* Written by Alan McGovern <alan.mcgovern@gmail.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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;
namespace Gphoto2
{
/// <summary>
/// Represents a music track
/// </summary>
public class MusicFile : File
{
/// <value>
/// The name of the album
/// </value>
public string Album
{
get { return GetString("AlbumName"); }
set { SetValue("AlbumName", value); }
}
/// <value>
/// The name of the artist
/// </value>
public string Artist
{
get { return GetString("Artist"); }
set { SetValue("Artist", value); }
}
/// <value>
/// The bitrate of the track
/// </value>
public int Bitrate
{
get { return GetInt("AudioBitDepth"); }
set { SetValue("AudioBitDepth", value); }
}
/// <value>
/// The duration of the track in seconds
/// </value>
public int Duration
{
get { return GetInt("Duration"); }
set { SetValue("Duration", value); }
}
/// <value>
/// The format of the track
/// </value>
public string Format
{
get { return GetString("AudioWAVECodec"); }
set { SetValue("AudioWAVECodec", value); }
}
/// <value>
/// The genre of the track
/// </value>
public string Genre
{
get {return GetString("Genre"); }
set { SetValue("Genre", value); }
}
/// <value>
/// The title of the track
/// </value>
public string Title
{
get { return GetString("Name"); }
set { SetValue("Name", value); }
}
/// <value>
/// The tracknumber of the track
/// </value>
public int Track
{
get { return GetInt("Track"); }
set { SetValue("Track", value); }
}
/// <value>
/// The number of times the track has been played
/// </value>
public int UseCount
{
get { return GetInt("UseCount"); }
set { SetValue("UseCount", value); }
}
/// <value>
/// The year the track was recorded
/// </value>
public int Year
{
get
{
int year;
string releaseDate = GetString("OriginalReleaseDate");
if(releaseDate.Length > 4)
releaseDate = releaseDate.Substring(0, 4);
if(!int.TryParse(releaseDate, out year))
return 0;
return year;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("Year");
SetValue("OriginalReleaseDate", string.Format("{0:0000}0101T0000.0", value));
}
}
internal MusicFile(Camera camera, FileSystem fs, string metadata, string directory, string filename, bool local)
: base (camera, fs, metadata, directory, filename, local)
{
}
/// <summary>
/// Creates a new music file
/// </summary>
/// <param name="directory">The path to the track
/// A <see cref="System.String"/>
/// </param>
/// <param name="filename">The filename of the track
/// A <see cref="System.String"/>
/// </param>
public MusicFile(string directory, string filename)
: this(null, null, "", directory, filename, true)
{
}
/// <summary>
/// Creates a new file from the supplied stream
/// </summary>
/// <param name="stream">The stream containing the file data
/// A <see cref="Stream"/>
/// </param>
// public MusicFile(System.IO.Stream stream)
// : base(stream)
// {
//
// }
public override bool Equals (object o)
{
MusicFile f = o as MusicFile;
return f == null ? false : Equals(f);
}
public bool Equals(MusicFile file)
{
return file == null
? false : this.Album == file.Album
&& this.Artist == file.Artist
&& this.Title == file.Title
&& this.Track == file.Track;
}
public override int GetHashCode ()
{
int result = 0;
result ^= Album.GetHashCode();
result ^= Artist.GetHashCode();
result ^= Title.GetHashCode();
result ^= Track;
return result;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
using Microsoft.Win32;
namespace Microsoft.PythonTools.Analysis {
internal class PyLibAnalyzer : IDisposable {
private const string AnalysisLimitsKey = @"Software\Microsoft\PythonTools\" + AssemblyVersionInfo.VSVersion +
@"\Analysis\StandardLibrary";
private readonly Guid _id;
private readonly Version _version;
private readonly string _interpreter;
private readonly List<PythonLibraryPath> _library;
private readonly string _outDir;
private readonly List<string> _baseDb;
private readonly string _logPrivate, _logGlobal, _logDiagnostic;
private readonly bool _dryRun;
private readonly string _waitForAnalysis;
private readonly int _repeatCount;
private bool _all;
private FileStream _pidMarkerFile;
private readonly AnalyzerStatusUpdater _updater;
private readonly CancellationToken _cancel;
private TextWriter _listener;
internal readonly List<List<ModulePath>> _scrapeFileGroups, _analyzeFileGroups;
private readonly HashSet<string> _treatPathsAsStandardLibrary;
private IEnumerable<string> _readModulePath;
private int _progressOffset;
private int _progressTotal;
private const string BuiltinName2x = "__builtin__.idb";
private const string BuiltinName3x = "builtins.idb";
private static readonly HashSet<string> SkipBuiltinNames = new HashSet<string> {
"__main__"
};
private static void Help() {
Console.WriteLine("Python Library Analyzer {0} ({1})",
AssemblyVersionInfo.StableVersion,
AssemblyVersionInfo.Version);
Console.WriteLine("Generates a cached analysis database for a Python interpreter.");
Console.WriteLine();
Console.WriteLine(" /id [GUID] - specify GUID of the interpreter being used");
Console.WriteLine(" /v[ersion] [version] - specify language version to be used (x.y format)");
Console.WriteLine(" /py[thon] [filename] - full path to the Python interpreter to use");
Console.WriteLine(" /lib[rary] [directory] - full path to the Python library to analyze");
Console.WriteLine(" /outdir [output dir] - specify output directory for analysis (default " +
"is current dir)");
Console.WriteLine(" /all - don't skip file groups that look up to date");
Console.WriteLine(" /basedb [input dir] - specify directory for baseline analysis.");
Console.WriteLine(" /log [filename] - write analysis log");
Console.WriteLine(" /glog [filename] - write start/stop events");
Console.WriteLine(" /diag [filename] - write detailed (CSV) analysis log");
Console.WriteLine(" /dryrun - don't analyze, but write out list of files that " +
"would have been analyzed.");
Console.WriteLine(" /wait [identifier] - wait for the specified analysis to complete.");
Console.WriteLine(" /repeat [count] - repeat up to count times if needed (default 3).");
}
private static IEnumerable<KeyValuePair<string, string>> ParseArguments(IEnumerable<string> args) {
string currentKey = null;
using (var e = args.GetEnumerator()) {
while (e.MoveNext()) {
if (e.Current.StartsWith("/")) {
if (currentKey != null) {
yield return new KeyValuePair<string, string>(currentKey, null);
}
currentKey = e.Current.Substring(1).Trim();
} else {
yield return new KeyValuePair<string, string>(currentKey, e.Current);
currentKey = null;
}
}
if (currentKey != null) {
yield return new KeyValuePair<string, string>(currentKey, null);
}
}
}
public static int Main(string[] args) {
PyLibAnalyzer inst;
try {
inst = MakeFromArguments(args);
} catch (ArgumentNullException ex) {
Console.Error.WriteLine("{0} is a required argument", ex.Message);
Help();
return PythonTypeDatabase.InvalidArgumentExitCode;
} catch (ArgumentException ex) {
Console.Error.WriteLine("'{0}' is not valid for {1}", ex.Message, ex.ParamName);
Help();
return PythonTypeDatabase.InvalidArgumentExitCode;
} catch (IdentifierInUseException) {
Console.Error.WriteLine("This interpreter is already being analyzed.");
return PythonTypeDatabase.AlreadyGeneratingExitCode;
} catch (InvalidOperationException ex) {
Console.Error.WriteLine(ex.Message);
Help();
return PythonTypeDatabase.InvalidOperationExitCode;
}
using (inst) {
return inst.Run().GetAwaiter().GetResult();
}
}
private async Task<int> Run() {
#if DEBUG
// Running with the debugger attached will skip the
// unhandled exception handling to allow easier debugging.
if (Debugger.IsAttached) {
await RunWorker();
} else {
#endif
try {
await RunWorker();
} catch (IdentifierInUseException) {
// Database is currently being analyzed
Console.Error.WriteLine("This interpreter is already being analyzed.");
return PythonTypeDatabase.AlreadyGeneratingExitCode;
} catch (Exception e) {
Console.WriteLine("Error during analysis: {0}{1}", Environment.NewLine, e.ToString());
LogToGlobal("FAIL_STDLIB" + Environment.NewLine + e.ToString());
TraceError("Analysis failed{0}{1}", Environment.NewLine, e.ToString());
return -10;
}
#if DEBUG
}
#endif
LogToGlobal("DONE_STDLIB");
return 0;
}
private async Task RunWorker() {
WaitForOtherRun();
while (true) {
try {
await StartTraceListener();
break;
} catch (IOException) {
}
await Task.Delay(20000);
}
LogToGlobal("START_STDLIB");
for (int i = 0; i < _repeatCount && await Prepare(i == 0); ++i) {
await Scrape();
await Analyze();
}
await Epilogue();
}
public PyLibAnalyzer(
Guid id,
Version langVersion,
string interpreter,
IEnumerable<PythonLibraryPath> library,
List<string> baseDb,
string outDir,
string logPrivate,
string logGlobal,
string logDiagnostic,
bool rescanAll,
bool dryRun,
string waitForAnalysis,
int repeatCount
) {
_id = id;
_version = langVersion;
_interpreter = interpreter;
_baseDb = baseDb;
_outDir = outDir;
_logPrivate = logPrivate;
_logGlobal = logGlobal;
_logDiagnostic = logDiagnostic;
_all = rescanAll;
_dryRun = dryRun;
_waitForAnalysis = waitForAnalysis;
_repeatCount = repeatCount;
_scrapeFileGroups = new List<List<ModulePath>>();
_analyzeFileGroups = new List<List<ModulePath>>();
_treatPathsAsStandardLibrary = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
_library = library != null ? library.ToList() : new List<PythonLibraryPath>();
if (_id != Guid.Empty) {
var identifier = AnalyzerStatusUpdater.GetIdentifier(_id, _version);
_updater = new AnalyzerStatusUpdater(identifier);
// We worry about initialization exceptions here, specifically
// that our identifier may already be in use.
_updater.WaitForWorkerStarted();
try {
_updater.ThrowPendingExceptions();
// Immediately inform any listeners that we've started running
// successfully.
_updater.UpdateStatus(0, 0, "Initializing");
} catch (InvalidOperationException) {
// Thrown when we run out of space in our shared memory
// block. Disable updates for this run.
_updater.Dispose();
_updater = null;
}
}
// TODO: Link cancellation into the updater
_cancel = CancellationToken.None;
}
public void LogToGlobal(string message) {
if (!string.IsNullOrEmpty(_logGlobal)) {
for (int retries = 10; retries > 0; --retries) {
try {
File.AppendAllText(_logGlobal,
string.Format("{0:s} {1} {2}{3}",
DateTime.Now,
message,
Environment.CommandLine,
Environment.NewLine
)
);
break;
} catch (DirectoryNotFoundException) {
// Create the directory and try again
Directory.CreateDirectory(Path.GetDirectoryName(_logGlobal));
} catch (IOException) {
// racing with someone else generating?
Thread.Sleep(25);
}
}
}
}
public void Dispose() {
if (_updater != null) {
_updater.Dispose();
}
if (_listener != null) {
_listener.Flush();
_listener.Close();
_listener = null;
}
if (_pidMarkerFile != null) {
_pidMarkerFile.Close();
}
}
internal bool SkipUnchanged {
get { return !_all; }
}
private static PyLibAnalyzer MakeFromArguments(IEnumerable<string> args) {
var options = ParseArguments(args)
.ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.InvariantCultureIgnoreCase);
string value;
Guid id;
Version version;
string interpreter, outDir;
var library = new List<PythonLibraryPath>();
List<string> baseDb;
string logPrivate, logGlobal, logDiagnostic;
bool rescanAll, dryRun;
int repeatCount;
var cwd = Environment.CurrentDirectory;
if (!options.TryGetValue("id", out value)) {
id = Guid.Empty;
} else if (!Guid.TryParse(value, out id)) {
throw new ArgumentException(value, "id");
}
if (!options.TryGetValue("version", out value) && !options.TryGetValue("v", out value)) {
throw new ArgumentNullException("version");
} else if (!Version.TryParse(value, out version)) {
throw new ArgumentException(value, "version");
}
if (!options.TryGetValue("python", out value) && !options.TryGetValue("py", out value)) {
value = null;
}
if (!string.IsNullOrEmpty(value) && !CommonUtils.IsValidPath(value)) {
throw new ArgumentException(value, "python");
}
interpreter = value;
if (options.TryGetValue("library", out value) || options.TryGetValue("lib", out value)) {
if (!CommonUtils.IsValidPath(value)) {
throw new ArgumentException(value, "library");
}
if (Directory.Exists(value)) {
library.Add(new PythonLibraryPath(value, true, null));
var sitePackagesDir = Path.Combine(value, "site-packages");
if (Directory.Exists(sitePackagesDir)) {
library.Add(new PythonLibraryPath(sitePackagesDir, false, null));
library.AddRange(ModulePath.ExpandPathFiles(sitePackagesDir)
.Select(p => new PythonLibraryPath(p, false, null)));
}
}
}
if (!options.TryGetValue("outdir", out value)) {
value = cwd;
}
if (!CommonUtils.IsValidPath(value)) {
throw new ArgumentException(value, "outdir");
}
outDir = CommonUtils.GetAbsoluteDirectoryPath(cwd, value);
if (!options.TryGetValue("basedb", out value)) {
value = Environment.CurrentDirectory;
}
if (!CommonUtils.IsValidPath(value)) {
throw new ArgumentException(value, "basedb");
}
baseDb = value.Split(';').Select(p => CommonUtils.GetAbsoluteDirectoryPath(cwd, p)).ToList();
// Private log defaults to in current directory
if (!options.TryGetValue("log", out value)) {
value = "AnalysisLog.txt";
}
if (!CommonUtils.IsValidPath(value)) {
throw new ArgumentException(value, "log");
}
if (!Path.IsPathRooted(value)) {
value = CommonUtils.GetAbsoluteFilePath(outDir, value);
}
logPrivate = value;
// Global log defaults to null - we don't write start/stop events.
if (!options.TryGetValue("glog", out value)) {
value = null;
}
if (!string.IsNullOrEmpty(value) && !CommonUtils.IsValidPath(value)) {
throw new ArgumentException(value, "glog");
}
if (!string.IsNullOrEmpty(value) && !Path.IsPathRooted(value)) {
value = CommonUtils.GetAbsoluteFilePath(outDir, value);
}
logGlobal = value;
// Diagnostic log defaults to registry setting or else we don't use it.
if (!options.TryGetValue("diag", out value)) {
using (var key = Registry.CurrentUser.OpenSubKey(AnalysisLimitsKey)) {
if (key != null) {
value = key.GetValue("LogPath") as string;
}
}
}
if (!string.IsNullOrEmpty(value) && !CommonUtils.IsValidPath(value)) {
throw new ArgumentException(value, "diag");
}
if (!string.IsNullOrEmpty(value) && !Path.IsPathRooted(value)) {
value = CommonUtils.GetAbsoluteFilePath(outDir, value);
}
logDiagnostic = value;
string waitForAnalysis;
if (!options.TryGetValue("wait", out waitForAnalysis)) {
waitForAnalysis = null;
}
rescanAll = options.ContainsKey("all");
dryRun = options.ContainsKey("dryrun");
if (!options.TryGetValue("repeat", out value) || !int.TryParse(value, out repeatCount)) {
repeatCount = 3;
}
if (dryRun) {
repeatCount = 1;
}
return new PyLibAnalyzer(
id,
version,
interpreter,
library,
baseDb,
outDir,
logPrivate,
logGlobal,
logDiagnostic,
rescanAll,
dryRun,
waitForAnalysis,
repeatCount
);
}
internal async Task StartTraceListener() {
if (!CommonUtils.IsValidPath(_logPrivate)) {
return;
}
for (int retries = 10; retries > 0; --retries) {
try {
Directory.CreateDirectory(Path.GetDirectoryName(_logPrivate));
_listener = new StreamWriter(
new FileStream(_logPrivate, FileMode.Append, FileAccess.Write, FileShare.ReadWrite),
Encoding.UTF8
);
break;
} catch (IOException) {
} catch (UnauthorizedAccessException) {
}
await Task.Delay(100);
}
if (_listener != null) {
_listener.WriteLine();
TraceInformation("Start analysis");
} else {
LogToGlobal(string.Format("WARN: Unable to log output to {0}", _logPrivate));
}
}
internal void WaitForOtherRun() {
if (string.IsNullOrEmpty(_waitForAnalysis)) {
return;
}
if (_updater != null) {
_updater.UpdateStatus(0, 0, "Waiting for another refresh to start.");
}
bool everSeen = false;
using (var evt = new AutoResetEvent(false))
using (var listener = new AnalyzerStatusListener(d => {
AnalysisProgress progress;
if (d.TryGetValue(_waitForAnalysis, out progress)) {
everSeen = true;
var message = "Waiting for another refresh";
if (!string.IsNullOrEmpty(progress.Message)) {
message += ": " + progress.Message;
}
_updater.UpdateStatus(progress.Progress, progress.Maximum, message);
} else if (everSeen) {
try {
evt.Set();
} catch (ObjectDisposedException) {
// Event arrived after timeout and/or disposal of
// listener.
}
}
}, TimeSpan.FromSeconds(1.0))) {
if (!evt.WaitOne(TimeSpan.FromSeconds(60.0))) {
if (everSeen) {
// Running, but not finished yet
evt.WaitOne();
}
}
}
}
internal async Task<bool> Prepare(bool firstRun) {
if (_updater != null) {
_updater.UpdateStatus(0, 0, "Collecting files");
}
if (_library.Any()) {
if (firstRun) {
TraceWarning("Library was set explicitly - skipping path detection");
}
} else {
List<PythonLibraryPath> library = null;
// Execute the interpreter to get actual paths
for (int retries = 3; retries >= 0; --retries) {
try {
library = await PythonTypeDatabase.GetUncachedDatabaseSearchPathsAsync(_interpreter);
break;
} catch (InvalidOperationException ex) {
if (retries == 0) {
throw new InvalidOperationException("Cannot obtain search paths", ex);
}
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
throw new InvalidOperationException("Cannot obtain search paths", ex);
}
// May be a transient error, so try again shortly
await Task.Delay(500);
}
if (library == null) {
throw new InvalidOperationException("Cannot obtain search paths");
}
_library.AddRange(library);
}
if (File.Exists(_interpreter)) {
foreach (var module in IncludeModulesFromModulePath) {
_library.AddRange(await GetSearchPathsFromModulePath(_interpreter, module));
}
}
_treatPathsAsStandardLibrary.UnionWith(_library.Where(p => p.IsStandardLibrary).Select(p => p.Path));
List<List<ModulePath>> fileGroups = null;
for (int retries = 3; retries >= 0; --retries) {
try {
fileGroups = PythonTypeDatabase.GetDatabaseExpectedModules(_version, _library).ToList();
break;
} catch (UnauthorizedAccessException ex) {
if (retries == 0) {
throw new InvalidOperationException("Cannot obtain list of files", ex);
}
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
throw new InvalidOperationException("Cannot obtain list of files", ex);
}
// May be a transient error, so try again shortly.
await Task.Delay(500);
}
// HACK: Top-level modules in site-packages folders
// Need to analyse them after the standard library and treat their
// library paths as standard library so that output files are put at
// the top level in the database.
var sitePackageGroups = fileGroups
.Where(g => g.Any() && CommonUtils.GetFileOrDirectoryName(g[0].LibraryPath) == "site-packages")
.ToList();
fileGroups.RemoveAll(sitePackageGroups.Contains);
fileGroups.InsertRange(1, sitePackageGroups);
_treatPathsAsStandardLibrary.UnionWith(sitePackageGroups.Select(g => g[0].LibraryPath));
var databaseVer = Path.Combine(_outDir, "database.ver");
var databasePid = Path.Combine(_outDir, "database.pid");
var databasePath = Path.Combine(_outDir, "database.path");
if (!firstRun) {
// We've already run once, so we only want to do a partial
// update.
_all = false;
} else if (!PythonTypeDatabase.IsDatabaseVersionCurrent(_outDir)) {
// Database is not the current version, so we have to
// refresh all modules.
_all = true;
}
var filesInDatabase = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (_dryRun) {
TraceDryRun("WRITE;{0};{1}", databasePid, Process.GetCurrentProcess().Id);
TraceDryRun("DELETE;{0}", databaseVer);
TraceDryRun("WRITE;{0}", databasePath);
// The output directory for a dry run may be completely invalid.
// If the top level does not contain any .idb files, we won't
// bother recursing.
if (Directory.Exists(_outDir) &&
Directory.EnumerateFiles(_outDir, "*.idb", SearchOption.TopDirectoryOnly).Any()) {
filesInDatabase.UnionWith(Directory.EnumerateFiles(_outDir, "*.idb", SearchOption.AllDirectories));
}
} else if (firstRun) {
Directory.CreateDirectory(_outDir);
try {
_pidMarkerFile = new FileStream(
databasePid,
FileMode.CreateNew,
FileAccess.Write,
FileShare.ReadWrite | FileShare.Delete,
8,
FileOptions.DeleteOnClose
);
} catch (IOException) {
// File exists, which means we are already being refreshed
// by another instance.
throw new IdentifierInUseException();
}
// Let exceptions propagate from here. If we can't write to this
// file, we can't safely generate the DB.
var pidString = Process.GetCurrentProcess().Id.ToString();
var data = Encoding.UTF8.GetBytes(pidString);
_pidMarkerFile.Write(data, 0, data.Length);
_pidMarkerFile.Flush(true);
// Don't close the file (because it will be deleted on close).
// We will close it when we are disposed, or if we crash.
try {
File.Delete(databaseVer);
} catch (ArgumentException) {
} catch (IOException) {
} catch (NotSupportedException) {
} catch (UnauthorizedAccessException) {
}
for (int retries = 3; retries >= 0; --retries) {
try {
PythonTypeDatabase.WriteDatabaseSearchPaths(_outDir, _library);
break;
} catch (IOException ex) {
if (retries == 0) {
throw new InvalidOperationException("Unable to cache search paths", ex);
}
} catch (Exception ex) {
throw new InvalidOperationException("Unable to cache search paths", ex);
}
// May be a transient error, so try again shortly.
await Task.Delay(500);
}
}
if (!_dryRun) {
filesInDatabase.UnionWith(Directory.EnumerateFiles(_outDir, "*.idb", SearchOption.AllDirectories));
}
// Store the files we want to keep separately, in case we decide to
// delete the entire existing database.
var filesToKeep = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (!_all) {
var builtinModulePaths = await GetBuiltinModuleOutputFiles();
if (builtinModulePaths.Any()) {
var interpreterTime = File.GetLastWriteTimeUtc(_interpreter);
var outOfDate = builtinModulePaths.Where(p => !File.Exists(p) || File.GetLastWriteTimeUtc(p) <= interpreterTime);
if (!outOfDate.Any()) {
filesToKeep.UnionWith(builtinModulePaths);
} else {
TraceVerbose(
"Adding /all because the following built-in modules needed updating: {0}",
string.Join(";", outOfDate)
);
_all = true;
}
} else {
// Failed to get builtin names, so don't delete anything
// from the main output directory.
filesToKeep.UnionWith(
Directory.EnumerateFiles(_outDir, "*.idb", SearchOption.TopDirectoryOnly)
);
}
}
_progressTotal = 0;
_progressOffset = 0;
_scrapeFileGroups.Clear();
_analyzeFileGroups.Clear();
var candidateScrapeFileGroups = new List<List<ModulePath>>();
var candidateAnalyzeFileGroups = new List<List<ModulePath>>();
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var fileGroup in fileGroups) {
var toScrape = fileGroup.Where(mp => mp.IsCompiled && seen.Add(mp.ModuleName)).ToList();
var toAnalyze = fileGroup.Where(mp => seen.Add(mp.ModuleName)).ToList();
if (ShouldAnalyze(toScrape.Concat(toAnalyze))) {
if (!_all && _treatPathsAsStandardLibrary.Contains(fileGroup[0].LibraryPath)) {
_all = true;
TraceVerbose("Adding /all because the above module is builtin or stdlib");
// Include all the file groups we've already seen.
_scrapeFileGroups.InsertRange(0, candidateScrapeFileGroups);
_analyzeFileGroups.InsertRange(0, candidateAnalyzeFileGroups);
_progressTotal += candidateScrapeFileGroups.Concat(candidateAnalyzeFileGroups).Sum(fg => fg.Count);
candidateScrapeFileGroups = null;
candidateAnalyzeFileGroups = null;
}
_progressTotal += toScrape.Count + toAnalyze.Count;
if (toScrape.Any()) {
_scrapeFileGroups.Add(toScrape);
}
if (toAnalyze.Any()) {
_analyzeFileGroups.Add(toAnalyze);
}
} else {
filesToKeep.UnionWith(fileGroup
.Where(mp => File.Exists(mp.SourceFile))
.Select(GetOutputFile));
if (candidateScrapeFileGroups != null) {
candidateScrapeFileGroups.Add(toScrape);
}
if (candidateAnalyzeFileGroups != null) {
candidateAnalyzeFileGroups.Add(toAnalyze);
}
}
}
if (!_all) {
filesInDatabase.ExceptWith(filesToKeep);
}
// Scale file removal by 10 because it's much quicker than analysis.
_progressTotal += filesInDatabase.Count / 10;
Clean(filesInDatabase, 10);
return _scrapeFileGroups.Any() || _analyzeFileGroups.Any();
}
internal static async Task<IEnumerable<PythonLibraryPath>> GetSearchPathsFromModulePath(
string interpreter,
string moduleName
) {
using (var proc = ProcessOutput.RunHiddenAndCapture(
interpreter,
"-E", // ignore environment
"-c", string.Format("import {0}; print('\\n'.join({0}.__path__[1:]))", moduleName)
)) {
if (await proc != 0) {
return Enumerable.Empty<PythonLibraryPath>();
}
return proc.StandardOutputLines
.Where(Directory.Exists)
.Select(path => new PythonLibraryPath(path, false, moduleName + "."))
.ToList();
}
}
bool ShouldAnalyze(IEnumerable<ModulePath> group) {
if (_all) {
return true;
}
foreach (var file in group.Where(f => File.Exists(f.SourceFile))) {
var destPath = GetOutputFile(file);
if (!File.Exists(destPath) ||
File.GetLastWriteTimeUtc(file.SourceFile) > File.GetLastWriteTimeUtc(destPath)) {
TraceVerbose("Including {0} because {1} needs updating", file.LibraryPath, file.FullName);
return true;
}
}
return false;
}
internal async Task<IEnumerable<string>> GetBuiltinModuleOutputFiles() {
if (string.IsNullOrEmpty(_interpreter)) {
return Enumerable.Empty<string>();
}
// Ignoring case because these will become file paths, even though
// they are case-sensitive module names.
var builtinNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
builtinNames.Add(_version.Major == 3 ? BuiltinName3x : BuiltinName2x);
using (var output = ProcessOutput.RunHiddenAndCapture(
_interpreter,
"-E", "-S",
"-c", "import sys; print('\\n'.join(sys.builtin_module_names))"
)) {
if (await output != 0) {
TraceInformation("Getting builtin names");
TraceInformation("Command {0}", output.Arguments);
if (output.StandardErrorLines.Any()) {
TraceError("Errors{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, output.StandardErrorLines));
}
return Enumerable.Empty<string>();
} else {
builtinNames = new HashSet<string>(output.StandardOutputLines);
}
}
if (builtinNames.Contains("clr")) {
bool isCli = false;
using (var output = ProcessOutput.RunHiddenAndCapture(_interpreter,
"-E", "-S",
"-c", "import sys; print(sys.platform)"
)) {
if (await output == 0) {
isCli = output.StandardOutputLines.Contains("cli");
}
}
if (isCli) {
// These should match IronPythonScraper.SPECIAL_MODULES
builtinNames.Remove("wpf");
builtinNames.Remove("clr");
}
}
TraceVerbose("Builtin names are: {0}", string.Join(", ", builtinNames.OrderBy(s => s, StringComparer.OrdinalIgnoreCase)));
return builtinNames
.Where(n => !SkipBuiltinNames.Contains(n))
.Where(CommonUtils.IsValidPath)
.Select(n => GetOutputFile(n));
}
internal void Clean(HashSet<string> files, int progressScale = 1) {
if (_updater != null) {
_updater.UpdateStatus(_progressOffset, _progressTotal, "Cleaning old files");
}
int modCount = 0;
TraceInformation("Deleting {0} files", files.Count);
bool traceDelete = files.Count < 10;
foreach (var file in files) {
if (_updater != null && ++modCount >= progressScale) {
modCount = 0;
_updater.UpdateStatus(++_progressOffset, _progressTotal, "Cleaning old files");
}
if (_dryRun) {
TraceDryRun("DELETE:{0}", file);
} else {
if (traceDelete) {
// Extra logging for occasional issues where a few files
// always get deleted.
TraceInformation("Deleting \"{0}\"", file);
} else {
TraceVerbose("Deleting \"{0}\"", file);
}
try {
File.Delete(file);
File.Delete(file + ".$memlist");
var dirName = Path.GetDirectoryName(file);
if (!Directory.EnumerateFileSystemEntries(dirName, "*", SearchOption.TopDirectoryOnly).Any()) {
TraceVerbose("Removing empty directory \"{0}\"", dirName);
Directory.Delete(dirName);
}
} catch (ArgumentException) {
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (NotSupportedException) {
}
}
}
}
internal string PythonScraperPath {
get {
var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var file = Path.Combine(dir, "PythonScraper.py");
return file;
}
}
internal string ExtensionScraperPath {
get {
var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var file = Path.Combine(dir, "ExtensionScraper.py");
return file;
}
}
private Dictionary<string, int> GetCallDepthOverrides() {
var res = new Dictionary<string, int>();
var values = ConfigurationManager.AppSettings.Get("NoCallSiteAnalysis");
if (!string.IsNullOrEmpty(values)) {
TraceInformation("NoCallSiteAnalysis = {0}", values);
foreach (var value in values.Split(',', ';').Where(n => !string.IsNullOrWhiteSpace(n))) {
res[value] = 0;
}
}
var r = new Regex(@"^(?<module>[\w\.]+)\.CallDepth", RegexOptions.IgnoreCase);
Match m;
foreach (var key in ConfigurationManager.AppSettings.AllKeys) {
if ((m = r.Match(key)).Success) {
int depth;
if (int.TryParse(ConfigurationManager.AppSettings[key], out depth)) {
res[m.Groups["module"].Value] = depth;
} else {
TraceWarning("Failed to parse \"{0}={1}\" from config file", key, ConfigurationManager.AppSettings[key]);
}
}
}
foreach (var keyValue in res.OrderBy(kv => kv.Key)) {
TraceInformation("{0}.CallDepth = {1}", keyValue.Key, keyValue.Value);
}
return res;
}
private IEnumerable<string> GetSkipModules() {
var res = new HashSet<string>();
var r = new Regex(@"^(?<module>[\w\.]+)\.Skip", RegexOptions.IgnoreCase);
Match m;
foreach (var key in ConfigurationManager.AppSettings.AllKeys) {
if ((m = r.Match(key)).Success) {
bool value;
if (bool.TryParse(ConfigurationManager.AppSettings[key], out value) && value) {
TraceInformation("{0}.Skip = True", m.Groups["module"].Value);
yield return m.Groups["module"].Value;
}
}
}
}
private IEnumerable<string> IncludeModulesFromModulePath {
get {
if (_readModulePath == null) {
var values = ConfigurationManager.AppSettings.Get("IncludeModulesFromModulePath");
if (string.IsNullOrEmpty(values)) {
_readModulePath = Enumerable.Empty<string>();
} else {
TraceInformation("IncludeModulesFromModulePath = {0}", values);
_readModulePath = values.Split(',', ';').Where(n => !string.IsNullOrWhiteSpace(n)).ToArray();
}
}
return _readModulePath;
}
}
internal async Task Scrape() {
if (string.IsNullOrEmpty(_interpreter)) {
return;
}
if (_updater != null) {
_updater.UpdateStatus(_progressOffset, _progressTotal, "Scraping standard library");
}
if (_all) {
if (_dryRun) {
TraceDryRun("Scrape builtin modules");
} else {
// Scape builtin Python types
using (var output = ProcessOutput.RunHiddenAndCapture(_interpreter, PythonScraperPath, _outDir, _baseDb.First())) {
TraceInformation("Scraping builtin modules");
TraceInformation("Command: {0}", output.Arguments);
await output;
if (output.StandardOutputLines.Any()) {
TraceInformation("Output{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, output.StandardOutputLines));
}
if (output.StandardErrorLines.Any()) {
TraceWarning("Errors{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, output.StandardErrorLines));
}
if (output.ExitCode != 0) {
if (output.ExitCode.HasValue) {
TraceError("Failed to scrape builtin modules (Exit Code: {0})", output.ExitCode);
} else {
TraceError("Failed to scrape builtin modules");
}
throw new InvalidOperationException("Failed to scrape builtin modules");
} else {
TraceInformation("Scraped builtin modules");
}
}
}
}
foreach (var file in _scrapeFileGroups.SelectMany()) {
Debug.Assert(file.IsCompiled);
if (_updater != null) {
_updater.UpdateStatus(_progressOffset++, _progressTotal,
"Scraping " + CommonUtils.GetFileOrDirectoryName(file.LibraryPath));
}
var destFile = Path.ChangeExtension(GetOutputFile(file), null);
if (_dryRun) {
TraceDryRun("SCRAPE;{0};{1}.idb", file.SourceFile, CommonUtils.CreateFriendlyDirectoryPath(_outDir, destFile));
} else {
Directory.CreateDirectory(Path.GetDirectoryName(destFile));
// Provide a sys.path entry to ensure we can import the
// extension module. For cases where this is necessary, it
// probably means that the user can't import the module
// either, but they may have some other way of resolving it
// at runtime.
var scrapePath = Path.GetDirectoryName(file.SourceFile);
foreach (var part in file.ModuleName.Split('.').Reverse().Skip(1)) {
if (Path.GetFileName(scrapePath).Equals(part, StringComparison.Ordinal)) {
scrapePath = Path.GetDirectoryName(scrapePath);
} else {
break;
}
}
var prefixDir = Path.GetDirectoryName(_interpreter);
var pathVar = string.Format("{0};{1}", Environment.GetEnvironmentVariable("PATH"), prefixDir);
var arguments = new [] { ExtensionScraperPath, "scrape", file.ModuleName, scrapePath, destFile };
var env = new[] { new KeyValuePair<string, string>("PATH", pathVar) };
using (var output = ProcessOutput.Run(_interpreter, arguments, prefixDir, env, false, null)) {
TraceInformation("Scraping {0}", file.ModuleName);
TraceInformation("Command: {0}", output.Arguments);
TraceVerbose("environ['Path'] = {0}", pathVar);
await output;
if (output.StandardOutputLines.Any()) {
TraceInformation("Output{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, output.StandardOutputLines));
}
if (output.StandardErrorLines.Any()) {
TraceWarning("Errors{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, output.StandardErrorLines));
}
if (output.ExitCode != 0) {
if (output.ExitCode.HasValue) {
TraceError("Failed to scrape {1} (Exit code: {0})", output.ExitCode, file.ModuleName);
} else {
TraceError("Failed to scrape {0}", file.ModuleName);
}
} else {
TraceVerbose("Scraped {0}", file.ModuleName);
}
}
// Ensure that the output file exists, otherwise the DB will
// never appear to be up to date.
var expected = GetOutputFile(file);
if (!File.Exists(expected)) {
using (var writer = new FileStream(expected, FileMode.Create, FileAccess.ReadWrite)) {
new Pickler(writer).Dump(new Dictionary<string, object> {
{ "members", new Dictionary<string, object>() },
{ "doc", "Could not import compiled module" }
});
}
}
}
}
if (_scrapeFileGroups.Any()) {
TraceInformation("Scraped {0} files", _scrapeFileGroups.SelectMany().Count());
}
}
private static bool ContainsModule(HashSet<string> modules, string moduleName) {
foreach (var name in ModulePath.GetParents(moduleName)) {
if (modules.Contains(name)) {
return true;
}
}
return false;
}
internal Task Analyze() {
if (_updater != null) {
_updater.UpdateStatus(_progressOffset, _progressTotal, "Starting analysis");
}
if (!string.IsNullOrEmpty(_logDiagnostic) && AnalysisLog.Output == null) {
try {
AnalysisLog.Output = new StreamWriter(new FileStream(_logDiagnostic, FileMode.Create, FileAccess.Write, FileShare.Read), Encoding.UTF8);
AnalysisLog.AsCSV = _logDiagnostic.EndsWith(".csv", StringComparison.InvariantCultureIgnoreCase);
} catch (Exception ex) {
TraceWarning("Failed to open \"{0}\" for logging{1}{2}", _logDiagnostic, Environment.NewLine, ex.ToString());
}
}
var callDepthOverrides = GetCallDepthOverrides();
var skipModules = new HashSet<string>(GetSkipModules(), StringComparer.Ordinal);
foreach (var files in _analyzeFileGroups) {
if (_cancel.IsCancellationRequested) {
break;
}
if (files.Count == 0) {
continue;
}
var outDir = GetOutputDir(files[0]);
if (_dryRun) {
foreach (var file in files) {
if (ContainsModule(skipModules, file.ModuleName)) {
continue;
}
Debug.Assert(!file.IsCompiled);
var idbFile = CommonUtils.CreateFriendlyDirectoryPath(
_outDir,
Path.Combine(outDir, file.ModuleName)
);
TraceDryRun("ANALYZE;{0};{1}.idb", file.SourceFile, idbFile);
}
continue;
}
Directory.CreateDirectory(outDir);
TraceInformation("Start group \"{0}\" with {1} files", files[0].LibraryPath, files.Count);
AnalysisLog.StartFileGroup(files[0].LibraryPath, files.Count);
Console.WriteLine("Now analyzing: {0}", files[0].LibraryPath);
string currentLibrary;
if (_treatPathsAsStandardLibrary.Contains(files[0].LibraryPath)) {
currentLibrary = "standard library";
} else {
currentLibrary = CommonUtils.GetFileOrDirectoryName(files[0].LibraryPath);
}
using (var factory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(
_version,
null,
new[] { _outDir, outDir }.Concat(_baseDb.Skip(1)).Distinct(StringComparer.OrdinalIgnoreCase).ToArray()
))
using (var projectState = PythonAnalyzer.CreateAsync(factory).WaitAndUnwrapExceptions()) {
int? mostItemsInQueue = null;
if (_updater != null) {
projectState.SetQueueReporting(itemsInQueue => {
if (itemsInQueue > (mostItemsInQueue ?? 0)) {
mostItemsInQueue = itemsInQueue;
}
if (mostItemsInQueue > 0) {
var progress = (files.Count * (mostItemsInQueue - itemsInQueue)) / mostItemsInQueue;
_updater.UpdateStatus(_progressOffset + (progress ?? 0), _progressTotal,
"Analyzing " + currentLibrary);
} else {
_updater.UpdateStatus(_progressOffset + files.Count, _progressTotal,
"Analyzing " + currentLibrary);
}
}, 10);
}
try {
using (var key = Registry.CurrentUser.OpenSubKey(AnalysisLimitsKey)) {
projectState.Limits = AnalysisLimits.LoadFromStorage(key, defaultToStdLib: true);
}
} catch (SecurityException) {
projectState.Limits = AnalysisLimits.GetStandardLibraryLimits();
} catch (UnauthorizedAccessException) {
projectState.Limits = AnalysisLimits.GetStandardLibraryLimits();
} catch (IOException) {
projectState.Limits = AnalysisLimits.GetStandardLibraryLimits();
}
var items = files.Select(f => new AnalysisItem(f)).ToList();
foreach (var item in items) {
if (_cancel.IsCancellationRequested) {
break;
}
item.Entry = projectState.AddModule(item.ModuleName, item.SourceFile);
foreach (var name in ModulePath.GetParents(item.ModuleName, includeFullName: true)) {
int depth;
if (callDepthOverrides.TryGetValue(name, out depth)) {
TraceVerbose("Set CallDepthLimit to 0 for {0}", item.ModuleName);
item.Entry.Properties[AnalysisLimits.CallDepthKey] = depth;
break;
}
}
}
foreach (var item in items) {
if (_cancel.IsCancellationRequested) {
break;
}
if (ContainsModule(skipModules, item.ModuleName)) {
continue;
}
if (_updater != null) {
_updater.UpdateStatus(_progressOffset, _progressTotal,
string.Format("Parsing {0}", currentLibrary));
}
try {
var sourceUnit = new FileStream(item.SourceFile, FileMode.Open, FileAccess.Read, FileShare.Read);
var errors = new CollectingErrorSink();
var opts = new ParserOptions() { BindReferences = true, ErrorSink = errors };
TraceInformation("Parsing \"{0}\" (\"{1}\")", item.ModuleName, item.SourceFile);
item.Tree = Parser.CreateParser(sourceUnit, _version.ToLanguageVersion(), opts).ParseFile();
if (errors.Errors.Any() || errors.Warnings.Any()) {
TraceWarning("File \"{0}\" contained parse errors", item.SourceFile);
TraceInformation(string.Join(Environment.NewLine, errors.Errors.Concat(errors.Warnings)
.Select(er => string.Format("{0} {1}", er.Span, er.Message))));
}
} catch (Exception ex) {
TraceError("Error parsing \"{0}\" \"{1}\"{2}{3}", item.ModuleName, item.SourceFile, Environment.NewLine, ex.ToString());
}
}
TraceInformation("Parsing complete");
foreach (var item in items) {
if (_cancel.IsCancellationRequested) {
break;
}
if (item.Tree != null) {
item.Entry.UpdateTree(item.Tree, null);
}
}
foreach (var item in items) {
if (_cancel.IsCancellationRequested) {
break;
}
try {
if (item.Tree != null) {
TraceInformation("Analyzing \"{0}\"", item.ModuleName);
item.Entry.Analyze(_cancel, true);
TraceVerbose("Analyzed \"{0}\"", item.SourceFile);
}
} catch (Exception ex) {
TraceError("Error analyzing \"{0}\" \"{1}\"{2}{3}", item.ModuleName, item.SourceFile, Environment.NewLine, ex.ToString());
}
}
if (items.Count > 0 && !_cancel.IsCancellationRequested) {
TraceInformation("Starting analysis of {0} modules", items.Count);
items[0].Entry.AnalysisGroup.AnalyzeQueuedEntries(_cancel);
TraceInformation("Analysis complete");
}
if (_cancel.IsCancellationRequested) {
break;
}
TraceInformation("Saving group \"{0}\"", files[0].LibraryPath);
if (_updater != null) {
_progressOffset += files.Count;
_updater.UpdateStatus(_progressOffset, _progressTotal, "Saving " + currentLibrary);
}
Directory.CreateDirectory(outDir);
new SaveAnalysis().Save(projectState, outDir);
TraceInformation("End of group \"{0}\"", files[0].LibraryPath);
AnalysisLog.EndFileGroup();
AnalysisLog.Flush();
}
}
// Lets us have an awaitable function, even though it doesn't need
// to be async yet. This helps keep the interfaces consistent.
return Task.FromResult<object>(null);
}
internal Task Epilogue() {
if (_dryRun) {
TraceDryRun("WRITE;{0};{1}", Path.Combine(_outDir, "database.ver"), PythonTypeDatabase.CurrentVersion);
} else {
try {
File.WriteAllText(Path.Combine(_outDir, "database.ver"), PythonTypeDatabase.CurrentVersion.ToString());
} catch (ArgumentException) {
} catch (IOException) {
} catch (NotSupportedException) {
} catch (SecurityException) {
} catch (UnauthorizedAccessException) {
}
if (_pidMarkerFile != null) {
_pidMarkerFile.Close();
_pidMarkerFile = null;
}
}
// Lets us have an awaitable function, even though it doesn't need
// to be async yet. This helps keep the interfaces consistent.
return Task.FromResult<object>(null);
}
private string GetOutputDir(ModulePath file) {
if (_treatPathsAsStandardLibrary.Contains(file.LibraryPath)) {
return _outDir;
} else {
return Path.Combine(_outDir, Regex.Replace(
CommonUtils.TrimEndSeparator(CommonUtils.GetFileOrDirectoryName(file.LibraryPath)),
@"[.\\/\s]",
"_"
));
}
}
private string GetOutputFile(string builtinName) {
return CommonUtils.GetAbsoluteFilePath(_outDir, builtinName + ".idb");
}
private string GetOutputFile(ModulePath file) {
return CommonUtils.GetAbsoluteFilePath(GetOutputDir(file), file.ModuleName + ".idb");
}
class AnalysisItem {
readonly ModulePath _path;
public IPythonProjectEntry Entry { get; set; }
public PythonAst Tree { get; set; }
public AnalysisItem(ModulePath path) {
_path = path;
}
public string ModuleName { get { return _path.ModuleName; } }
public string SourceFile { get { return _path.SourceFile; } }
}
internal void TraceInformation(string message, params object[] args) {
if (_listener != null) {
_listener.WriteLine(DateTime.Now.ToString("s") + ": " + string.Format(message, args));
_listener.Flush();
}
}
internal void TraceWarning(string message, params object[] args) {
if (_listener != null) {
_listener.WriteLine(DateTime.Now.ToString("s") + ": [WARNING] " + string.Format(message, args));
_listener.Flush();
}
}
internal void TraceError(string message, params object[] args) {
if (_listener != null) {
_listener.WriteLine(DateTime.Now.ToString("s") + ": [ERROR] " + string.Format(message, args));
_listener.Flush();
}
}
[Conditional("DEBUG")]
internal void TraceVerbose(string message, params object[] args) {
if (_listener != null) {
_listener.WriteLine(DateTime.Now.ToString("s") + ": [VERBOSE] " + string.Format(message, args));
_listener.Flush();
}
}
internal void TraceDryRun(string message, params object[] args) {
Console.WriteLine(message, args);
TraceInformation(message, args);
}
}
}
| |
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
namespace SliceEm
{
/// <summary>
/// Summary description for PolygonNode.
/// </summary>
[Serializable]
public class PolygonNode
{
private ArrayList _Pnts;
private int _region = 0;
private int _mode = 0;
private int _mark = 0;
public int Mark
{
get { return _mark % _Pnts.Count; }
set { _mark = (value % _Pnts.Count); }
}
public PolygonNode()
{
_Pnts = new ArrayList();
}
public int Region
{
get { return _region; }
set { _region = value; }
}
public int Mode
{
get { return _mode; }
set { _mode = value; }
}
public PolygonNode(ArrayList myPoints)
{
_Pnts = myPoints;
}
public ArrayList Pnts
{
get { return _Pnts; }
}
public ArrayList GetSubset(ArrayList Many)
{
ArrayList subset = new ArrayList();
for(int i = 0; i < Pnts.Count; i++)
{
if(Many.Contains(Pnts[i]))
{
subset.Add(Pnts[i]);
}
}
return subset;
}
public ControlPoint GetCycleCenter(ArrayList Many)
{
for(int i = 0; i < Pnts.Count; i++)
{
if(!Many.Contains(Pnts[i]))
{
return Pnts[i] as ControlPoint;
}
}
return null;
}
public ControlPoint SplitEdges(ControlPoint A, ControlPoint B, ControlPoint C)
{
ControlPoint CPnew = null;
if(!_Pnts.Contains(A)) return null;
if(!_Pnts.Contains(B)) return null;
if(C==null)
{
CPnew = new ControlPoint();
CPnew.x = (A.x + B.x)/2;
CPnew.y = (A.y + B.y)/2;
}
else
{
CPnew = C;
}
if((_Pnts.IndexOf(A) - _Pnts.IndexOf(B)) == 1 || (_Pnts.IndexOf(B) - _Pnts.IndexOf(A)) == (Pnts.Count - 1))
{
_Pnts.Insert(_Pnts.IndexOf(A), CPnew);
}
else
{
_Pnts.Insert(_Pnts.IndexOf(B), CPnew);
}
return CPnew;
}
public bool Hit(float x, float y)
{
int cntX = 0;
int cntY = 0;
for(int i = 0; i < _Pnts.Count; i++)
{
ControlPoint A = _Pnts[i] as ControlPoint;
ControlPoint B = _Pnts[(i+1)%_Pnts.Count] as ControlPoint;
float dx = B.x - A.x;
float dy = B.y - A.y;
float t;
if(Math.Abs(dy) > 0.000001)
{
t = (y - A.y) / dy;
if( A.x + dx * t <= x && 0 <= t && t <= 1.0f)
{ cntY++; }
}
if(Math.Abs(dx) > 0.000001)
{
t = (x - A.x) / dx;
if( A.y + dy * t <= y && 0 <= t && t <= 1.0f)
{ cntX++; }
}
}
return (cntY%2==1 && cntX%2==1);
}
public PointF getCenter()
{
PointF PF = new PointF();
for(int i = 0; i < Pnts.Count; i++)
{
ControlPoint A = Pnts[i] as ControlPoint;
PF.X += A.x + A.dx;
PF.Y += A.y + A.dy;
}
PF.X/= Pnts.Count;
PF.Y/= Pnts.Count;
return PF;
}
public PolygonNode Union(PolygonNode PN)
{
ArrayList Asub = this.GetSubset(PN.Pnts);
if(Asub.Count == 0) return null;
int hd_a = Pnts.Count + 1;
int hd_b = PN.Pnts.Count + 1;
bool chain = true;
/*
ControlPoint HDcalc = GetCycleCenter(Asub);
for(int i = 0; i < Pnts.Count; i++)
{
if(Asub.Contains(Pnts[(i + Pnts.IndexOf(HDcalc))%Pnts.Count]))
{
hd_a = i;
i = Pnts.Count + 1;
}
}
ControlPoint HDcalc = GetCycleCenter(Asub);
MessageBox.Show("" + hd_a + "/" + Pnts.Count + " frm" + Pnts.IndexOf(HDcalc));
return null;
*/
for(int i = 0; i < Asub.Count; i++)
{
ControlPoint A = Asub[i] as ControlPoint;
int k = Pnts.IndexOf(A);
if(k>=1 && ! Asub.Contains(Pnts[(k-1)%Pnts.Count]))
{
hd_a = k;
}
if(k==0 && ! Asub.Contains(Pnts[Pnts.Count - 1]))
{
hd_a = k;
}
}
for(int i = 0; i < Asub.Count; i++)
{
ControlPoint A = Asub[i] as ControlPoint;
int k = PN.Pnts.IndexOf(A);
if(k>=1 && ! Asub.Contains(PN.Pnts[(k-1)%PN.Pnts.Count]))
{
hd_b = k;
}
if(k==0 && ! Asub.Contains(PN.Pnts[PN.Pnts.Count - 1]))
{
hd_b = k;
}
}
//MessageBox.Show("heads are: " + hd_a + " / " + Pnts.Count + " , " + hd_b + " / " + PN.Pnts.Count);
for(int i = 0; i < Asub.Count; i++)
{
ControlPoint A = Pnts[(i+hd_a)%Pnts.Count] as ControlPoint;
ControlPoint B = PN.Pnts[(i+hd_b)%PN.Pnts.Count] as ControlPoint;
if(Asub.Contains(A) && Asub.Contains(B))
{
}
else
{
chain = false;
}
}
if(chain)
{
ArrayList AL = new ArrayList();
for(int i = 0; i <= Pnts.Count - Asub.Count; i++)
{
int v = (hd_a + Asub.Count + i)%Pnts.Count;
AL.Add(Pnts[v]);
}
for(int i = 0; i <= PN.Pnts.Count - Asub.Count; i++)
{
int v = (hd_b + Asub.Count + i)%PN.Pnts.Count;
AL.Add(PN.Pnts[v]);
}
PolygonNode newPN = new PolygonNode(AL);
newPN.Region = this.Region;
newPN.Mark = this.Mark;
return newPN;
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using Moq;
using NUnit.Framework;
using SqlCE4Umbraco;
using umbraco;
using umbraco.businesslogic;
using umbraco.cms.businesslogic;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Profiling;
using Umbraco.Core.PropertyEditors;
using umbraco.DataLayer;
using umbraco.editorControls;
using umbraco.MacroEngines;
using umbraco.uicontrols;
using Umbraco.Web;
using Umbraco.Web.PropertyEditors;
namespace Umbraco.Tests.Plugins
{
[TestFixture]
public class PluginManagerTests
{
private PluginManager _manager;
[SetUp]
public void Initialize()
{
//this ensures its reset
_manager = new PluginManager(new ActivatorServiceProvider(), new NullCacheProvider(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
//for testing, we'll specify which assemblies are scanned for the PluginTypeResolver
//TODO: Should probably update this so it only searches this assembly and add custom types to be found
_manager.AssembliesToScan = new[]
{
this.GetType().Assembly,
typeof(ApplicationStartupHandler).Assembly,
typeof(SqlCEHelper).Assembly,
typeof(CMSNode).Assembly,
typeof(System.Guid).Assembly,
typeof(NUnit.Framework.Assert).Assembly,
typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly,
typeof(System.Xml.NameTable).Assembly,
typeof(System.Configuration.GenericEnumConverter).Assembly,
typeof(System.Web.SiteMap).Assembly,
typeof(TabPage).Assembly,
typeof(System.Web.Mvc.ActionResult).Assembly,
typeof(TypeFinder).Assembly,
typeof(ISqlHelper).Assembly,
typeof(ICultureDictionary).Assembly,
typeof(UmbracoContext).Assembly,
typeof(BaseDataType).Assembly
};
}
[TearDown]
public void TearDown()
{
_manager = null;
}
private DirectoryInfo PrepareFolder()
{
var assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
var dir = Directory.CreateDirectory(Path.Combine(assDir.FullName, "PluginManager", Guid.NewGuid().ToString("N")));
foreach (var f in dir.GetFiles())
{
f.Delete();
}
return dir;
}
//[Test]
//public void Scan_Vs_Load_Benchmark()
//{
// var pluginManager = new PluginManager(false);
// var watch = new Stopwatch();
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var type2 = Type.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type3 = Type.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type4 = Type.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type5 = Type.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds);
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var type2 = BuildManager.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type3 = BuildManager.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type4 = BuildManager.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type5 = BuildManager.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds);
// watch.Reset();
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var refreshers = pluginManager.ResolveTypes<ICacheRefresher>(false);
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (2nd round): " + watch.ElapsedMilliseconds);
//}
////NOTE: This test shows that Type.GetType is 100% faster than Assembly.Load(..).GetType(...) so we'll use that :)
//[Test]
//public void Load_Type_Benchmark()
//{
// var watch = new Stopwatch();
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var type2 = Type.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type3 = Type.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type4 = Type.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// var type5 = Type.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null");
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds);
// watch.Reset();
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var type2 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null")
// .GetType("umbraco.macroCacheRefresh");
// var type3 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null")
// .GetType("umbraco.templateCacheRefresh");
// var type4 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null")
// .GetType("umbraco.presentation.cache.MediaLibraryRefreshers");
// var type5 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null")
// .GetType("umbraco.presentation.cache.pageRefresher");
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (2nd round): " + watch.ElapsedMilliseconds);
// watch.Reset();
// watch.Start();
// for (var i = 0; i < 1000; i++)
// {
// var type2 = BuildManager.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type3 = BuildManager.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type4 = BuildManager.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// var type5 = BuildManager.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true);
// }
// watch.Stop();
// Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds);
//}
[Test]
public void Detect_Legacy_Plugin_File_List()
{
var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/PluginCache");
var filePath= Path.Combine(tempFolder, string.Format("umbraco-plugins.{0}.list", NetworkHelper.FileSafeMachineName));
File.WriteAllText(filePath, @"<?xml version=""1.0"" encoding=""utf-8""?>
<plugins>
<baseType type=""umbraco.interfaces.ICacheRefresher"">
<add type=""umbraco.macroCacheRefresh, umbraco, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</baseType>
</plugins>");
Assert.IsTrue(_manager.DetectLegacyPluginListFile());
File.Delete(filePath);
//now create a valid one
File.WriteAllText(filePath, @"<?xml version=""1.0"" encoding=""utf-8""?>
<plugins>
<baseType type=""umbraco.interfaces.ICacheRefresher"" resolutionType=""FindAllTypes"">
<add type=""umbraco.macroCacheRefresh, umbraco, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</baseType>
</plugins>");
Assert.IsFalse(_manager.DetectLegacyPluginListFile());
}
[Test]
public void Create_Cached_Plugin_File()
{
var types = new[] { typeof(PluginManager), typeof(PluginManagerTests), typeof(UmbracoContext) };
//yes this is silly, none of these types inherit from string, but this is just to test the xml file format
_manager.UpdateCachedPluginsFile<string>(types, PluginManager.TypeResolutionKind.FindAllTypes);
var plugins = _manager.TryGetCachedPluginsFromFile<string>(PluginManager.TypeResolutionKind.FindAllTypes);
var diffType = _manager.TryGetCachedPluginsFromFile<string>(PluginManager.TypeResolutionKind.FindAttributedTypes);
Assert.IsTrue(plugins.Success);
//this will be false since there is no cache of that type resolution kind
Assert.IsFalse(diffType.Success);
Assert.AreEqual(3, plugins.Result.Count());
var shouldContain = types.Select(x => x.AssemblyQualifiedName);
//ensure they are all found
Assert.IsTrue(plugins.Result.ContainsAll(shouldContain));
}
[Test]
public void PluginHash_From_String()
{
var s = "hello my name is someone".GetHashCode().ToString("x", CultureInfo.InvariantCulture);
var output = PluginManager.ConvertPluginsHashFromHex(s);
Assert.AreNotEqual(0, output);
}
[Test]
public void Get_Plugins_Hash()
{
//Arrange
var dir = PrepareFolder();
var d1 = dir.CreateSubdirectory("1");
var d2 = dir.CreateSubdirectory("2");
var d3 = dir.CreateSubdirectory("3");
var d4 = dir.CreateSubdirectory("4");
var f1 = new FileInfo(Path.Combine(d1.FullName, "test1.dll"));
var f2 = new FileInfo(Path.Combine(d1.FullName, "test2.dll"));
var f3 = new FileInfo(Path.Combine(d2.FullName, "test1.dll"));
var f4 = new FileInfo(Path.Combine(d2.FullName, "test2.dll"));
var f5 = new FileInfo(Path.Combine(d3.FullName, "test1.dll"));
var f6 = new FileInfo(Path.Combine(d3.FullName, "test2.dll"));
var f7 = new FileInfo(Path.Combine(d4.FullName, "test1.dll"));
f1.CreateText().Close();
f2.CreateText().Close();
f3.CreateText().Close();
f4.CreateText().Close();
f5.CreateText().Close();
f6.CreateText().Close();
f7.CreateText().Close();
var list1 = new[] { f1, f2, f3, f4, f5, f6 };
var list2 = new[] { f1, f3, f5 };
var list3 = new[] { f1, f3, f5, f7 };
//Act
var hash1 = PluginManager.GetFileHash(list1, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
var hash2 = PluginManager.GetFileHash(list2, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
var hash3 = PluginManager.GetFileHash(list3, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
//Assert
Assert.AreNotEqual(hash1, hash2);
Assert.AreNotEqual(hash1, hash3);
Assert.AreNotEqual(hash2, hash3);
Assert.AreEqual(hash1, PluginManager.GetFileHash(list1, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())));
}
[Test]
public void Ensure_Only_One_Type_List_Created()
{
var foundTypes1 = _manager.ResolveFindMeTypes();
var foundTypes2 = _manager.ResolveFindMeTypes();
Assert.AreEqual(1,
_manager.GetTypeLists()
.Count(x => x.IsTypeList<IFindMe>(PluginManager.TypeResolutionKind.FindAllTypes)));
}
[Test]
public void Resolves_Assigned_Mappers()
{
var foundTypes1 = _manager.ResolveAssignedMapperTypes();
Assert.AreEqual(28, foundTypes1.Count());
}
[Test]
public void Resolves_Types()
{
var foundTypes1 = _manager.ResolveFindMeTypes();
Assert.AreEqual(2, foundTypes1.Count());
}
[Test]
public void Resolves_Attributed_Trees()
{
var trees = _manager.ResolveAttributedTrees();
Assert.AreEqual(17, trees.Count());
}
[Test]
public void Resolves_Actions()
{
var actions = _manager.ResolveActions();
Assert.AreEqual(37, actions.Count());
}
[Test]
public void Resolves_Trees()
{
var trees = _manager.ResolveTrees();
Assert.AreEqual(39, trees.Count());
}
[Test]
public void Resolves_Applications()
{
var apps = _manager.ResolveApplications();
Assert.AreEqual(7, apps.Count());
}
[Test]
public void Resolves_DataTypes()
{
var types = _manager.ResolveDataTypes();
Assert.AreEqual(35, types.Count());
}
[Test]
public void Resolves_RazorDataTypeModels()
{
var types = _manager.ResolveRazorDataTypeModels();
Assert.AreEqual(2, types.Count());
}
[Test]
public void Resolves_RestExtensions()
{
var types = _manager.ResolveRestExtensions();
Assert.AreEqual(3, types.Count());
}
[Test]
public void Resolves_XsltExtensions()
{
var types = _manager.ResolveXsltExtensions();
Assert.AreEqual(3, types.Count());
}
/// <summary>
/// This demonstrates this issue: http://issues.umbraco.org/issue/U4-3505 - the TypeList was returning a list of assignable types
/// not explicit types which is sort of ideal but is confusing so we'll do it the less confusing way.
/// </summary>
[Test]
public void TypeList_Resolves_Explicit_Types()
{
var types = new HashSet<PluginManager.TypeList>();
var propEditors = new PluginManager.TypeList<PropertyEditor>(PluginManager.TypeResolutionKind.FindAllTypes);
propEditors.AddType(typeof(LabelPropertyEditor));
types.Add(propEditors);
var found = types.SingleOrDefault(x => x.IsTypeList<PropertyEditor>(PluginManager.TypeResolutionKind.FindAllTypes));
Assert.IsNotNull(found);
//This should not find a type list of this type
var shouldNotFind = types.SingleOrDefault(x => x.IsTypeList<IParameterEditor>(PluginManager.TypeResolutionKind.FindAllTypes));
Assert.IsNull(shouldNotFind);
}
[XsltExtension("Blah.Blah")]
public class MyXsltExtension
{
}
[Umbraco.Web.BaseRest.RestExtension("Blah")]
public class MyRestExtesion
{
}
public interface IFindMe
{
}
public class FindMe1 : IFindMe
{
}
public class FindMe2 : IFindMe
{
}
}
}
| |
// 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.Diagnostics;
using System.Xml.XPath;
namespace MS.Internal.Xml.Cache
{
/// <summary>
/// Library of XPathNode helper routines.
/// </summary>
internal abstract class XPathNodeHelper
{
/// <summary>
/// Return chain of namespace nodes. If specified node has no local namespaces, then 0 will be
/// returned. Otherwise, the first node in the chain is guaranteed to be a local namespace (its
/// parent is this node). Subsequent nodes may not have the same node as parent, so the caller will
/// need to test the parent in order to terminate a search that processes only local namespaces.
/// </summary>
public static int GetLocalNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp)
{
if (pageElem[idxElem].HasNamespaceDecls)
{
// Only elements have namespace nodes
Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element);
return pageElem[idxElem].Document.LookupNamespaces(pageElem, idxElem, out pageNmsp);
}
pageNmsp = null;
return 0;
}
/// <summary>
/// Return chain of in-scope namespace nodes for nodes of type Element. Nodes in the chain might not
/// have this element as their parent. Since the xmlns:xml namespace node is always in scope, this
/// method will never return 0 if the specified node is an element.
/// </summary>
public static int GetInScopeNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp)
{
XPathDocument doc;
// Only elements have namespace nodes
if (pageElem[idxElem].NodeType == XPathNodeType.Element)
{
doc = pageElem[idxElem].Document;
// Walk ancestors, looking for an ancestor that has at least one namespace declaration
while (!pageElem[idxElem].HasNamespaceDecls)
{
idxElem = pageElem[idxElem].GetParent(out pageElem);
if (idxElem == 0)
{
// There are no namespace nodes declared on ancestors, so return xmlns:xml node
return doc.GetXmlNamespaceNode(out pageNmsp);
}
}
// Return chain of in-scope namespace nodes
return doc.LookupNamespaces(pageElem, idxElem, out pageNmsp);
}
pageNmsp = null;
return 0;
}
/// <summary>
/// Return the first attribute of the specified node. If no attribute exist, do not
/// set pageNode or idxNode and return false.
/// </summary>
public static bool GetFirstAttribute(ref XPathNode[] pageNode, ref int idxNode)
{
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (pageNode[idxNode].HasAttribute)
{
GetChild(ref pageNode, ref idxNode);
Debug.Assert(pageNode[idxNode].NodeType == XPathNodeType.Attribute);
return true;
}
return false;
}
/// <summary>
/// Return the next attribute sibling of the specified node. If the node is not itself an
/// attribute, or if there are no siblings, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetNextAttribute(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page;
int idx;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
idx = pageNode[idxNode].GetSibling(out page);
if (idx != 0 && page[idx].NodeType == XPathNodeType.Attribute)
{
pageNode = page;
idxNode = idx;
return true;
}
return false;
}
/// <summary>
/// Return the first content-typed child of the specified node. If the node has no children, or
/// if the node is not content-typed, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentChild(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (page[idx].HasContentChild)
{
GetChild(ref page, ref idx);
// Skip past attribute children
while (page[idx].NodeType == XPathNodeType.Attribute)
{
idx = page[idx].GetSibling(out page);
Debug.Assert(idx != 0);
}
pageNode = page;
idxNode = idx;
return true;
}
return false;
}
/// <summary>
/// Return the next content-typed sibling of the specified node. If the node has no siblings, or
/// if the node is not content-typed, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentSibling(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (!page[idx].IsAttrNmsp)
{
idx = page[idx].GetSibling(out page);
if (idx != 0)
{
pageNode = page;
idxNode = idx;
return true;
}
}
return false;
}
/// <summary>
/// Return the parent of the specified node. If the node has no parent, do not set pageNode
/// or idxNode and return false.
/// </summary>
public static bool GetParent(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
idx = page[idx].GetParent(out page);
if (idx != 0)
{
pageNode = page;
idxNode = idx;
return true;
}
return false;
}
/// <summary>
/// Return a location integer that can be easily compared with other locations from the same document
/// in order to determine the relative document order of two nodes.
/// </summary>
public static int GetLocation(XPathNode[] pageNode, int idxNode)
{
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
Debug.Assert(idxNode <= ushort.MaxValue);
Debug.Assert(pageNode[0].PageInfo.PageNumber <= short.MaxValue);
return (pageNode[0].PageInfo.PageNumber << 16) | idxNode;
}
/// <summary>
/// Return the first element child of the specified node that has the specified name. If no such child exists,
/// then do not set pageNode or idxNode and return false. Assume that the localName has been atomized with respect
/// to this document's name table, but not the namespaceName.
/// </summary>
public static bool GetElementChild(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Only check children if at least one element child exists
if (page[idx].HasElementChild)
{
GetChild(ref page, ref idx);
Debug.Assert(idx != 0);
// Find element with specified localName and namespaceName
do
{
if (page[idx].ElementMatch(localName, namespaceName))
{
pageNode = page;
idxNode = idx;
return true;
}
idx = page[idx].GetSibling(out page);
}
while (idx != 0);
}
return false;
}
/// <summary>
/// Return a following sibling element of the specified node that has the specified name. If no such
/// sibling exists, or if the node is not content-typed, then do not set pageNode or idxNode and
/// return false. Assume that the localName has been atomized with respect to this document's name table,
/// but not the namespaceName.
/// </summary>
public static bool GetElementSibling(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Elements should not be returned as "siblings" of attributes (namespaces don't link to elements, so don't need to check them)
if (page[idx].NodeType != XPathNodeType.Attribute)
{
while (true)
{
idx = page[idx].GetSibling(out page);
if (idx == 0)
break;
if (page[idx].ElementMatch(localName, namespaceName))
{
pageNode = page;
idxNode = idx;
return true;
}
}
}
return false;
}
/// <summary>
/// Return the first child of the specified node that has the specified type (must be a content type). If no such
/// child exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentChild(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ)
{
XPathNode[] page = pageNode;
int idx = idxNode;
int mask;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Only check children if at least one content-typed child exists
if (page[idx].HasContentChild)
{
mask = XPathNavigator.GetContentKindMask(typ);
GetChild(ref page, ref idx);
do
{
if (((1 << (int)page[idx].NodeType) & mask) != 0)
{
// Never return attributes, as Attribute is not a content type
if (typ == XPathNodeType.Attribute)
return false;
pageNode = page;
idxNode = idx;
return true;
}
idx = page[idx].GetSibling(out page);
}
while (idx != 0);
}
return false;
}
/// <summary>
/// Return a following sibling of the specified node that has the specified type. If no such
/// sibling exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentSibling(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ)
{
XPathNode[] page = pageNode;
int idx = idxNode;
int mask = XPathNavigator.GetContentKindMask(typ);
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (page[idx].NodeType != XPathNodeType.Attribute)
{
while (true)
{
idx = page[idx].GetSibling(out page);
if (idx == 0)
break;
if (((1 << (int)page[idx].NodeType) & mask) != 0)
{
Debug.Assert(typ != XPathNodeType.Attribute && typ != XPathNodeType.Namespace);
pageNode = page;
idxNode = idx;
return true;
}
}
}
return false;
}
/// <summary>
/// Return the first preceding sibling of the specified node. If no such sibling exists, then do not set
/// pageNode or idxNode and return false.
/// </summary>
public static bool GetPreviousContentSibling(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] pageParent = pageNode, pagePrec, pageAnc;
int idxParent = idxNode, idxPrec, idxAnc;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
Debug.Assert(pageNode[idxNode].NodeType != XPathNodeType.Attribute);
// Since nodes are laid out in document order on pages, the algorithm is:
// 1. Get parent of current node
// 2. If no parent, then there is no previous sibling, so return false
// 3. Get node that immediately precedes the current node in document order
// 4. If preceding node is parent, then there is no previous sibling, so return false
// 5. Walk ancestors of preceding node, until parent of current node is found
idxParent = pageParent[idxParent].GetParent(out pageParent);
if (idxParent != 0)
{
idxPrec = idxNode - 1;
if (idxPrec == 0)
{
// Need to get previous page
pagePrec = pageNode[0].PageInfo.PreviousPage;
idxPrec = pagePrec.Length - 1;
}
else
{
// Previous node is on the same page
pagePrec = pageNode;
}
// If parent node is previous node, then no previous sibling
if (idxParent == idxPrec && pageParent == pagePrec)
return false;
// Find child of parent node by walking ancestor chain
pageAnc = pagePrec;
idxAnc = idxPrec;
do
{
pagePrec = pageAnc;
idxPrec = idxAnc;
idxAnc = pageAnc[idxAnc].GetParent(out pageAnc);
Debug.Assert(idxAnc != 0 && pageAnc != null);
}
while (idxAnc != idxParent || pageAnc != pageParent);
// We found the previous sibling, but if it's an attribute node, then return false
if (pagePrec[idxPrec].NodeType != XPathNodeType.Attribute)
{
pageNode = pagePrec;
idxNode = idxPrec;
return true;
}
}
return false;
}
/// <summary>
/// Return the attribute of the specified node that has the specified name. If no such attribute exists,
/// then do not set pageNode or idxNode and return false. Assume that the localName has been atomized with respect
/// to this document's name table, but not the namespaceName.
/// </summary>
public static bool GetAttribute(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Find attribute with specified localName and namespaceName
if (page[idx].HasAttribute)
{
GetChild(ref page, ref idx);
do
{
if (page[idx].NameMatch(localName, namespaceName))
{
pageNode = page;
idxNode = idx;
return true;
}
idx = page[idx].GetSibling(out page);
}
while (idx != 0 && page[idx].NodeType == XPathNodeType.Attribute);
}
return false;
}
/// <summary>
/// Get the next element node that:
/// 1. Follows the current node in document order (includes descendants, unlike XPath following axis)
/// 2. Precedes the ending node in document order (if pageEnd is null, then all following nodes in the document are considered)
/// 3. Has the specified QName
/// If no such element exists, then do not set pageCurrent or idxCurrent and return false.
/// Assume that the localName has been atomized with respect to this document's name table, but not the namespaceName.
/// </summary>
public static bool GetElementFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd, string localName, string namespaceName)
{
XPathNode[] page = pageCurrent;
int idx = idxCurrent;
Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)");
// If current node is an element having a matching name,
if (page[idx].NodeType == XPathNodeType.Element && (object)page[idx].LocalName == (object)localName)
{
// Then follow similar element name pointers
int idxPageEnd = 0;
int idxPageCurrent;
if (pageEnd != null)
{
idxPageEnd = pageEnd[0].PageInfo.PageNumber;
idxPageCurrent = page[0].PageInfo.PageNumber;
// If ending node is <= starting node in document order, then scan to end of document
if (idxPageCurrent > idxPageEnd || (idxPageCurrent == idxPageEnd && idx >= idxEnd))
pageEnd = null;
}
while (true)
{
idx = page[idx].GetSimilarElement(out page);
if (idx == 0)
break;
// Only scan to ending node
if (pageEnd != null)
{
idxPageCurrent = page[0].PageInfo.PageNumber;
if (idxPageCurrent > idxPageEnd)
break;
if (idxPageCurrent == idxPageEnd && idx >= idxEnd)
break;
}
if ((object)page[idx].LocalName == (object)localName && page[idx].NamespaceUri == namespaceName)
goto FoundNode;
}
return false;
}
// Since nodes are laid out in document order on pages, scan them sequentially
// rather than following links.
idx++;
do
{
if ((object)page == (object)pageEnd && idx <= idxEnd)
{
// Only scan to termination point
while (idx != idxEnd)
{
if (page[idx].ElementMatch(localName, namespaceName))
goto FoundNode;
idx++;
}
break;
}
else
{
// Scan all nodes in the page
while (idx < page[0].PageInfo.NodeCount)
{
if (page[idx].ElementMatch(localName, namespaceName))
goto FoundNode;
idx++;
}
}
page = page[0].PageInfo.NextPage;
idx = 1;
}
while (page != null);
return false;
FoundNode:
// Found match
pageCurrent = page;
idxCurrent = idx;
return true;
}
/// <summary>
/// Get the next node that:
/// 1. Follows the current node in document order (includes descendants, unlike XPath following axis)
/// 2. Precedes the ending node in document order (if pageEnd is null, then all following nodes in the document are considered)
/// 3. Has the specified XPathNodeType (but Attributes and Namespaces never match)
/// If no such node exists, then do not set pageCurrent or idxCurrent and return false.
/// </summary>
public static bool GetContentFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd, XPathNodeType typ)
{
XPathNode[] page = pageCurrent;
int idx = idxCurrent;
int mask = XPathNavigator.GetContentKindMask(typ);
Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)");
Debug.Assert(typ != XPathNodeType.Text, "Text should be handled by GetTextFollowing in order to take into account collapsed text.");
Debug.Assert(page[idx].NodeType != XPathNodeType.Attribute, "Current node should never be an attribute or namespace--caller should handle this case.");
// Since nodes are laid out in document order on pages, scan them sequentially
// rather than following sibling/child/parent links.
idx++;
do
{
if ((object)page == (object)pageEnd && idx <= idxEnd)
{
// Only scan to termination point
while (idx != idxEnd)
{
if (((1 << (int)page[idx].NodeType) & mask) != 0)
goto FoundNode;
idx++;
}
break;
}
else
{
// Scan all nodes in the page
while (idx < page[0].PageInfo.NodeCount)
{
if (((1 << (int)page[idx].NodeType) & mask) != 0)
goto FoundNode;
idx++;
}
}
page = page[0].PageInfo.NextPage;
idx = 1;
}
while (page != null);
return false;
FoundNode:
Debug.Assert(!page[idx].IsAttrNmsp, "GetContentFollowing should never return attributes or namespaces.");
// Found match
pageCurrent = page;
idxCurrent = idx;
return true;
}
/// <summary>
/// Scan all nodes that follow the current node in document order, but precede the ending node in document order.
/// Return two types of nodes with non-null text:
/// 1. Element parents of collapsed text nodes (since it is the element parent that has the collapsed text)
/// 2. Non-collapsed text nodes
/// If no such node exists, then do not set pageCurrent or idxCurrent and return false.
/// </summary>
public static bool GetTextFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd)
{
XPathNode[] page = pageCurrent;
int idx = idxCurrent;
Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)");
Debug.Assert(!page[idx].IsAttrNmsp, "Current node should never be an attribute or namespace--caller should handle this case.");
// Since nodes are laid out in document order on pages, scan them sequentially
// rather than following sibling/child/parent links.
idx++;
do
{
if ((object)page == (object)pageEnd && idx <= idxEnd)
{
// Only scan to termination point
while (idx != idxEnd)
{
if (page[idx].IsText || (page[idx].NodeType == XPathNodeType.Element && page[idx].HasCollapsedText))
goto FoundNode;
idx++;
}
break;
}
else
{
// Scan all nodes in the page
while (idx < page[0].PageInfo.NodeCount)
{
if (page[idx].IsText || (page[idx].NodeType == XPathNodeType.Element && page[idx].HasCollapsedText))
goto FoundNode;
idx++;
}
}
page = page[0].PageInfo.NextPage;
idx = 1;
}
while (page != null);
return false;
FoundNode:
// Found match
pageCurrent = page;
idxCurrent = idx;
return true;
}
/// <summary>
/// Get the next non-virtual (not collapsed text, not namespaces) node that follows the specified node in document order,
/// but is not a descendant. If no such node exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetNonDescendant(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
// Get page, idx at which to end sequential scan of nodes
do
{
// If the current node has a sibling,
if (page[idx].HasSibling)
{
// Then that is the first non-descendant
pageNode = page;
idxNode = page[idx].GetSibling(out pageNode);
return true;
}
// Otherwise, try finding a sibling at the parent level
idx = page[idx].GetParent(out page);
}
while (idx != 0);
return false;
}
/// <summary>
/// Return the page and index of the first child (attribute or content) of the specified node.
/// </summary>
private static void GetChild(ref XPathNode[] pageNode, ref int idxNode)
{
Debug.Assert(pageNode[idxNode].HasAttribute || pageNode[idxNode].HasContentChild, "Caller must check HasAttribute/HasContentChild on parent before calling GetChild.");
Debug.Assert(pageNode[idxNode].HasAttribute || !pageNode[idxNode].HasCollapsedText, "Text child is virtualized and therefore is not present in the physical node page.");
if (++idxNode >= pageNode.Length)
{
// Child is first node on next page
pageNode = pageNode[0].PageInfo.NextPage;
idxNode = 1;
}
// Else child is next node on this page
}
}
}
| |
//
// CanvasHost.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright 2009 Aaron Bockover
//
// 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 Gtk;
using Gdk;
using Hyena.Gui.Theming;
namespace Hyena.Gui.Canvas
{
public class FpsCalculator
{
private DateTime last_update;
private TimeSpan update_interval;
private int frame_count;
private double fps;
public FpsCalculator ()
{
update_interval = TimeSpan.FromSeconds (0.5);
}
public bool Update ()
{
bool updated = false;
DateTime current_time = DateTime.Now;
frame_count++;
if (current_time - last_update >= update_interval) {
fps = (double)frame_count / (current_time - last_update).TotalSeconds;
frame_count = 0;
updated = true;
last_update = current_time;
}
return updated;
}
public double FramesPerSecond {
get { return fps; }
}
}
public class CanvasHost : Widget
{
private Gdk.Window event_window;
private CanvasItem canvas_child;
private Theme theme;
private CanvasManager manager;
private bool debug = false;
private FpsCalculator fps = new FpsCalculator ();
public CanvasHost ()
{
WidgetFlags |= WidgetFlags.NoWindow;
manager = new CanvasManager (this);
}
protected CanvasHost (IntPtr native) : base (native)
{
}
protected override void OnRealized ()
{
base.OnRealized ();
WindowAttr attributes = new WindowAttr ();
attributes.WindowType = Gdk.WindowType.Child;
attributes.X = Allocation.X;
attributes.Y = Allocation.Y;
attributes.Width = Allocation.Width;
attributes.Height = Allocation.Height;
attributes.Wclass = WindowClass.InputOnly;
attributes.EventMask = (int)(
EventMask.PointerMotionMask |
EventMask.ButtonPressMask |
EventMask.ButtonReleaseMask |
EventMask.EnterNotifyMask |
EventMask.LeaveNotifyMask |
EventMask.ExposureMask);
WindowAttributesType attributes_mask =
WindowAttributesType.X | WindowAttributesType.Y | WindowAttributesType.Wmclass;
event_window = new Gdk.Window (GdkWindow, attributes, attributes_mask);
event_window.UserData = Handle;
AllocateChild ();
QueueResize ();
}
protected override void OnUnrealized ()
{
WidgetFlags ^= WidgetFlags.Realized;
event_window.UserData = IntPtr.Zero;
Hyena.Gui.GtkWorkarounds.WindowDestroy (event_window);
event_window = null;
base.OnUnrealized ();
}
protected override void OnMapped ()
{
event_window.Show ();
base.OnMapped ();
}
protected override void OnUnmapped ()
{
event_window.Hide ();
base.OnUnmapped ();
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
if (IsRealized) {
event_window.MoveResize (allocation);
AllocateChild ();
}
}
protected override void OnSizeRequested (ref Gtk.Requisition requisition)
{
if (canvas_child != null) {
Size size = canvas_child.Measure (Size.Empty);
if (size.Width > 0) {
requisition.Width = (int)Math.Ceiling (size.Width);
}
if (size.Height > 0) {
requisition.Height = (int)Math.Ceiling (size.Height);
}
}
}
private Random rand;
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
if (canvas_child == null || !canvas_child.Visible || !Visible || !IsMapped) {
return true;
}
Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window);
foreach (Gdk.Rectangle damage in evnt.Region.GetRectangles ()) {
cr.Rectangle (damage.X, damage.Y, damage.Width, damage.Height);
cr.Clip ();
cr.Translate (Allocation.X, Allocation.Y);
canvas_child.Render (cr);
cr.Translate (-Allocation.X, -Allocation.Y);
if (Debug) {
cr.LineWidth = 1.0;
cr.Color = CairoExtensions.RgbToColor (
(uint)(rand = rand ?? new Random ()).Next (0, 0xffffff));
cr.Rectangle (damage.X + 0.5, damage.Y + 0.5, damage.Width - 1, damage.Height - 1);
cr.Stroke ();
}
cr.ResetClip ();
}
CairoExtensions.DisposeContext (cr);
if (fps.Update ()) {
// Console.WriteLine ("FPS: {0}", fps.FramesPerSecond);
}
return true;
}
private void AllocateChild ()
{
if (canvas_child != null) {
canvas_child.Allocation = new Rect (0, 0, Allocation.Width, Allocation.Height);
canvas_child.Measure (new Size (Allocation.Width, Allocation.Height));
canvas_child.Arrange ();
}
}
public void QueueRender (CanvasItem item, Rect rect)
{
double x = Allocation.X;
double y = Allocation.Y;
double w, h;
if (rect.IsEmpty) {
w = item.Allocation.Width;
h = item.Allocation.Height;
} else {
x += rect.X;
y += rect.Y;
w = rect.Width;
h = rect.Height;
}
while (item != null) {
x += item.ContentAllocation.X;
y += item.ContentAllocation.Y;
item = item.Parent;
}
QueueDrawArea (
(int)Math.Floor (x),
(int)Math.Floor (y),
(int)Math.Ceiling (w),
(int)Math.Ceiling (h)
);
}
private bool changing_style = false;
protected override void OnStyleSet (Style old_style)
{
if (changing_style) {
return;
}
changing_style = true;
theme = new GtkTheme (this);
if (canvas_child != null) {
canvas_child.Theme = theme;
}
changing_style = false;
base.OnStyleSet (old_style);
}
protected override bool OnButtonPressEvent (Gdk.EventButton evnt)
{
if (canvas_child != null) {
canvas_child.ButtonPress (evnt.X, evnt.Y, evnt.Button);
}
return true;
}
protected override bool OnButtonReleaseEvent (Gdk.EventButton evnt)
{
if (canvas_child != null) {
canvas_child.ButtonRelease ();
}
return true;
}
protected override bool OnMotionNotifyEvent (EventMotion evnt)
{
if (canvas_child != null) {
canvas_child.PointerMotion (evnt.X, evnt.Y);
}
return true;
}
public void Add (CanvasItem child)
{
if (Child != null) {
throw new InvalidOperationException ("Child is already set, remove it first");
}
Child = child;
}
public void Remove (CanvasItem child)
{
if (Child != child) {
throw new InvalidOperationException ("child does not already belong to host");
}
Child = null;
}
private void OnCanvasChildLayoutUpdated (object o, EventArgs args)
{
QueueDraw ();
}
private void OnCanvasChildSizeChanged (object o, EventArgs args)
{
QueueResize ();
}
public CanvasItem Child {
get { return canvas_child; }
set {
if (canvas_child == value) {
return;
} else if (canvas_child != null) {
canvas_child.Theme = null;
canvas_child.Manager = null;
canvas_child.LayoutUpdated -= OnCanvasChildLayoutUpdated;
canvas_child.SizeChanged -= OnCanvasChildSizeChanged;
}
canvas_child = value;
if (canvas_child != null) {
canvas_child.Theme = theme;
canvas_child.Manager = manager;
canvas_child.LayoutUpdated += OnCanvasChildLayoutUpdated;
canvas_child.SizeChanged += OnCanvasChildSizeChanged;
}
AllocateChild ();
}
}
public bool Debug {
get { return debug; }
set { debug = value; }
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Collections.Specialized;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Glass.Mapper.Sc.RenderField;
using Glass.Mapper.Sc.Web.Ui;
using Sitecore.Shell.Applications.Dialogs.ItemLister;
namespace Glass.Mapper.Sc.Web.Mvc
{
/// <summary>
///
/// </summary>
/// <typeparam name="TModel"></typeparam>
public abstract class GlassView<TModel> : WebViewPage<TModel> where TModel : class
{
/// <summary>
///
/// </summary>
public IGlassHtml GlassHtml { get; private set; }
public ISitecoreContext SitecoreContext { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is in editing mode.
/// </summary>
/// <value><c>true</c> if this instance is in editing mode; otherwise, <c>false</c>.</value>
public bool IsInEditingMode
{
get { return Sc.GlassHtml.IsInEditingMode; }
}
/// <summary>
/// Inits the helpers.
/// </summary>
public override void InitHelpers()
{
base.InitHelpers();
SitecoreContext = Sc.SitecoreContext.GetFromHttpContext();
GlassHtml = new GlassHtml(SitecoreContext);
if (Model == null && this.ViewData.Model == null)
{
this.ViewData.Model = GetModel();
}
}
protected virtual TModel GetModel()
{
if (Sitecore.Mvc.Presentation.RenderingContext.Current == null ||
Sitecore.Mvc.Presentation.RenderingContext.Current.Rendering == null ||
Sitecore.Mvc.Presentation.RenderingContext.Current.Rendering.DataSource.IsNullOrEmpty())
{
return SitecoreContext.GetCurrentItem<TModel>();
}
else
{
return
SitecoreContext.GetItem<TModel>(
Sitecore.Mvc.Presentation.RenderingContext.Current.Rendering.DataSource);
}
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <param name="field">The field that should be made editable</param>
/// <param name="parameters"> </param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable<T>(T target, Expression<Func<T, object>> field, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(target, field, parameters));
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam>
/// <param name="target">The target object that contains the item to be edited</param>
/// <param name="field">The field that should be made editable</param>
/// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable<T>(T target, Expression<Func<T, object>> field,
Expression<Func<T, string>> standardOutput, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(target, field, standardOutput, parameters));
}
/// <summary>
/// Renders an image allowing simple page editor support
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model that contains the image field</param>
/// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param>
/// <param name="parameters">Image parameters, e.g. width, height</param>
/// <param name="isEditable">Indicates if the field should be editable</param>
/// <returns></returns>
public virtual HtmlString RenderImage<T>(T target, Expression<Func<T, object>> field,
object parameters = null,
bool isEditable = false)
{
return new HtmlString(GlassHtml.RenderImage<T>(target, field, parameters, isEditable));
}
/// <summary>
/// Render HTML for a link with contents
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model</param>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <returns></returns>
public virtual RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field,
object attributes = null, bool isEditable = false)
{
return GlassHtml.BeginRenderLink(model, field, this.Output, attributes, isEditable);
}
/// <summary>
/// Render HTML for a link
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model</param>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <param name="contents">Content to override the default decription or item name</param>
/// <returns></returns>
public virtual HtmlString RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents = null)
{
return new HtmlString(GlassHtml.RenderLink(model, field, attributes, isEditable, contents));
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <param name="field">The field that should be made editable</param>
/// <param name="parameters"></param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable(Expression<Func<TModel, object>> field, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(Model, field, parameters));
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <param name="field">The field that should be made editable</param>
/// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable(Expression<Func<TModel, object>> field, Expression<Func<TModel, string>> standardOutput, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(Model, field, standardOutput, parameters));
}
/// <summary>
/// Renders an image allowing simple page editor support
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model that contains the image field</param>
/// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param>
/// <param name="parameters">Image parameters, e.g. width, height</param>
/// <param name="isEditable">Indicates if the field should be editable</param>
/// <returns></returns>
public virtual HtmlString RenderImage(Expression<Func<TModel, object>> field,
object parameters = null,
bool isEditable = false)
{
return new HtmlString(GlassHtml.RenderImage(Model, field, parameters, isEditable));
}
/// <summary>
/// Render HTML for a link with contents
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model</param>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <returns></returns>
public virtual RenderingResult BeginRenderLink(Expression<Func<TModel, object>> field,
object attributes = null, bool isEditable = false)
{
return GlassHtml.BeginRenderLink(this.Model, field, this.Output, attributes, isEditable);
}
/// <summary>
/// Render HTML for a link
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model</param>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <param name="contents">Content to override the default decription or item name</param>
/// <returns></returns>
public virtual HtmlString RenderLink(Expression<Func<TModel, object>> field, object attributes = null, bool isEditable = false, string contents = null)
{
return new HtmlString(GlassHtml.RenderLink(this.Model, field, attributes, isEditable, contents));
}
/// <summary>
/// Begins the edit frame.
/// </summary>
/// <param name="buttons">The buttons.</param>
/// <param name="dataSource">The data source.</param>
/// <returns></returns>
public GlassEditFrame BeginEditFrame(string buttons, string dataSource)
{
var frame = new GlassEditFrame(buttons, this.Output, dataSource);
frame.RenderFirstPart();
return frame;
}
/// <summary>
/// Creates an Edit Frame using the Default Buttons list
/// </summary>
/// <param name="dataSource"></param>
/// <returns></returns>
public GlassEditFrame BeginEditFrame(string dataSource)
{
var frame = new GlassEditFrame(GlassEditFrame.DefaultEditButtons, this.Output, dataSource);
frame.RenderFirstPart();
return frame;
}
/// <summary>
/// Creates an edit frame using the current context item
/// </summary>
/// <returns></returns>
public GlassEditFrame BeginEditFrame()
{
var frame = new GlassEditFrame(GlassEditFrame.DefaultEditButtons, this.Output);
frame.RenderFirstPart();
return frame;
}
public T GetRenderingParameters<T>() where T: class
{
var parameters = Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering[Sc.GlassHtml.Parameters];
return
GlassHtml.GetRenderingParameters<T>(parameters);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.SubCommands
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DocAsCode;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Exceptions;
using Microsoft.DocAsCode.Plugins;
using Newtonsoft.Json;
internal sealed class InitCommand : ISubCommand
{
#region private members
private const string ConfigName = Constants.ConfigFileName;
private const string DefaultOutputFolder = "docfx_project";
private const string DefaultMetadataOutputFolder = "api";
private static readonly string[] DefaultExcludeFiles = new string[] { "obj/**" };
private static readonly string[] DefaultSrcExcludeFiles = new string[] { "**/obj/**", "**/bin/**" };
private readonly InitCommandOptions _options;
private static readonly IEnumerable<IQuestion> _metadataQuestions = new IQuestion[]
{
new MultiAnswerQuestion(
"What are the locations of your source code files?", (s, m, c) =>
{
if (s != null)
{
var exclude = new FileItems(DefaultSrcExcludeFiles);
if(!string.IsNullOrEmpty(m.Build.Destination))
{
exclude.Add($"{m.Build.Destination}/**");
}
var item = new FileMapping(new FileMappingItem(s) { Exclude = exclude });
m.Metadata.Add(new MetadataJsonItemConfig
{
Source = item,
Destination = DefaultMetadataOutputFolder,
});
m.Build.Content = new FileMapping(new FileMappingItem("api/**.yml", "api/index.md"));
}
},
new string[] { "src/**.csproj" }) {
Descriptions = new string[]
{
"Supported project files could be .sln, .csproj, .vbproj project files or .cs, .vb source files",
Hints.Glob,
Hints.Enter,
}
},
new MultiAnswerQuestion(
"What are the locations of your markdown files overwriting triple slash comments?", (s, m, c) =>
{
if (s != null)
{
var exclude = new FileItems(DefaultExcludeFiles);
if(!string.IsNullOrEmpty(m.Build.Destination))
{
exclude.Add($"{m.Build.Destination}/**");
}
m.Build.Overwrite = new FileMapping(new FileMappingItem(s) { Exclude = exclude });
}
},
new string[] { "apidoc/**.md" }) {
Descriptions = new string[]
{
"You can specify markdown files with a YAML header to overwrite summary, remarks and description for parameters",
Hints.Glob,
Hints.Enter,
}
},
};
private static readonly IEnumerable<IQuestion> _overallQuestion = new IQuestion[]
{
new SingleAnswerQuestion(
"Where to save the generated documentation?", (s, m, c) => {
m.Build.Destination = s;
},
"_site") {
Descriptions = new string[]
{
Hints.Enter,
}
},
};
private static readonly IEnumerable<IQuestion> _buildQuestions = new IQuestion[]
{
// TODO: Check if the input glob pattern matches any files
// IF no matching: WARN [init]: There is no file matching this pattern.
new MultiAnswerQuestion(
"What are the locations of your conceptual files?", (s, m, c) =>
{
if (s != null)
{
if (m.Build.Content == null)
{
m.Build.Content = new FileMapping();
}
var exclude = new FileItems(DefaultExcludeFiles);
if(!string.IsNullOrEmpty(m.Build.Destination))
{
exclude.Add($"{m.Build.Destination}/**");
}
m.Build.Content.Add(new FileMappingItem(s) { Exclude = exclude });
}
},
new string[] { "articles/**.md", "articles/**/toc.yml", "toc.yml", "*.md" }) {
Descriptions = new string[]
{
"Supported conceptual files could be any text files. Markdown format is also supported.",
Hints.Glob,
Hints.Enter,
}
},
new MultiAnswerQuestion(
"What are the locations of your resource files?", (s, m, c) =>
{
if (s != null)
{
var exclude = new FileItems(DefaultExcludeFiles);
if(!string.IsNullOrEmpty(m.Build.Destination))
{
exclude.Add($"{m.Build.Destination}/**");
}
m.Build.Resource = new FileMapping(new FileMappingItem(s) { Exclude = exclude });
}
},
new string[] { "images/**" }) {
Descriptions = new string[]
{
"The resource files which conceptual files are referencing, e.g. images.",
Hints.Glob,
Hints.Enter,
}
},
new MultiAnswerQuestion(
"Do you want to specify external API references?", (s, m, c) =>
{
if (s != null)
{
m.Build.ExternalReference = new FileMapping(new FileMappingItem(s));
}
},
null) {
Descriptions = new string[]
{
"Supported external API references can be in either JSON or YAML format.",
Hints.Glob,
Hints.Enter,
}
},
new MultiAnswerQuestion(
"What documentation templates do you want to use?", (s, m, c) => { if (s != null) m.Build.Templates.AddRange(s); },
new string[] { "default" }) {
Descriptions = new string[]
{
"You can define multiple templates in order. The latter one will overwrite the former one if names collide",
"Predefined templates in docfx are now: default, statictoc",
Hints.Enter,
}
}
};
private static readonly IEnumerable<IQuestion> _selectorQuestions = new IQuestion[]
{
new YesOrNoQuestion(
"Does the website contain API documentation from source code?", (s, m, c) =>
{
m.Build = new BuildJsonConfig();
if (s)
{
m.Metadata = new MetadataJsonConfig();
c.ContainsMetadata = true;
}
else
{
c.ContainsMetadata = false;
}
}),
};
#endregion
public bool AllowReplay => false;
public InitCommand(InitCommandOptions options)
{
_options = options;
}
public void Exec(SubCommandRunningContext context)
{
string outputFolder = null;
try
{
var config = new DefaultConfigModel();
var questionContext = new QuestionContext
{
Quiet = _options.Quiet
};
foreach (var question in _selectorQuestions)
{
question.Process(config, questionContext);
}
foreach (var question in _overallQuestion)
{
question.Process(config, questionContext);
}
if (questionContext.ContainsMetadata)
{
foreach (var question in _metadataQuestions)
{
question.Process(config, questionContext);
}
}
foreach (var question in _buildQuestions)
{
question.Process(config, questionContext);
}
if (_options.OnlyConfigFile)
{
GenerateConfigFile(_options.OutputFolder, config);
}
else
{
outputFolder = StringExtension.ToDisplayPath(Path.GetFullPath(string.IsNullOrEmpty(_options.OutputFolder) ? DefaultOutputFolder : _options.OutputFolder));
GenerateSeedProject(outputFolder, config);
}
}
catch (Exception e)
{
throw new DocfxInitException($"Error with init docfx project under \"{outputFolder}\" : {e.Message}", e);
}
}
private static void GenerateConfigFile(string outputFolder, object config)
{
var path = StringExtension.ToDisplayPath(Path.Combine(outputFolder ?? string.Empty, ConfigName));
if (File.Exists(path))
{
if (!ProcessOverwriteQuestion($"Config file \"{path}\" already exists, do you want to overwrite this file?"))
{
return;
}
}
SaveConfigFile(path, config);
$"Successfully generated default docfx config file to {path}".WriteLineToConsole(ConsoleColor.Green);
}
private static void GenerateSeedProject(string outputFolder, DefaultConfigModel config)
{
if (Directory.Exists(outputFolder))
{
if (!ProcessOverwriteQuestion($"Output folder \"{outputFolder}\" already exists. Do you still want to generate files into this folder? You can use -o command option to specify the folder name"))
{
return;
}
}
else
{
Directory.CreateDirectory(outputFolder);
}
// 1. Create default files
var srcFolder = Path.Combine(outputFolder, "src");
var apiFolder = Path.Combine(outputFolder, "api");
var apidocFolder = Path.Combine(outputFolder, "apidoc");
var articleFolder = Path.Combine(outputFolder, "articles");
var imageFolder = Path.Combine(outputFolder, "images");
var folders = new string[] { srcFolder, apiFolder, apidocFolder, articleFolder, imageFolder };
foreach (var folder in folders)
{
Directory.CreateDirectory(folder);
$"Created folder {StringExtension.ToDisplayPath(folder)}".WriteLineToConsole(ConsoleColor.Gray);
}
// 2. Create default files
// a. toc.yml
// b. index.md
// c. articles/toc.yml
// d. articles/index.md
// e. .gitignore
// f. api/.gitignore
// TODO: move api/index.md out to some other folder
var tocYaml = Tuple.Create("toc.yml", @"- name: Articles
href: articles/
- name: Api Documentation
href: api/
homepage: api/index.md
");
var indexMarkdownFile = Tuple.Create("index.md", @"# This is the **HOMEPAGE**.
Refer to [Markdown](http://daringfireball.net/projects/markdown/) for how to write markdown files.
## Quick Start Notes:
1. Add images to the *images* folder if the file is referencing an image.
");
var apiTocFile = Tuple.Create("api/toc.yml", @"- name: TO BE REPLACED
- href: index.md
");
var apiIndexFile = Tuple.Create("api/index.md", @"# PLACEHOLDER
TODO: Add .NET projects to the *src* folder and run `docfx` to generate **REAL** *API Documentation*!
");
var articleTocFile = Tuple.Create("articles/toc.yml", @"- name: Introduction
href: intro.md
");
var articleMarkdownFile = Tuple.Create("articles/intro.md", @"# Add your introductions here!
");
var gitignore = Tuple.Create(".gitignore", $@"###############
# folder #
###############
/**/DROP/
/**/TEMP/
/**/packages/
/**/bin/
/**/obj/
{config.Build.Destination}
");
var apiGitignore = Tuple.Create("api/.gitignore", $@"###############
# temp file #
###############
*.yml
");
var files = new Tuple<string, string>[] { tocYaml, indexMarkdownFile, apiTocFile, apiIndexFile, articleTocFile, articleMarkdownFile, gitignore, apiGitignore };
foreach (var file in files)
{
var filePath = Path.Combine(outputFolder, file.Item1);
var content = file.Item2;
var dir = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllText(filePath, content);
$"Created File {StringExtension.ToDisplayPath(filePath)}".WriteLineToConsole(ConsoleColor.Gray);
}
// 2. Create docfx.json
var path = Path.Combine(outputFolder ?? string.Empty, ConfigName);
SaveConfigFile(path, config);
$"Created config file {StringExtension.ToDisplayPath(path)}".WriteLineToConsole(ConsoleColor.Gray);
$"Successfully generated default docfx project to {StringExtension.ToDisplayPath(outputFolder)}".WriteLineToConsole(ConsoleColor.Green);
"Please run:".WriteLineToConsole(ConsoleColor.Gray);
$"\tdocfx \"{StringExtension.ToDisplayPath(path)}\" --serve".WriteLineToConsole(ConsoleColor.White);
"To generate a default docfx website.".WriteLineToConsole(ConsoleColor.Gray);
}
private static void SaveConfigFile(string path, object config)
{
JsonUtility.Serialize(path, config, Formatting.Indented);
}
private static bool ProcessOverwriteQuestion(string message)
{
bool overwrited = true;
var overwriteQuestion = new NoOrYesQuestion(
message,
(s, m, c) =>
{
if (!s)
{
overwrited = false;
}
});
overwriteQuestion.Process(null, new QuestionContext { NeedWarning = overwrited });
return overwrited;
}
#region Question classes
private static class YesOrNoOption
{
public const string YesAnswer = "Yes";
public const string NoAnswer = "No";
}
/// <summary>
/// the default option is Yes
/// </summary>
private sealed class YesOrNoQuestion : SingleChoiceQuestion<bool>
{
private static readonly string[] YesOrNoAnswer = { YesOrNoOption.YesAnswer, YesOrNoOption.NoAnswer };
public YesOrNoQuestion(string content, Action<bool, DefaultConfigModel, QuestionContext> setter) : base(content, setter, Converter, YesOrNoAnswer)
{
}
private static bool Converter(string input)
{
return input == YesOrNoOption.YesAnswer;
}
}
/// <summary>
/// the default option is No
/// </summary>
private sealed class NoOrYesQuestion : SingleChoiceQuestion<bool>
{
private static readonly string[] NoOrYesAnswer = { YesOrNoOption.NoAnswer, YesOrNoOption.YesAnswer };
public NoOrYesQuestion(string content, Action<bool, DefaultConfigModel, QuestionContext> setter) : base(content, setter, Converter, NoOrYesAnswer)
{
}
private static bool Converter(string input)
{
return input == YesOrNoOption.YesAnswer;
}
}
private class SingleChoiceQuestion<T> : Question<T>
{
private Func<string, T> _converter;
/// <summary>
/// Options, the first one as the default one
/// </summary>
public string[] Options { get; set; }
public SingleChoiceQuestion(string content, Action<T, DefaultConfigModel, QuestionContext> setter, Func<string, T> converter, params string[] options)
: base(content, setter)
{
if (options == null || options.Length == 0) throw new ArgumentNullException(nameof(options));
if (converter == null) throw new ArgumentNullException(nameof(converter));
_converter = converter;
Options = options;
DefaultAnswer = options[0];
DefaultValue = converter(DefaultAnswer);
}
protected override T GetAnswer()
{
var options = Options;
Console.Write("Choose Answer ({0}): ", string.Join("/", options));
Console.Write(DefaultAnswer[0]);
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
string matched = null;
var line = Console.ReadLine();
while (!string.IsNullOrEmpty(line))
{
matched = GetMatchedOption(options, line);
if (matched == null)
{
Console.Write("Invalid Answer, please reenter: ");
}
else
{
return _converter(matched);
}
line = Console.ReadLine();
}
return DefaultValue;
}
private static string GetMatchedOption(string[] options, string input)
{
return options.FirstOrDefault(s => s.Equals(input, StringComparison.OrdinalIgnoreCase) || s.Substring(0, 1).Equals(input, StringComparison.OrdinalIgnoreCase));
}
}
private sealed class MultiAnswerQuestion : Question<string[]>
{
public MultiAnswerQuestion(string content, Action<string[], DefaultConfigModel, QuestionContext> setter, string[] defaultValue = null)
: base(content, setter)
{
DefaultValue = defaultValue;
DefaultAnswer = ConvertToString(defaultValue);
}
protected override string[] GetAnswer()
{
var line = Console.ReadLine();
List<string> answers = new List<string>();
while (!string.IsNullOrEmpty(line))
{
answers.Add(line);
line = Console.ReadLine();
}
if (answers.Count > 0)
{
return answers.ToArray();
}
else
{
return DefaultValue;
}
}
private static string ConvertToString(string[] array)
{
if (array == null) return null;
return string.Join(",", array);
}
}
private sealed class SingleAnswerQuestion : Question<string>
{
public SingleAnswerQuestion(string content, Action<string, DefaultConfigModel, QuestionContext> setter, string defaultAnswer = null)
: base(content, setter)
{
DefaultValue = defaultAnswer;
DefaultAnswer = defaultAnswer;
}
protected override string GetAnswer()
{
var line = Console.ReadLine();
if (!string.IsNullOrEmpty(line))
{
return line;
}
else
{
return DefaultValue;
}
}
}
private abstract class Question<T> : IQuestion
{
private Action<T, DefaultConfigModel, QuestionContext> _setter { get; }
public string Content { get; }
/// <summary>
/// Each string stands for one line
/// </summary>
public string[] Descriptions { get; set; }
public T DefaultValue { get; protected set; }
public string DefaultAnswer { get; protected set; }
public Question(string content, Action<T, DefaultConfigModel, QuestionContext> setter)
{
if (setter == null) throw new ArgumentNullException(nameof(setter));
Content = content;
_setter = setter;
}
public void Process(DefaultConfigModel model, QuestionContext context)
{
if (context.Quiet)
{
_setter(DefaultValue, model, context);
}
else
{
WriteQuestion(context);
var value = GetAnswer();
_setter(value, model, context);
}
}
protected abstract T GetAnswer();
private void WriteQuestion(QuestionContext context)
{
Content.WriteToConsole(context.NeedWarning ? ConsoleColor.Yellow : ConsoleColor.White);
WriteDefaultAnswer();
Descriptions.WriteLinesToConsole(ConsoleColor.Gray);
}
private void WriteDefaultAnswer()
{
if (DefaultAnswer == null)
{
Console.WriteLine();
return;
}
" (Default: ".WriteToConsole(ConsoleColor.Gray);
DefaultAnswer.WriteToConsole(ConsoleColor.Green);
")".WriteLineToConsole(ConsoleColor.Gray);
}
}
private interface IQuestion
{
void Process(DefaultConfigModel model, QuestionContext context);
}
private sealed class QuestionContext
{
public bool Quiet { get; set; }
public bool ContainsMetadata { get; set; }
public bool NeedWarning { get; set; }
}
#endregion
private static class Hints
{
public const string Tab = "Press TAB to list possible options.";
public const string Enter = "Press ENTER to move to the next question.";
public const string Glob = "You can use glob patterns, e.g. src/**";
}
private class DefaultConfigModel
{
[JsonProperty("metadata")]
public MetadataJsonConfig Metadata { get; set; }
[JsonProperty("build")]
public BuildJsonConfig Build { get; set; }
}
}
}
| |
// 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 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// HttpSuccess operations.
/// </summary>
public partial interface IHttpSuccess
{
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Head200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get 200 success
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<bool?>> Get200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put boolean value true returning 200 success
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Put200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch true Boolean value in request returning 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Patch200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post bollean value true in request that returns a 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Post200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete simple boolean value true returns 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Delete200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put true Boolean value in request returns 201
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Put201WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post true Boolean value in request returns 201 (Created)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Post201WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Put202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch true Boolean value in request returns 202
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Patch202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Post202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete true Boolean value in request returns 202 (accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Delete202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Head204WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Put204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Patch204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Post204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Delete204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 404 status code
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Head404WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
#if UNITY_ANDROID || UNITY_IPHONE
namespace Chartboost {
public class CBBinding {
#if UNITY_ANDROID
private static AndroidJavaObject _plugin;
static CBBinding()
{
if( Application.platform != RuntimePlatform.Android )
return;
// find the plugin instance
using( var pluginClass = new AndroidJavaClass( "com.chartboost.sdk.unity.CBPlugin" ) )
_plugin = pluginClass.CallStatic<AndroidJavaObject>( "instance" );
}
#elif UNITY_IPHONE
[DllImport("__Internal")]
private static extern void _chartBoostInit( string appId, string appSignature );
[DllImport("__Internal")]
private static extern void _chartBoostCacheInterstitial( string location );
[DllImport("__Internal")]
private static extern bool _chartBoostHasCachedInterstitial( string location );
[DllImport("__Internal")]
private static extern void _chartBoostShowInterstitial( string location );
[DllImport("__Internal")]
private static extern void _chartBoostCacheMoreApps();
[DllImport("__Internal")]
private static extern bool _chartBoostHasCachedMoreApps();
[DllImport("__Internal")]
private static extern void _chartBoostShowMoreApps();
[DllImport("__Internal")]
private static extern void _chartBoostForceOrientation( string orient );
[DllImport("__Internal")]
private static extern void _chartBoostTrackEvent( string eventIdentifier );
[DllImport("__Internal")]
private static extern void _chartBoostTrackEventWithMetadata( string eventIdentifier, string metadata );
[DllImport("__Internal")]
private static extern void _chartBoostTrackEventWithValue( string eventIdentifier, float value );
[DllImport("__Internal")]
private static extern void _chartBoostTrackEventWithValueAndMetadata( string eventIdentifier, float value, string metadata );
#endif
private static bool initialized = false;
private static bool checkInitialized()
{
#if UNITY_ANDROID
if( Application.platform != RuntimePlatform.Android )
return false;
#elif UNITY_IPHONE
if( Application.platform != RuntimePlatform.IPhonePlayer )
return false;
#endif
if( initialized ) {
return true;
} else {
Debug.Log( "Please call CBBinding.init() before using any other features of this library." );
return false;
}
}
#if UNITY_ANDROID
/// Initializes the Chartboost plugin
/// This must be called before using any other Chartboost features
public static void init()
{
if( Application.platform == RuntimePlatform.Android )
_plugin.Call( "init" );
initialized = true;
}
#elif UNITY_IPHONE
/// Initializes the Chartboost plugin and records the beginning of a user session
/// This must be called before using any other Chartboost features
public static void init( string appId, string appSignature )
{
if( Application.platform == RuntimePlatform.IPhonePlayer )
_chartBoostInit( appId, appSignature );
initialized = true;
}
#endif
#if UNITY_ANDROID
/// Return whether impressions are shown using an additional activity instead
/// of just overlaying on top of the Unity activity. Default is true.
/// See `Plugins/Android/res/values/strings.xml` to set this value
public static bool getImpressionsUseActivities()
{
if( !checkInitialized() )
return true;
return _plugin.Call<bool>( "getImpressionsUseActivities" );
}
/// Used to notify Chartboost that the Android back button has been pressed
/// Returns true to indicate that Chartboost has handled the event and it should not be further processed
public static bool onBackPressed()
{
if( !checkInitialized() )
return false;
return _plugin.Call<bool>( "onBackPressed" );
}
#endif
/// Returns true if an impression (interstitial or more apps page) is currently visible
public static bool isImpressionVisible()
{
if( !checkInitialized() )
return false;
return CBManager.isImpressionVisible();
}
/// Caches an interstitial. Location is optional. Pass in null if you do not want to specify the location.
public static void cacheInterstitial( string location )
{
if( !checkInitialized() )
return;
#if UNITY_ANDROID
if( location == null )
location = string.Empty;
_plugin.Call( "cacheInterstitial", location );
#elif UNITY_IPHONE
_chartBoostCacheInterstitial( location );
#endif
}
/// Checks for a cached an interstitial. Location is optional. Pass in null if you do not want to specify the location.
public static bool hasCachedInterstitial( string location )
{
if( !checkInitialized() )
return false;
if( location == null )
location = string.Empty;
#if UNITY_ANDROID
if( location == null )
location = string.Empty;
return _plugin.Call<bool>( "hasCachedInterstitial", location );
#elif UNITY_IPHONE
return _chartBoostHasCachedInterstitial( location );
#endif
}
/// Loads an interstitial. Location is optional. Pass in null if you do not want to specify the location.
public static void showInterstitial( string location )
{
if( !checkInitialized() )
return;
#if UNITY_ANDROID
if( location == null )
location = string.Empty;
_plugin.Call( "showInterstitial", location );
#elif UNITY_IPHONE
_chartBoostShowInterstitial( location );
#endif
}
/// Caches the more apps screen
public static void cacheMoreApps()
{
if( !checkInitialized() )
return;
#if UNITY_ANDROID
_plugin.Call( "cacheMoreApps" );
#elif UNITY_IPHONE
_chartBoostCacheMoreApps();
#endif
}
/// Checks to see if the more apps screen is cached
public static bool hasCachedMoreApps()
{
if( !checkInitialized() )
return false;
#if UNITY_ANDROID
return _plugin.Call<bool>( "hasCachedMoreApps" );
#elif UNITY_IPHONE
return _chartBoostHasCachedMoreApps();
#endif
}
/// Shows the more apps screen
public static void showMoreApps()
{
if( !checkInitialized() )
return;
#if UNITY_ANDROID
_plugin.Call( "showMoreApps" );
#elif UNITY_IPHONE
_chartBoostShowMoreApps();
#endif
}
/// Forces the orientation of impressions to the given orientation
#if UNITY_IPHONE
/// If your project is properly setup to autorotate, animated native views
/// will work as expected and you should not need to set this
#endif
public static void forceOrientation( ScreenOrientation orient )
{
if( !checkInitialized() )
return;
#if UNITY_ANDROID
_plugin.Call( "forceOrientation", orient.ToString() );
#elif UNITY_IPHONE
_chartBoostForceOrientation( orient.ToString() );
#endif
}
#region event tracking
/// Tracks an event
public static void trackEvent( string eventIdentifier )
{
if( !checkInitialized() )
return;
#if UNITY_ANDROID
_plugin.Call( "trackEvent", eventIdentifier );
#elif UNITY_IPHONE
_chartBoostTrackEvent( eventIdentifier );
#endif
}
/// Tracks an event with additional metadata
public static void trackEventWithMetadata( string eventIdentifier, Hashtable metadata )
{
if( !checkInitialized() )
return;
#if UNITY_ANDROID
_plugin.Call( "trackEventWithMetadata", eventIdentifier, CBJSON.Serialize( metadata ) );
#elif UNITY_IPHONE
_chartBoostTrackEventWithMetadata( eventIdentifier, CBJSON.Serialize( metadata ) );
#endif
}
/// Tracks an event with a value
public static void trackEventWithValue( string eventIdentifier, float val )
{
if( !checkInitialized() )
return;
#if UNITY_ANDROID
_plugin.Call( "trackEventWithValue", eventIdentifier, val );
#elif UNITY_IPHONE
_chartBoostTrackEventWithValue( eventIdentifier, val );
#endif
}
/// Tracks an event with a value and additional metadata
public static void trackEventWithValueAndMetadata( string eventIdentifier, float val, Hashtable metadata )
{
if( !checkInitialized() )
return;
#if UNITY_ANDROID
_plugin.Call( "trackEventWithValueAndMetadata", eventIdentifier, val, CBJSON.Serialize( metadata ) );
#elif UNITY_IPHONE
_chartBoostTrackEventWithValueAndMetadata( eventIdentifier, val, CBJSON.Serialize( metadata ) );
#endif
}
#endregion
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.DirectoryServices.ActiveDirectory
{
public abstract class DirectoryServer : IDisposable
{
private bool _disposed = false;
internal DirectoryContext context = null;
internal string replicaName = null;
internal DirectoryEntryManager directoryEntryMgr = null;
// internal variables for the public properties
internal bool siteInfoModified = false;
internal string cachedSiteName = null;
internal string cachedSiteObjectName = null;
internal string cachedServerObjectName = null;
internal string cachedNtdsaObjectName = null;
internal Guid cachedNtdsaObjectGuid = Guid.Empty;
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal string cachedIPAddress = null;
#pragma warning restore 0414
internal ReadOnlyStringCollection cachedPartitions = null;
internal const int DS_REPSYNC_ASYNCHRONOUS_OPERATION = 0x00000001;
internal const int DS_REPSYNC_ALL_SOURCES = 0x00000010;
internal const int DS_REPSYNCALL_ID_SERVERS_BY_DN = 0x00000004;
internal const int DS_REPL_NOTSUPPORTED = 50;
private ReplicationConnectionCollection _inbound = null;
private ReplicationConnectionCollection _outbound = null;
#region constructors
protected DirectoryServer()
{
}
#endregion constructors
#region IDisposable
~DirectoryServer() => Dispose(false);
public void Dispose()
{
Dispose(true);
// Take yourself off of the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// private Dispose method
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
// check if this is an explicit Dispose
// only then clean up the directory entries
if (disposing)
{
// dispose all directory entries
foreach (DirectoryEntry entry in directoryEntryMgr.GetCachedDirectoryEntries())
{
entry.Dispose();
}
}
_disposed = true;
}
}
#endregion IDisposable
#region public methods
public override string ToString() => Name;
public void MoveToAnotherSite(string siteName)
{
CheckIfDisposed();
// validate siteName
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
if (siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName));
}
// the dc is really being moved to a different site
if (Utils.Compare(SiteName, siteName) != 0)
{
DirectoryEntry newParentEntry = null;
try
{
// Bind to the target site's server container
// Get the distinguished name for the site
string parentDN = "CN=Servers,CN=" + siteName + "," + directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SitesContainer);
newParentEntry = DirectoryEntryManager.GetDirectoryEntry(context, parentDN);
string serverName = (this is DomainController) ? ((DomainController)this).ServerObjectName : ((AdamInstance)this).ServerObjectName;
DirectoryEntry serverEntry = directoryEntryMgr.GetCachedDirectoryEntry(serverName);
// force binding (needed otherwise S.DS throw an exception while releasing the COM interface pointer)
string dn = (string)PropertyManager.GetPropertyValue(context, serverEntry, PropertyManager.DistinguishedName);
// move the object to the servers container of the target site
serverEntry.MoveTo(newParentEntry);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (newParentEntry != null)
{
newParentEntry.Dispose();
}
}
// remove stale cached directory entries
// invalidate the cached properties that get affected by this
siteInfoModified = true;
cachedSiteName = null;
if (cachedSiteObjectName != null)
{
directoryEntryMgr.RemoveIfExists(cachedSiteObjectName);
cachedSiteObjectName = null;
}
if (cachedServerObjectName != null)
{
directoryEntryMgr.RemoveIfExists(cachedServerObjectName);
cachedServerObjectName = null;
}
if (cachedNtdsaObjectName != null)
{
directoryEntryMgr.RemoveIfExists(cachedNtdsaObjectName);
cachedNtdsaObjectName = null;
}
}
}
public DirectoryEntry GetDirectoryEntry()
{
CheckIfDisposed();
string serverName = (this is DomainController) ? ((DomainController)this).ServerObjectName : ((AdamInstance)this).ServerObjectName;
return DirectoryEntryManager.GetDirectoryEntry(context, serverName);
}
#endregion public methods
#region public abstract methods
public abstract void CheckReplicationConsistency();
public abstract ReplicationCursorCollection GetReplicationCursors(string partition);
public abstract ReplicationOperationInformation GetReplicationOperationInformation();
public abstract ReplicationNeighborCollection GetReplicationNeighbors(string partition);
public abstract ReplicationNeighborCollection GetAllReplicationNeighbors();
public abstract ReplicationFailureCollection GetReplicationConnectionFailures();
public abstract ActiveDirectoryReplicationMetadata GetReplicationMetadata(string objectPath);
public abstract void SyncReplicaFromServer(string partition, string sourceServer);
public abstract void TriggerSyncReplicaFromNeighbors(string partition);
public abstract void SyncReplicaFromAllServers(string partition, SyncFromAllServersOptions options);
#endregion public abstract methods
#region public properties
public string Name
{
get
{
CheckIfDisposed();
return replicaName;
}
}
public ReadOnlyStringCollection Partitions
{
get
{
CheckIfDisposed();
if (cachedPartitions == null)
{
cachedPartitions = new ReadOnlyStringCollection(GetPartitions());
}
return cachedPartitions;
}
}
#endregion public properties
#region public abstract properties
public abstract string IPAddress { get; }
public abstract string SiteName { get; }
public abstract SyncUpdateCallback SyncFromAllServersCallback { get; set; }
public abstract ReplicationConnectionCollection InboundConnections { get; }
public abstract ReplicationConnectionCollection OutboundConnections { get; }
#endregion public abstract properties
#region private methods
internal ArrayList GetPartitions()
{
ArrayList partitionList = new ArrayList();
DirectoryEntry rootDSE = null;
DirectoryEntry serverNtdsaEntry = null;
try
{
// get the writable partitions
rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
// don't need range retrieval for root dse attributes
foreach (string partition in rootDSE.Properties[PropertyManager.NamingContexts])
{
partitionList.Add(partition);
}
// also the read only partitions
string ntdsaName = (this is DomainController) ? ((DomainController)this).NtdsaObjectName : ((AdamInstance)this).NtdsaObjectName;
serverNtdsaEntry = DirectoryEntryManager.GetDirectoryEntry(context, ntdsaName);
// use range retrieval
ArrayList propertyNames = new ArrayList();
propertyNames.Add(PropertyManager.HasPartialReplicaNCs);
Hashtable values = null;
try
{
values = Utils.GetValuesWithRangeRetrieval(serverNtdsaEntry, null, propertyNames, SearchScope.Base);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
ArrayList readOnlyPartitions = (ArrayList)values[PropertyManager.HasPartialReplicaNCs.ToLower(CultureInfo.InvariantCulture)];
Debug.Assert(readOnlyPartitions != null);
foreach (string readOnlyPartition in readOnlyPartitions)
{
partitionList.Add(readOnlyPartition);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (rootDSE != null)
{
rootDSE.Dispose();
}
if (serverNtdsaEntry != null)
{
serverNtdsaEntry.Dispose();
}
}
return partitionList;
}
internal void CheckIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
internal DirectoryContext Context => context;
internal void CheckConsistencyHelper(IntPtr dsHandle, LoadLibrarySafeHandle libHandle)
{
// call DsReplicaConsistencyCheck
IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaConsistencyCheck");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
UnsafeNativeMethods.DsReplicaConsistencyCheck replicaConsistencyCheck = (UnsafeNativeMethods.DsReplicaConsistencyCheck)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaConsistencyCheck));
int result = replicaConsistencyCheck(dsHandle, 0, 0);
if (result != 0)
throw ExceptionHelper.GetExceptionFromErrorCode(result, Name);
}
internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondaryType, string partition, ref bool advanced, int context, LoadLibrarySafeHandle libHandle)
{
IntPtr info = (IntPtr)0;
int result = 0;
bool needToTryAgain = true;
IntPtr functionPtr;
// first try to use the DsReplicaGetInfo2W API which does not exist on win2k machine
// call DsReplicaGetInfo2W
functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfo2W");
if (functionPtr == (IntPtr)0)
{
// a win2k machine which does not have it.
functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfoW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
UnsafeNativeMethods.DsReplicaGetInfoW dsReplicaGetInfoW = (UnsafeNativeMethods.DsReplicaGetInfoW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaGetInfoW));
result = dsReplicaGetInfoW(dsHandle, secondaryType, partition, (IntPtr)0, ref info);
advanced = false;
needToTryAgain = false;
}
else
{
UnsafeNativeMethods.DsReplicaGetInfo2W dsReplicaGetInfo2W = (UnsafeNativeMethods.DsReplicaGetInfo2W)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaGetInfo2W));
result = dsReplicaGetInfo2W(dsHandle, type, partition, (IntPtr)0, null, null, 0, context, ref info);
}
// check the result
if (needToTryAgain && result == DS_REPL_NOTSUPPORTED)
{
// this is the case that client is xp/win2k3, dc is win2k
functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfoW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
UnsafeNativeMethods.DsReplicaGetInfoW dsReplicaGetInfoW = (UnsafeNativeMethods.DsReplicaGetInfoW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaGetInfoW));
result = dsReplicaGetInfoW(dsHandle, secondaryType, partition, (IntPtr)0, ref info);
advanced = false;
}
if (result != 0)
{
if (partition != null)
{
// this is the case of meta data
if (type == (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_2_FOR_OBJ)
{
if (result == ExceptionHelper.ERROR_DS_DRA_BAD_DN || result == ExceptionHelper.ERROR_DS_NAME_UNPARSEABLE)
throw new ArgumentException(ExceptionHelper.GetErrorMessage(result, false), "objectPath");
DirectoryEntry verifyEntry = DirectoryEntryManager.GetDirectoryEntry(this.context, partition);
try
{
verifyEntry.RefreshCache(new string[] { "name" });
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072020) | // dir_error on server side
e.ErrorCode == unchecked((int)0x80072030)) // object not exists
throw new ArgumentException(SR.DSNoObject, "objectPath");
else if (e.ErrorCode == unchecked((int)0x80005000) | // bad path name
e.ErrorCode == unchecked((int)0x80072032)) // ERROR_DS_INVALID_DN_SYNTAX
throw new ArgumentException(SR.DSInvalidPath, "objectPath");
}
}
else
{
if (!Partitions.Contains(partition))
throw new ArgumentException(SR.ServerNotAReplica, nameof(partition));
}
}
throw ExceptionHelper.GetExceptionFromErrorCode(result, Name);
}
return info;
}
internal ReplicationCursorCollection ConstructReplicationCursors(IntPtr dsHandle, bool advanced, IntPtr info, string partition, DirectoryServer server, LoadLibrarySafeHandle libHandle)
{
int context = 0;
int count = 0;
ReplicationCursorCollection collection = new ReplicationCursorCollection(server);
// construct the collection
if (advanced)
{
// using paging to get all the results
while (true)
{
try
{
if (info != (IntPtr)0)
{
DS_REPL_CURSORS_3 cursors = new DS_REPL_CURSORS_3();
Marshal.PtrToStructure(info, cursors);
count = cursors.cNumCursors;
if (count > 0)
collection.AddHelper(partition, cursors, advanced, info);
context = cursors.dwEnumerationContext;
// we already get all the results or there is no result
if (context == -1 || count == 0)
break;
}
else
{
// should not happen, treat as no result is returned.
break;
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_3_FOR_NC, info, libHandle);
}
// get the next batch of results
info = GetReplicationInfoHelper(dsHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_3_FOR_NC, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_FOR_NC, partition, ref advanced, context, libHandle);
}
}
else
{
try
{
if (info != (IntPtr)0)
{
// structure of DS_REPL_CURSORS_3 and DS_REPL_CURSORS actually are the same
DS_REPL_CURSORS cursors = new DS_REPL_CURSORS();
Marshal.PtrToStructure(info, cursors);
collection.AddHelper(partition, cursors, advanced, info);
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_FOR_NC, info, libHandle);
}
}
return collection;
}
internal ReplicationOperationInformation ConstructPendingOperations(IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle)
{
ReplicationOperationInformation replicationInfo = new ReplicationOperationInformation();
ReplicationOperationCollection collection = new ReplicationOperationCollection(server);
replicationInfo.collection = collection;
int count = 0;
try
{
if (info != (IntPtr)0)
{
DS_REPL_PENDING_OPS operations = new DS_REPL_PENDING_OPS();
Marshal.PtrToStructure(info, operations);
count = operations.cNumPendingOps;
if (count > 0)
{
collection.AddHelper(operations, info);
replicationInfo.startTime = DateTime.FromFileTime(operations.ftimeCurrentOpStarted);
replicationInfo.currentOp = collection.GetFirstOperation();
}
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_PENDING_OPS, info, libHandle);
}
return replicationInfo;
}
internal ReplicationNeighborCollection ConstructNeighbors(IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle)
{
ReplicationNeighborCollection collection = new ReplicationNeighborCollection(server);
int count = 0;
try
{
if (info != (IntPtr)0)
{
DS_REPL_NEIGHBORS neighbors = new DS_REPL_NEIGHBORS();
Marshal.PtrToStructure(info, neighbors);
Debug.Assert(neighbors != null);
count = neighbors.cNumNeighbors;
if (count > 0)
collection.AddHelper(neighbors, info);
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, info, libHandle);
}
return collection;
}
internal ReplicationFailureCollection ConstructFailures(IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle)
{
ReplicationFailureCollection collection = new ReplicationFailureCollection(server);
int count = 0;
try
{
if (info != (IntPtr)0)
{
DS_REPL_KCC_DSA_FAILURES failures = new DS_REPL_KCC_DSA_FAILURES();
Marshal.PtrToStructure(info, failures);
count = failures.cNumEntries;
if (count > 0)
collection.AddHelper(failures, info);
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES, info, libHandle);
}
return collection;
}
internal ActiveDirectoryReplicationMetadata ConstructMetaData(bool advanced, IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle)
{
ActiveDirectoryReplicationMetadata collection = new ActiveDirectoryReplicationMetadata(server);
int count = 0;
if (advanced)
{
try
{
if (info != (IntPtr)0)
{
DS_REPL_OBJ_META_DATA_2 objMetaData = new DS_REPL_OBJ_META_DATA_2();
Marshal.PtrToStructure(info, objMetaData);
count = objMetaData.cNumEntries;
if (count > 0)
{
collection.AddHelper(count, info, true);
}
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_2_FOR_OBJ, info, libHandle);
}
}
else
{
try
{
DS_REPL_OBJ_META_DATA objMetadata = new DS_REPL_OBJ_META_DATA();
Marshal.PtrToStructure(info, objMetadata);
count = objMetadata.cNumEntries;
if (count > 0)
{
collection.AddHelper(count, info, false);
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_FOR_OBJ, info, libHandle);
}
}
return collection;
}
internal bool SyncAllCallbackRoutine(IntPtr data, IntPtr update)
{
if (SyncFromAllServersCallback == null)
{
// user does not specify callback, resume the DsReplicaSyncAll execution
return true;
}
else
{
// user specifies callback
// our callback is invoked, update should not be NULL, do assertion here
Debug.Assert(update != (IntPtr)0);
DS_REPSYNCALL_UPDATE syncAllUpdate = new DS_REPSYNCALL_UPDATE();
Marshal.PtrToStructure(update, syncAllUpdate);
// get the event type
SyncFromAllServersEvent eventType = syncAllUpdate.eventType;
// get the error information
IntPtr temp = syncAllUpdate.pErrInfo;
SyncFromAllServersOperationException exception = null;
if (temp != (IntPtr)0)
{
// error information is available
exception = ExceptionHelper.CreateSyncAllException(temp, true);
if (exception == null)
{
// this is the special case that we ingore the failure when SyncAllOptions.CheckServerAlivenessOnly is specified
return true;
}
}
string targetName = null;
string sourceName = null;
temp = syncAllUpdate.pSync;
if (temp != (IntPtr)0)
{
DS_REPSYNCALL_SYNC sync = new DS_REPSYNCALL_SYNC();
Marshal.PtrToStructure(temp, sync);
targetName = Marshal.PtrToStringUni(sync.pszDstId);
sourceName = Marshal.PtrToStringUni(sync.pszSrcId);
}
// invoke the client callback
SyncUpdateCallback clientCallback = SyncFromAllServersCallback;
return clientCallback(eventType, targetName, sourceName, exception);
}
}
internal void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallback syncAllFunctionPointer, string partition, SyncFromAllServersOptions option, SyncUpdateCallback callback, LoadLibrarySafeHandle libHandle)
{
IntPtr errorInfo = (IntPtr)0;
if (!Partitions.Contains(partition))
throw new ArgumentException(SR.ServerNotAReplica, nameof(partition));
// we want to return the dn instead of DNS guid
// call DsReplicaSyncAllW
IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaSyncAllW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
UnsafeNativeMethods.DsReplicaSyncAllW dsReplicaSyncAllW = (UnsafeNativeMethods.DsReplicaSyncAllW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaSyncAllW));
int result = dsReplicaSyncAllW(handle, partition, (int)option | DS_REPSYNCALL_ID_SERVERS_BY_DN, syncAllFunctionPointer, (IntPtr)0, ref errorInfo);
try
{
// error happens during the synchronization
if (errorInfo != (IntPtr)0)
{
SyncFromAllServersOperationException e = ExceptionHelper.CreateSyncAllException(errorInfo, false);
if (e == null)
return;
else
throw e;
}
else
{
// API does not return error infor occurred during synchronization, but result is not success.
if (result != 0)
throw new SyncFromAllServersOperationException(ExceptionHelper.GetErrorMessage(result, false));
}
}
finally
{
// release the memory
if (errorInfo != (IntPtr)0)
UnsafeNativeMethods.LocalFree(errorInfo);
}
}
private void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, LoadLibrarySafeHandle libHandle)
{
if (value != (IntPtr)0)
{
// call DsReplicaFreeInfo
IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaFreeInfo");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
UnsafeNativeMethods.DsReplicaFreeInfo dsReplicaFreeInfo = (UnsafeNativeMethods.DsReplicaFreeInfo)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaFreeInfo));
dsReplicaFreeInfo((int)type, value);
}
}
internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, string sourceServer, int option, LoadLibrarySafeHandle libHandle)
{
int structSize = Marshal.SizeOf(typeof(Guid));
IntPtr unmanagedGuid = (IntPtr)0;
Guid guid = Guid.Empty;
AdamInstance adamServer = null;
DomainController dcServer = null;
unmanagedGuid = Marshal.AllocHGlobal(structSize);
try
{
if (sourceServer != null)
{
DirectoryContext newContext = Utils.GetNewDirectoryContext(sourceServer, DirectoryContextType.DirectoryServer, context);
if (isADAM)
{
adamServer = AdamInstance.GetAdamInstance(newContext);
guid = adamServer.NtdsaObjectGuid;
}
else
{
dcServer = DomainController.GetDomainController(newContext);
guid = dcServer.NtdsaObjectGuid;
}
Marshal.StructureToPtr(guid, unmanagedGuid, false);
}
// call DsReplicaSyncW
IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaSyncW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
UnsafeNativeMethods.DsReplicaSyncW dsReplicaSyncW = (UnsafeNativeMethods.DsReplicaSyncW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaSyncW));
int result = dsReplicaSyncW(dsHandle, partition, unmanagedGuid, (int)option);
// check the result
if (result != 0)
{
if (!Partitions.Contains(partition))
throw new ArgumentException(SR.ServerNotAReplica, nameof(partition));
string serverDownName = null;
// this is the error returned when the server that we want to sync from is down
if (result == ExceptionHelper.RPC_S_SERVER_UNAVAILABLE)
serverDownName = sourceServer;
// this is the error returned when the server that we want to get synced is down
else if (result == ExceptionHelper.RPC_S_CALL_FAILED)
serverDownName = Name;
throw ExceptionHelper.GetExceptionFromErrorCode(result, serverDownName);
}
}
finally
{
if (unmanagedGuid != (IntPtr)0)
Marshal.FreeHGlobal(unmanagedGuid);
if (adamServer != null)
adamServer.Dispose();
if (dcServer != null)
dcServer.Dispose();
}
}
internal ReplicationConnectionCollection GetInboundConnectionsHelper()
{
if (_inbound == null)
{
// construct the replicationconnection collection
_inbound = new ReplicationConnectionCollection();
DirectoryContext newContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context);
// this is the first time that user tries to retrieve this property, so get it from the directory
string serverName = (this is DomainController) ? ((DomainController)this).ServerObjectName : ((AdamInstance)this).ServerObjectName;
string srchDN = "CN=NTDS Settings," + serverName;
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context), srchDN);
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=nTDSConnection)(objectCategory=nTDSConnection))",
new string[] { "cn" },
SearchScope.OneLevel);
SearchResultCollection srchResults = null;
try
{
srchResults = adSearcher.FindAll();
foreach (SearchResult r in srchResults)
{
ReplicationConnection con = new ReplicationConnection(newContext, r.GetDirectoryEntry(), (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.Cn));
_inbound.Add(con);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(newContext, e);
}
finally
{
if (srchResults != null)
srchResults.Dispose();
de.Dispose();
}
}
return _inbound;
}
internal ReplicationConnectionCollection GetOutboundConnectionsHelper()
{
// this is the first time that user tries to retrieve this property, so get it from the directory
if (_outbound == null)
{
// search base is the site container
string siteName = (this is DomainController) ? ((DomainController)this).SiteObjectName : ((AdamInstance)this).SiteObjectName;
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context), siteName);
string serverName = (this is DomainController) ? ((DomainController)this).ServerObjectName : ((AdamInstance)this).ServerObjectName;
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=nTDSConnection)(objectCategory=nTDSConnection)(fromServer=CN=NTDS Settings," + serverName + "))",
new string[] { "objectClass", "cn" },
SearchScope.Subtree);
SearchResultCollection results = null;
DirectoryContext newContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context);
try
{
results = adSearcher.FindAll();
_outbound = new ReplicationConnectionCollection();
foreach (SearchResult result in results)
{
ReplicationConnection con = new ReplicationConnection(newContext, result.GetDirectoryEntry(), (string)result.Properties["cn"][0]);
_outbound.Add(con);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(newContext, e);
}
finally
{
if (results != null)
results.Dispose();
de.Dispose();
}
}
return _outbound;
}
#endregion private methods
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// This is a C# implementation of the Richards benchmark from:
//
// http://www.cl.cam.ac.uk/~mr10/Bench.html
//
// The benchmark was originally implemented in BCPL by Martin Richards.
#define INTF_FOR_TASK
using Microsoft.Xunit.Performance;
using System;
using System.Collections.Generic;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
// using System.Diagnostics;
// using System.Text.RegularExpressions;
namespace Richards
{
/// <summary>
/// Support is used for a place to generate any 'miscellaneous' methods generated as part
/// of code generation, (which do not have user-visible names)
/// </summary>
public class Support
{
public static bool runRichards()
{
Scheduler scheduler = new Scheduler();
scheduler.addIdleTask(ID_IDLE, 0, null, COUNT);
Packet queue = new Packet(null, ID_WORKER, KIND_WORK);
queue = new Packet(queue, ID_WORKER, KIND_WORK);
scheduler.addWorkerTask(ID_WORKER, 1000, queue);
queue = new Packet(null, ID_DEVICE_A, KIND_DEVICE);
queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE);
queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE);
scheduler.addHandlerTask(ID_HANDLER_A, 2000, queue);
queue = new Packet(null, ID_DEVICE_B, KIND_DEVICE);
queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE);
queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE);
scheduler.addHandlerTask(ID_HANDLER_B, 3000, queue);
scheduler.addDeviceTask(ID_DEVICE_A, 4000, null);
scheduler.addDeviceTask(ID_DEVICE_B, 5000, null);
scheduler.schedule();
return ((scheduler.queueCount == EXPECTED_QUEUE_COUNT)
&& (scheduler.holdCount == EXPECTED_HOLD_COUNT));
}
public const int COUNT = 1000;
/**
* These two constants specify how many times a packet is queued and
* how many times a task is put on hold in a correct run of richards.
* They don't have any meaning a such but are characteristic of a
* correct run so if the actual queue or hold count is different from
* the expected there must be a bug in the implementation.
**/
public const int EXPECTED_QUEUE_COUNT = 2322;
public const int EXPECTED_HOLD_COUNT = 928;
public const int ID_IDLE = 0;
public const int ID_WORKER = 1;
public const int ID_HANDLER_A = 2;
public const int ID_HANDLER_B = 3;
public const int ID_DEVICE_A = 4;
public const int ID_DEVICE_B = 5;
public const int NUMBER_OF_IDS = 6;
public const int KIND_DEVICE = 0;
public const int KIND_WORK = 1;
/**
* The task is running and is currently scheduled.
*/
public const int STATE_RUNNING = 0;
/**
* The task has packets left to process.
*/
public const int STATE_RUNNABLE = 1;
/**
* The task is not currently running. The task is not blocked as such and may
* be started by the scheduler.
*/
public const int STATE_SUSPENDED = 2;
/**
* The task is blocked and cannot be run until it is explicitly released.
*/
public const int STATE_HELD = 4;
public const int STATE_SUSPENDED_RUNNABLE = STATE_SUSPENDED | STATE_RUNNABLE;
public const int STATE_NOT_HELD = ~STATE_HELD;
/* --- *
* P a c k e t
* --- */
public const int DATA_SIZE = 4;
public static int Main(String[] args)
{
int n = 1;
if (args.Length > 0)
{
n = Int32.Parse(args[0]);
}
bool result = Measure(n);
return (result ? 100 : -1);
}
public static bool Measure(int n)
{
DateTime start = DateTime.Now;
bool result = true;
for (int i = 0; i < n; i++)
{
result &= runRichards();
}
DateTime end = DateTime.Now;
TimeSpan dur = end - start;
Console.WriteLine("Doing {0} iters of Richards takes {1} ms; {2} us/iter.",
n, dur.TotalMilliseconds, (1000.0 * dur.TotalMilliseconds) / n);
return result;
}
[Benchmark]
public static void Bench()
{
const int Iterations = 5000;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
runRichards();
}
}
}
}
}
internal class Scheduler
{
public int queueCount;
public int holdCount;
public TaskControlBlock[] blocks;
public TaskControlBlock list;
public TaskControlBlock currentTcb;
public int currentId;
public Scheduler()
{
this.queueCount = 0;
this.holdCount = 0;
this.blocks = new TaskControlBlock[Support.NUMBER_OF_IDS];
this.list = null;
this.currentTcb = null;
this.currentId = 0;
}
/**
* Add an idle task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
* @param {int} count the number of times to schedule the task
*/
public void addIdleTask(int id, int priority, Packet queue, int count)
{
this.addRunningTask(id, priority, queue,
new IdleTask(this, 1, count));
}
/**
* Add a work task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
*/
public void addWorkerTask(int id, int priority, Packet queue)
{
this.addTask(id, priority, queue,
new WorkerTask(this, Support.ID_HANDLER_A, 0));
}
/**
* Add a handler task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
*/
public void addHandlerTask(int id, int priority, Packet queue)
{
this.addTask(id, priority, queue, new HandlerTask(this));
}
/**
* Add a handler task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
*/
public void addDeviceTask(int id, int priority, Packet queue)
{
this.addTask(id, priority, queue, new DeviceTask(this));
}
/**
* Add the specified task and mark it as running.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
* @param {Task} task the task to add
*/
public void addRunningTask(int id, int priority, Packet queue, Task task)
{
this.addTask(id, priority, queue, task);
this.currentTcb.setRunning();
}
/**
* Add the specified task to this scheduler.
* @param {int} id the identity of the task
* @param {int} priority the task's priority
* @param {Packet} queue the queue of work to be processed by the task
* @param {Task} task the task to add
*/
public void addTask(int id, int priority, Packet queue, Task task)
{
this.currentTcb = new TaskControlBlock(this.list, id, priority, queue, task);
this.list = this.currentTcb;
this.blocks[id] = this.currentTcb;
}
/**
* Execute the tasks managed by this scheduler.
*/
public void schedule()
{
this.currentTcb = this.list;
#if TRACEIT
int kkk = 0;
#endif
while (this.currentTcb != null)
{
#if TRACEIT
Console.WriteLine("kkk = {0}", kkk); kkk++;
#endif
if (this.currentTcb.isHeldOrSuspended())
{
#if TRACEIT
Console.WriteLine("held");
#endif
this.currentTcb = this.currentTcb.link;
}
else
{
this.currentId = this.currentTcb.id;
#if TRACEIT
Console.WriteLine("currentId is now...{0}", this.currentId.ToString());
#endif
this.currentTcb = this.currentTcb.run();
}
}
}
/**
* Release a task that is currently blocked and return the next block to run.
* @param {int} id the id of the task to suspend
*/
public TaskControlBlock release(int id)
{
TaskControlBlock tcb = this.blocks[id];
if (tcb == null) return tcb;
tcb.markAsNotHeld();
if (tcb.priority >= this.currentTcb.priority)
{
return tcb;
}
else
{
return this.currentTcb;
}
}
/**
* Block the currently executing task and return the next task control block
* to run. The blocked task will not be made runnable until it is explicitly
* released, even if new work is added to it.
*/
public TaskControlBlock holdCurrent()
{
this.holdCount++;
this.currentTcb.markAsHeld();
return this.currentTcb.link;
}
/**
* Suspend the currently executing task and return the next task control block
* to run. If new work is added to the suspended task it will be made runnable.
*/
public TaskControlBlock suspendCurrent()
{
this.currentTcb.markAsSuspended();
return this.currentTcb;
}
/**
* Add the specified packet to the end of the worklist used by the task
* associated with the packet and make the task runnable if it is currently
* suspended.
* @param {Packet} packet the packet to add
*/
public TaskControlBlock queue(Packet packet)
{
TaskControlBlock t = this.blocks[packet.id];
if (t == null) return t;
this.queueCount++;
packet.link = null;
packet.id = this.currentId;
return t.checkPriorityAdd(this.currentTcb, packet);
}
}
/**
* A task control block manages a task and the queue of work packages associated
* with it.
* @param {TaskControlBlock} link the preceding block in the linked block list
* @param {int} id the id of this block
* @param {int} priority the priority of this block
* @param {Packet} queue the queue of packages to be processed by the task
* @param {Task} task the task
* @constructor
*/
public class TaskControlBlock
{
public TaskControlBlock link;
public int id;
public int priority;
public Packet queue;
public Task task;
public int state;
public TaskControlBlock(TaskControlBlock link, int id, int priority,
Packet queue, Task task)
{
this.link = link;
this.id = id;
this.priority = priority;
this.queue = queue;
this.task = task;
if (queue == null)
{
this.state = Support.STATE_SUSPENDED;
}
else
{
this.state = Support.STATE_SUSPENDED_RUNNABLE;
}
}
public void setRunning()
{
this.state = Support.STATE_RUNNING;
}
public void markAsNotHeld()
{
this.state = this.state & Support.STATE_NOT_HELD;
}
public void markAsHeld()
{
this.state = this.state | Support.STATE_HELD;
}
public bool isHeldOrSuspended()
{
return ((this.state & Support.STATE_HELD) != 0) || (this.state == Support.STATE_SUSPENDED);
}
public void markAsSuspended()
{
this.state = this.state | Support.STATE_SUSPENDED;
}
public void markAsRunnable()
{
this.state = this.state | Support.STATE_RUNNABLE;
}
/**
* Runs this task, if it is ready to be run, and returns the next task to run.
*/
public TaskControlBlock run()
{
Packet packet;
#if TRACEIT
Console.WriteLine(" TCB::run, state = {0}", this.state);
#endif
if (this.state == Support.STATE_SUSPENDED_RUNNABLE)
{
packet = this.queue;
this.queue = packet.link;
if (this.queue == null)
{
this.state = Support.STATE_RUNNING;
}
else
{
this.state = Support.STATE_RUNNABLE;
}
#if TRACEIT
Console.WriteLine(" State is now {0}", this.state);
#endif
}
else
{
#if TRACEIT
Console.WriteLine(" TCB::run, setting packet = Null.");
#endif
packet = null;
}
return this.task.run(packet);
}
/**
* Adds a packet to the worklist of this block's task, marks this as runnable if
* necessary, and returns the next runnable object to run (the one
* with the highest priority).
*/
public TaskControlBlock checkPriorityAdd(TaskControlBlock task, Packet packet)
{
if (this.queue == null)
{
this.queue = packet;
this.markAsRunnable();
if (this.priority >= task.priority) return this;
}
else
{
this.queue = packet.addTo(this.queue);
}
return task;
}
public String toString()
{
return "tcb { " + this.task.toString() + "@" + this.state.ToString() + " }";
}
}
#if INTF_FOR_TASK
// I deliberately ignore the "I" prefix convention here so that we can use Task as a type in both
// cases...
public interface Task
{
TaskControlBlock run(Packet packet);
String toString();
}
#else
public abstract class Task
{
public abstract TaskControlBlock run(Packet packet);
public abstract String toString();
}
#endif
/**
* An idle task doesn't do any work itself but cycles control between the two
* device tasks.
* @param {Scheduler} scheduler the scheduler that manages this task
* @param {int} v1 a seed value that controls how the device tasks are scheduled
* @param {int} count the number of times this task should be scheduled
* @constructor
*/
internal class IdleTask : Task
{
public Scheduler scheduler;
public int _v1;
public int _count;
public IdleTask(Scheduler scheduler, int v1, int count)
{
this.scheduler = scheduler;
this._v1 = v1;
this._count = count;
}
public
#if !INTF_FOR_TASK
override
#endif
TaskControlBlock run(Packet packet)
{
this._count--;
if (this._count == 0) return this.scheduler.holdCurrent();
if ((this._v1 & 1) == 0)
{
this._v1 = this._v1 >> 1;
return this.scheduler.release(Support.ID_DEVICE_A);
}
else
{
this._v1 = (this._v1 >> 1) ^ 0xD008;
return this.scheduler.release(Support.ID_DEVICE_B);
}
}
public
#if !INTF_FOR_TASK
override
#endif
String toString()
{
return "IdleTask";
}
}
/**
* A task that suspends itself after each time it has been run to simulate
* waiting for data from an external device.
* @param {Scheduler} scheduler the scheduler that manages this task
* @constructor
*/
internal class DeviceTask : Task
{
public Scheduler scheduler;
private Packet _v1;
public DeviceTask(Scheduler scheduler)
{
this.scheduler = scheduler;
_v1 = null;
}
public
#if !INTF_FOR_TASK
override
#endif
TaskControlBlock run(Packet packet)
{
if (packet == null)
{
if (_v1 == null) return this.scheduler.suspendCurrent();
Packet v = _v1;
_v1 = null;
return this.scheduler.queue(v);
}
else
{
_v1 = packet;
return this.scheduler.holdCurrent();
}
}
public
#if !INTF_FOR_TASK
override
#endif
String toString()
{
return "DeviceTask";
}
}
/**
* A task that manipulates work packets.
* @param {Scheduler} scheduler the scheduler that manages this task
* @param {int} v1 a seed used to specify how work packets are manipulated
* @param {int} v2 another seed used to specify how work packets are manipulated
* @constructor
*/
internal class WorkerTask : Task
{
public Scheduler scheduler;
public int v1;
public int _v2;
public WorkerTask(Scheduler scheduler, int v1, int v2)
{
this.scheduler = scheduler;
this.v1 = v1;
this._v2 = v2;
}
public
#if !INTF_FOR_TASK
override
#endif
TaskControlBlock run(Packet packet)
{
if (packet == null)
{
return this.scheduler.suspendCurrent();
}
else
{
if (this.v1 == Support.ID_HANDLER_A)
{
this.v1 = Support.ID_HANDLER_B;
}
else
{
this.v1 = Support.ID_HANDLER_A;
}
packet.id = this.v1;
packet.a1 = 0;
for (int i = 0; i < Support.DATA_SIZE; i++)
{
this._v2++;
if (this._v2 > 26) this._v2 = 1;
packet.a2[i] = this._v2;
}
return this.scheduler.queue(packet);
}
}
public
#if !INTF_FOR_TASK
override
#endif
String toString()
{
return "WorkerTask";
}
}
/**
* A task that manipulates work packets and then suspends itself.
* @param {Scheduler} scheduler the scheduler that manages this task
* @constructor
*/
internal class HandlerTask : Task
{
public Scheduler scheduler;
public Packet v1;
public Packet v2;
public HandlerTask(Scheduler scheduler)
{
this.scheduler = scheduler;
this.v1 = null;
this.v2 = null;
}
public
#if !INTF_FOR_TASK
override
#endif
TaskControlBlock run(Packet packet)
{
if (packet != null)
{
if (packet.kind == Support.KIND_WORK)
{
this.v1 = packet.addTo(this.v1);
}
else
{
this.v2 = packet.addTo(this.v2);
}
}
if (this.v1 != null)
{
int count = this.v1.a1;
Packet v;
if (count < Support.DATA_SIZE)
{
if (this.v2 != null)
{
v = this.v2;
this.v2 = this.v2.link;
v.a1 = this.v1.a2[count];
this.v1.a1 = count + 1;
return this.scheduler.queue(v);
}
}
else
{
v = this.v1;
this.v1 = this.v1.link;
return this.scheduler.queue(v);
}
}
return this.scheduler.suspendCurrent();
}
public
#if !INTF_FOR_TASK
override
#endif
String toString()
{
return "HandlerTask";
}
}
/**
* A simple package of data that is manipulated by the tasks. The exact layout
* of the payload data carried by a packet is not importaint, and neither is the
* nature of the work performed on packets by the tasks.
*
* Besides carrying data, packets form linked lists and are hence used both as
* data and worklists.
* @param {Packet} link the tail of the linked list of packets
* @param {int} id an ID for this packet
* @param {int} kind the type of this packet
* @constructor
*/
public class Packet
{
public Packet link;
public int id;
public int kind;
public int a1;
public int[] a2;
public Packet(Packet link, int id, int kind)
{
this.link = link;
this.id = id;
this.kind = kind;
this.a1 = 0;
this.a2 = new int[Support.DATA_SIZE];
}
public Packet addTo(Packet queue)
{
this.link = null;
if (queue == null) return this;
Packet peek;
Packet next = queue;
while ((peek = next.link) != null)
next = peek;
next.link = this;
return queue;
}
public String toString()
{
return "Packet";
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace PSLLunch.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
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);
}
}
}
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using BitCoinSharp.IO;
namespace BitCoinSharp
{
/// <summary>
/// A transaction represents the movement of coins from some addresses to some other addresses. It can also represent
/// the minting of new coins. A Transaction object corresponds to the equivalent in the BitCoin C++ implementation.
/// </summary>
/// <remarks>
/// It implements TWO serialization protocols - the BitCoin proprietary format which is identical to the C++
/// implementation and is used for reading/writing transactions to the wire and for hashing. It also implements Java
/// serialization which is used for the wallet. This allows us to easily add extra fields used for our own accounting
/// or UI purposes.
/// </remarks>
[Serializable]
public class Transaction : Message
{
// These are serialized in both BitCoin and java serialization.
private uint _version;
private List<TransactionInput> _inputs;
private List<TransactionOutput> _outputs;
private uint _lockTime;
// This is an in memory helper only.
[NonSerialized] private Sha256Hash _hash;
internal Transaction(NetworkParameters @params)
: base(@params)
{
_version = 1;
_inputs = new List<TransactionInput>();
_outputs = new List<TransactionOutput>();
// We don't initialize appearsIn deliberately as it's only useful for transactions stored in the wallet.
}
/// <summary>
/// Creates a transaction from the given serialized bytes, eg, from a block or a tx network message.
/// </summary>
/// <exception cref="ProtocolException"/>
public Transaction(NetworkParameters @params, byte[] payloadBytes)
: base(@params, payloadBytes, 0)
{
}
/// <summary>
/// Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed.
/// </summary>
/// <exception cref="ProtocolException"/>
public Transaction(NetworkParameters @params, byte[] payload, int offset)
: base(@params, payload, offset)
{
// inputs/outputs will be created in parse()
}
/// <summary>
/// Returns a read-only list of the inputs of this transaction.
/// </summary>
public IList<TransactionInput> Inputs
{
get { return _inputs.AsReadOnly(); }
}
/// <summary>
/// Returns a read-only list of the outputs of this transaction.
/// </summary>
public IList<TransactionOutput> Outputs
{
get { return _outputs.AsReadOnly(); }
}
/// <summary>
/// Returns the transaction hash as you see them in the block explorer.
/// </summary>
public Sha256Hash Hash
{
get { return _hash ?? (_hash = new Sha256Hash(Utils.ReverseBytes(Utils.DoubleDigest(BitcoinSerialize())))); }
}
public string HashAsString
{
get { return Hash.ToString(); }
}
/// <summary>
/// Calculates the sum of the outputs that are sending coins to a key in the wallet. The flag controls whether to
/// include spent outputs or not.
/// </summary>
internal ulong GetValueSentToMe(Wallet wallet, bool includeSpent)
{
// This is tested in WalletTest.
var v = 0UL;
foreach (var o in _outputs)
{
if (!o.IsMine(wallet)) continue;
if (!includeSpent && !o.IsAvailableForSpending) continue;
v += o.Value;
}
return v;
}
/// <summary>
/// Calculates the sum of the outputs that are sending coins to a key in the wallet.
/// </summary>
public ulong GetValueSentToMe(Wallet wallet)
{
return GetValueSentToMe(wallet, true);
}
/// <summary>
/// Returns a set of blocks which contain the transaction, or null if this transaction doesn't have that data
/// because it's not stored in the wallet or because it has never appeared in a block.
/// </summary>
internal ICollection<StoredBlock> AppearsIn { get; private set; }
/// <summary>
/// Adds the given block to the internal serializable set of blocks in which this transaction appears. This is
/// used by the wallet to ensure transactions that appear on side chains are recorded properly even though the
/// block stores do not save the transaction data at all.
/// </summary>
internal void AddBlockAppearance(StoredBlock block)
{
if (AppearsIn == null)
{
AppearsIn = new HashSet<StoredBlock>();
}
AppearsIn.Add(block);
}
/// <summary>
/// Calculates the sum of the inputs that are spending coins with keys in the wallet. This requires the
/// transactions sending coins to those keys to be in the wallet. This method will not attempt to download the
/// blocks containing the input transactions if the key is in the wallet but the transactions are not.
/// </summary>
/// <returns>Sum in nanocoins.</returns>
/// <exception cref="ScriptException"/>
public ulong GetValueSentFromMe(Wallet wallet)
{
// This is tested in WalletTest.
var v = 0UL;
foreach (var input in _inputs)
{
// This input is taking value from an transaction in our wallet. To discover the value,
// we must find the connected transaction.
var connected = input.GetConnectedOutput(wallet.Unspent);
if (connected == null)
connected = input.GetConnectedOutput(wallet.Spent);
if (connected == null)
connected = input.GetConnectedOutput(wallet.Pending);
if (connected == null)
continue;
// The connected output may be the change to the sender of a previous input sent to this wallet. In this
// case we ignore it.
if (!connected.IsMine(wallet))
continue;
v += connected.Value;
}
return v;
}
internal bool DisconnectInputs()
{
var disconnected = false;
foreach (var input in _inputs)
{
disconnected |= input.Disconnect();
}
return disconnected;
}
/// <summary>
/// Connects all inputs using the provided transactions. If any input cannot be connected returns that input or
/// null on success.
/// </summary>
internal TransactionInput ConnectForReorganize(IDictionary<Sha256Hash, Transaction> transactions)
{
foreach (var input in _inputs)
{
// Coinbase transactions, by definition, do not have connectable inputs.
if (input.IsCoinBase) continue;
var result = input.Connect(transactions, false);
// Connected to another tx in the wallet?
if (result == TransactionInput.ConnectionResult.Success)
continue;
// The input doesn't exist in the wallet, eg because it belongs to somebody else (inbound spend).
if (result == TransactionInput.ConnectionResult.NoSuchTx)
continue;
// Could not connect this input, so return it and abort.
return input;
}
return null;
}
/// <returns>true if every output is marked as spent.</returns>
public bool IsEveryOutputSpent()
{
foreach (var output in _outputs)
{
if (output.IsAvailableForSpending)
return false;
}
return true;
}
/// <summary>
/// These constants are a part of a scriptSig signature on the inputs. They define the details of how a
/// transaction can be redeemed, specifically, they control how the hash of the transaction is calculated.
/// </summary>
/// <remarks>
/// In the official client, this enum also has another flag, SIGHASH_ANYONECANPAY. In this implementation,
/// that's kept separate. Only SIGHASH_ALL is actually used in the official client today. The other flags
/// exist to allow for distributed contracts.
/// </remarks>
public enum SigHash
{
All, // 1
None, // 2
Single, // 3
}
/// <exception cref="ProtocolException"/>
protected override void Parse()
{
_version = ReadUint32();
// First come the inputs.
var numInputs = ReadVarInt();
_inputs = new List<TransactionInput>((int) numInputs);
for (var i = 0UL; i < numInputs; i++)
{
var input = new TransactionInput(Params, this, Bytes, Cursor);
_inputs.Add(input);
Cursor += input.MessageSize;
}
// Now the outputs
var numOutputs = ReadVarInt();
_outputs = new List<TransactionOutput>((int) numOutputs);
for (var i = 0UL; i < numOutputs; i++)
{
var output = new TransactionOutput(Params, this, Bytes, Cursor);
_outputs.Add(output);
Cursor += output.MessageSize;
}
_lockTime = ReadUint32();
}
/// <summary>
/// A coinbase transaction is one that creates a new coin. They are the first transaction in each block and their
/// value is determined by a formula that all implementations of BitCoin share. In 2011 the value of a coinbase
/// transaction is 50 coins, but in future it will be less. A coinbase transaction is defined not only by its
/// position in a block but by the data in the inputs.
/// </summary>
public bool IsCoinBase
{
get { return _inputs[0].IsCoinBase; }
}
/// <returns>A human readable version of the transaction useful for debugging.</returns>
public override string ToString()
{
var s = new StringBuilder();
s.Append(" ");
s.Append(HashAsString);
s.AppendLine();
if (IsCoinBase)
{
string script;
string script2;
try
{
script = _inputs[0].ScriptSig.ToString();
script2 = _outputs[0].ScriptPubKey.ToString();
}
catch (ScriptException)
{
script = "???";
script2 = "???";
}
return " == COINBASE TXN (scriptSig " + script + ") (scriptPubKey " + script2 + ")";
}
foreach (var @in in _inputs)
{
s.Append(" ");
s.Append("from ");
try
{
s.Append(@in.ScriptSig.FromAddress.ToString());
}
catch (Exception e)
{
s.Append("[exception: ").Append(e.Message).Append("]");
throw;
}
s.AppendLine();
}
foreach (var @out in _outputs)
{
s.Append(" ");
s.Append("to ");
try
{
var toAddr = new Address(Params, @out.ScriptPubKey.PubKeyHash);
s.Append(toAddr.ToString());
s.Append(" ");
s.Append(Utils.BitcoinValueToFriendlyString(@out.Value));
s.Append(" BTC");
}
catch (Exception e)
{
s.Append("[exception: ").Append(e.Message).Append("]");
}
s.AppendLine();
}
return s.ToString();
}
/// <summary>
/// Adds an input to this transaction that imports value from the given output. Note that this input is NOT
/// complete and after every input is added with addInput() and every output is added with addOutput(),
/// signInputs() must be called to finalize the transaction and finish the inputs off. Otherwise it won't be
/// accepted by the network.
/// </summary>
public void AddInput(TransactionOutput from)
{
AddInput(new TransactionInput(Params, this, from));
}
/// <summary>
/// Adds an input directly, with no checking that it's valid.
/// </summary>
public void AddInput(TransactionInput input)
{
_inputs.Add(input);
}
/// <summary>
/// Adds the given output to this transaction. The output must be completely initialized.
/// </summary>
public void AddOutput(TransactionOutput to)
{
to.ParentTransaction = this;
_outputs.Add(to);
}
/// <summary>
/// Once a transaction has some inputs and outputs added, the signatures in the inputs can be calculated. The
/// signature is over the transaction itself, to prove the redeemer actually created that transaction,
/// so we have to do this step last.
/// </summary>
/// <remarks>
/// This method is similar to SignatureHash in script.cpp
/// </remarks>
/// <param name="hashType">This should always be set to SigHash.ALL currently. Other types are unused. </param>
/// <param name="wallet">A wallet is required to fetch the keys needed for signing.</param>
/// <exception cref="ScriptException"/>
public void SignInputs(SigHash hashType, Wallet wallet)
{
Debug.Assert(_inputs.Count > 0);
Debug.Assert(_outputs.Count > 0);
// I don't currently have an easy way to test other modes work, as the official client does not use them.
Debug.Assert(hashType == SigHash.All);
// The transaction is signed with the input scripts empty except for the input we are signing. In the case
// where addInput has been used to set up a new transaction, they are already all empty. The input being signed
// has to have the connected OUTPUT program in it when the hash is calculated!
//
// Note that each input may be claiming an output sent to a different key. So we have to look at the outputs
// to figure out which key to sign with.
var signatures = new byte[_inputs.Count][];
var signingKeys = new EcKey[_inputs.Count];
for (var i = 0; i < _inputs.Count; i++)
{
var input = _inputs[i];
Debug.Assert(input.ScriptBytes.Length == 0, "Attempting to sign a non-fresh transaction");
// Set the input to the script of its output.
input.ScriptBytes = input.Outpoint.ConnectedPubKeyScript;
// Find the signing key we'll need to use.
var connectedPubKeyHash = input.Outpoint.ConnectedPubKeyHash;
var key = wallet.FindKeyFromPubHash(connectedPubKeyHash);
// This assert should never fire. If it does, it means the wallet is inconsistent.
Debug.Assert(key != null, "Transaction exists in wallet that we cannot redeem: " + Utils.BytesToHexString(connectedPubKeyHash));
// Keep the key around for the script creation step below.
signingKeys[i] = key;
// The anyoneCanPay feature isn't used at the moment.
const bool anyoneCanPay = false;
var hash = HashTransactionForSignature(hashType, anyoneCanPay);
// Set the script to empty again for the next input.
input.ScriptBytes = TransactionInput.EmptyArray;
// Now sign for the output so we can redeem it. We use the keypair to sign the hash,
// and then put the resulting signature in the script along with the public key (below).
using (var bos = new MemoryStream())
{
bos.Write(key.Sign(hash));
bos.Write((byte) (((int) hashType + 1) | (anyoneCanPay ? 0x80 : 0)));
signatures[i] = bos.ToArray();
}
}
// Now we have calculated each signature, go through and create the scripts. Reminder: the script consists of
// a signature (over a hash of the transaction) and the complete public key needed to sign for the connected
// output.
for (var i = 0; i < _inputs.Count; i++)
{
var input = _inputs[i];
Debug.Assert(input.ScriptBytes.Length == 0);
var key = signingKeys[i];
input.ScriptBytes = Script.CreateInputScript(signatures[i], key.PubKey);
}
// Every input is now complete.
}
private byte[] HashTransactionForSignature(SigHash type, bool anyoneCanPay)
{
using (var bos = new MemoryStream())
{
BitcoinSerializeToStream(bos);
// We also have to write a hash type.
var hashType = (uint) type + 1;
if (anyoneCanPay)
hashType |= 0x80;
Utils.Uint32ToByteStreamLe(hashType, bos);
// Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out
// however then we would expect that it is IS reversed.
return Utils.DoubleDigest(bos.ToArray());
}
}
/// <exception cref="IOException"/>
public override void BitcoinSerializeToStream(Stream stream)
{
Utils.Uint32ToByteStreamLe(_version, stream);
stream.Write(new VarInt((ulong) _inputs.Count).Encode());
foreach (var @in in _inputs)
@in.BitcoinSerializeToStream(stream);
stream.Write(new VarInt((ulong) _outputs.Count).Encode());
foreach (var @out in _outputs)
@out.BitcoinSerializeToStream(stream);
Utils.Uint32ToByteStreamLe(_lockTime, stream);
}
public override bool Equals(object other)
{
if (!(other is Transaction)) return false;
var t = (Transaction) other;
return t.Hash.Equals(Hash);
}
public override int GetHashCode()
{
return Hash.GetHashCode();
}
}
}
| |
/***************************************************************************\
*
* File: Setter.cs
*
* TargetType property setting class.
*
* Copyright (C) 2004 by Microsoft Corporation. All rights reserved.
*
\***************************************************************************/
using System;
using System.ComponentModel;
using System.Windows.Markup;
using System.Windows.Data;
using System.Globalization;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace System.Windows
{
/// <summary>
/// TargetType property setting class.
/// </summary>
[XamlSetMarkupExtensionAttribute("ReceiveMarkupExtension")]
[XamlSetTypeConverterAttribute("ReceiveTypeConverter")]
public class Setter : SetterBase, ISupportInitialize
{
/// <summary>
/// Property Setter construction - set everything to null or DependencyProperty.UnsetValue
/// </summary>
public Setter()
{
}
/// <summary>
/// Property Setter construction - given property and value
/// </summary>
public Setter( DependencyProperty property, object value )
{
Initialize( property, value, null );
}
/// <summary>
/// Property Setter construction - given property, value, and string identifier for child node.
/// </summary>
public Setter( DependencyProperty property, object value, string targetName )
{
Initialize( property, value, targetName );
}
/// <summary>
/// Method that does all the initialization work for the constructors.
/// </summary>
private void Initialize( DependencyProperty property, object value, string target )
{
if( value == DependencyProperty.UnsetValue )
{
throw new ArgumentException(SR.Get(SRID.SetterValueCannotBeUnset));
}
CheckValidProperty(property);
// No null check for target since null is a valid value.
_property = property;
_value = value;
_target = target;
}
private void CheckValidProperty( DependencyProperty property)
{
if (property == null)
{
throw new ArgumentNullException("property");
}
if (property.ReadOnly)
{
// Read-only properties will not be consulting Style/Template/Trigger Setter for value.
// Rather than silently do nothing, throw error.
throw new ArgumentException(SR.Get(SRID.ReadOnlyPropertyNotAllowed, property.Name, GetType().Name));
}
if( property == FrameworkElement.NameProperty)
{
throw new InvalidOperationException(SR.Get(SRID.CannotHavePropertyInStyle, FrameworkElement.NameProperty.Name));
}
}
/// <summary>
/// Seals this setter
/// </summary>
internal override void Seal()
{
// Do the validation that can't be done until we know all of the property
// values.
DependencyProperty dp = Property;
object value = ValueInternal;
if (dp == null)
{
throw new ArgumentException(SR.Get(SRID.NullPropertyIllegal, "Setter.Property"));
}
if( String.IsNullOrEmpty(TargetName))
{
// Setter on container is not allowed to affect the StyleProperty.
if (dp == FrameworkElement.StyleProperty)
{
throw new ArgumentException(SR.Get(SRID.StylePropertyInStyleNotAllowed));
}
}
// Value needs to be valid for the DP, or a deferred reference, or one of the supported
// markup extensions.
if (!dp.IsValidValue(value))
{
// The only markup extensions supported by styles is resources and bindings.
if (value is MarkupExtension)
{
if ( !(value is DynamicResourceExtension) && !(value is System.Windows.Data.BindingBase) )
{
throw new ArgumentException(SR.Get(SRID.SetterValueOfMarkupExtensionNotSupported,
value.GetType().Name));
}
}
else if (!(value is DeferredReference))
{
throw new ArgumentException(SR.Get(SRID.InvalidSetterValue, value, dp.OwnerType, dp.Name));
}
}
// Freeze the value for the setter
StyleHelper.SealIfSealable(_value);
base.Seal();
}
/// <summary>
/// Property that is being set by this setter
/// </summary>
[Ambient]
[DefaultValue(null)]
[Localizability(LocalizationCategory.None, Modifiability = Modifiability.Unmodifiable, Readability = Readability.Unreadable)] // Not localizable by-default
public DependencyProperty Property
{
get { return _property; }
set
{
CheckValidProperty(value);
CheckSealed();
_property = value;
}
}
/// <summary>
/// Property value that is being set by this setter
/// </summary>
[System.Windows.Markup.DependsOn("Property")]
[System.Windows.Markup.DependsOn("TargetName")]
[Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)] // Not localizable by-default
[TypeConverter(typeof(System.Windows.Markup.SetterTriggerConditionValueConverter))]
public object Value
{
get
{
// Inflate the deferred reference if the _value is one of those.
DeferredReference deferredReference = _value as DeferredReference;
if (deferredReference != null)
{
_value = deferredReference.GetValue(BaseValueSourceInternal.Unknown);
}
return _value;
}
set
{
if( value == DependencyProperty.UnsetValue )
{
throw new ArgumentException(SR.Get(SRID.SetterValueCannotBeUnset));
}
CheckSealed();
// No Expression support
if( value is Expression )
{
throw new ArgumentException(SR.Get(SRID.StyleValueOfExpressionNotSupported));
}
_value = value;
}
}
/// <summary>
/// Internal property used so that we obtain the value as
/// is without having to inflate the DeferredReference.
/// </summary>
internal object ValueInternal
{
get { return _value; }
}
/// <summary>
/// When the set is directed at a child node, this string
/// identifies the intended target child node.
/// </summary>
[DefaultValue(null)]
[Ambient]
public string TargetName
{
get
{
return _target;
}
set
{
// Setting to null is allowed, to clear out value.
CheckSealed();
_target = value;
}
}
public static void ReceiveMarkupExtension(object targetObject, XamlSetMarkupExtensionEventArgs eventArgs)
{
if (targetObject == null)
{
throw new ArgumentNullException("targetObject");
}
if (eventArgs == null)
{
throw new ArgumentNullException("eventArgs");
}
Setter setter = targetObject as Setter;
if (setter == null || eventArgs.Member.Name != "Value")
{
return;
}
MarkupExtension me = eventArgs.MarkupExtension;
if (me is StaticResourceExtension)
{
var sr = me as StaticResourceExtension;
setter.Value = sr.ProvideValueInternal(eventArgs.ServiceProvider, true /*allowDeferedReference*/);
eventArgs.Handled = true;
}
else if (me is DynamicResourceExtension || me is BindingBase)
{
setter.Value = me;
eventArgs.Handled = true;
}
}
public static void ReceiveTypeConverter(object targetObject, XamlSetTypeConverterEventArgs eventArgs)
{
Setter setter = targetObject as Setter;
if (setter == null)
{
throw new ArgumentNullException("targetObject");
}
if (eventArgs == null)
{
throw new ArgumentNullException("eventArgs");
}
if (eventArgs.Member.Name == "Property")
{
setter._unresolvedProperty = eventArgs.Value;
setter._serviceProvider = eventArgs.ServiceProvider;
setter._cultureInfoForTypeConverter = eventArgs.CultureInfo;
eventArgs.Handled = true;
}
else if (eventArgs.Member.Name == "Value")
{
setter._unresolvedValue = eventArgs.Value;
setter._serviceProvider = eventArgs.ServiceProvider;
setter._cultureInfoForTypeConverter = eventArgs.CultureInfo;
eventArgs.Handled = true;
}
}
#region ISupportInitialize Members
void ISupportInitialize.BeginInit()
{
}
void ISupportInitialize.EndInit()
{
// Resolve all properties here
if (_unresolvedProperty != null)
{
try
{
Property = DependencyPropertyConverter.ResolveProperty(_serviceProvider,
TargetName, _unresolvedProperty);
}
finally
{
_unresolvedProperty = null;
}
}
if (_unresolvedValue != null)
{
try
{
Value = SetterTriggerConditionValueConverter.ResolveValue(_serviceProvider,
Property, _cultureInfoForTypeConverter, _unresolvedValue);
}
finally
{
_unresolvedValue = null;
}
}
_serviceProvider = null;
_cultureInfoForTypeConverter = null;
}
#endregion
private DependencyProperty _property = null;
private object _value = DependencyProperty.UnsetValue;
private string _target = null;
private object _unresolvedProperty = null;
private object _unresolvedValue = null;
private ITypeDescriptorContext _serviceProvider = null;
private CultureInfo _cultureInfoForTypeConverter = null;
}
}
| |
/* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2021 the ZAP development team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
/*
* This file was automatically generated.
*/
namespace OWASPZAPDotNetAPI.Generated
{
public class AjaxSpider
{
private ClientApi api = null;
public AjaxSpider(ClientApi api)
{
this.api = api;
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse allowedResources()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "allowedResources", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse status()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "status", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse results(string start, string count)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("start", start);
parameters.Add("count", count);
return api.CallApi("ajaxSpider", "view", "results", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse numberOfResults()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "numberOfResults", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse fullResults()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "fullResults", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse optionBrowserId()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "optionBrowserId", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse optionEventWait()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "optionEventWait", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse optionMaxCrawlDepth()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "optionMaxCrawlDepth", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse optionMaxCrawlStates()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "optionMaxCrawlStates", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse optionMaxDuration()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "optionMaxDuration", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse optionNumberOfBrowsers()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "optionNumberOfBrowsers", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse optionReloadWait()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "optionReloadWait", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse optionClickDefaultElems()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "optionClickDefaultElems", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse optionClickElemsOnce()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "optionClickElemsOnce", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse optionRandomInputs()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "view", "optionRandomInputs", parameters);
}
/// <summary>
///Runs the AJAX Spider against a given target.
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse scan(string url, string inscope, string contextname, string subtreeonly)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("url", url);
parameters.Add("inScope", inscope);
parameters.Add("contextName", contextname);
parameters.Add("subtreeOnly", subtreeonly);
return api.CallApi("ajaxSpider", "action", "scan", parameters);
}
/// <summary>
///Runs the AJAX Spider from the perspective of a User of the web application.
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse scanAsUser(string contextname, string username, string url, string subtreeonly)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("contextName", contextname);
parameters.Add("userName", username);
parameters.Add("url", url);
parameters.Add("subtreeOnly", subtreeonly);
return api.CallApi("ajaxSpider", "action", "scanAsUser", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse stop()
{
Dictionary<string, string> parameters = null;
return api.CallApi("ajaxSpider", "action", "stop", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse addAllowedResource(string regex, string enabled)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("enabled", enabled);
return api.CallApi("ajaxSpider", "action", "addAllowedResource", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse removeAllowedResource(string regex)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
return api.CallApi("ajaxSpider", "action", "removeAllowedResource", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setEnabledAllowedResource(string regex, string enabled)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("regex", regex);
parameters.Add("enabled", enabled);
return api.CallApi("ajaxSpider", "action", "setEnabledAllowedResource", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setOptionBrowserId(string str)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("String", str);
return api.CallApi("ajaxSpider", "action", "setOptionBrowserId", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setOptionClickDefaultElems(bool boolean)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Boolean", Convert.ToString(boolean));
return api.CallApi("ajaxSpider", "action", "setOptionClickDefaultElems", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setOptionClickElemsOnce(bool boolean)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Boolean", Convert.ToString(boolean));
return api.CallApi("ajaxSpider", "action", "setOptionClickElemsOnce", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setOptionEventWait(int i)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Integer", Convert.ToString(i));
return api.CallApi("ajaxSpider", "action", "setOptionEventWait", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setOptionMaxCrawlDepth(int i)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Integer", Convert.ToString(i));
return api.CallApi("ajaxSpider", "action", "setOptionMaxCrawlDepth", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setOptionMaxCrawlStates(int i)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Integer", Convert.ToString(i));
return api.CallApi("ajaxSpider", "action", "setOptionMaxCrawlStates", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setOptionMaxDuration(int i)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Integer", Convert.ToString(i));
return api.CallApi("ajaxSpider", "action", "setOptionMaxDuration", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setOptionNumberOfBrowsers(int i)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Integer", Convert.ToString(i));
return api.CallApi("ajaxSpider", "action", "setOptionNumberOfBrowsers", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setOptionRandomInputs(bool boolean)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Boolean", Convert.ToString(boolean));
return api.CallApi("ajaxSpider", "action", "setOptionRandomInputs", parameters);
}
/// <summary>
///This component is optional and therefore the API will only work if it is installed
/// </summary>
/// <returns></returns>
public IApiResponse setOptionReloadWait(int i)
{
Dictionary<string, string> parameters = null;
parameters = new Dictionary<string, string>();
parameters.Add("Integer", Convert.ToString(i));
return api.CallApi("ajaxSpider", "action", "setOptionReloadWait", parameters);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
namespace Microsoft.AzureStack.Management
{
public static partial class ManagedPlanOperationsExtensions
{
/// <summary>
/// Creates or updates the plan
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='parameters'>
/// Required. Plan properties
/// </param>
/// <returns>
/// Result for the create or update operation of the plan
/// </returns>
public static ManagedPlanCreateOrUpdateResult CreateOrUpdate(this IManagedPlanOperations operations, string resourceGroupName, ManagedPlanCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates the plan
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='parameters'>
/// Required. Plan properties
/// </param>
/// <returns>
/// Result for the create or update operation of the plan
/// </returns>
public static Task<ManagedPlanCreateOrUpdateResult> CreateOrUpdateAsync(this IManagedPlanOperations operations, string resourceGroupName, ManagedPlanCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete operation on the plan
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='planId'>
/// Required. Plan name
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IManagedPlanOperations operations, string resourceGroupName, string planId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).DeleteAsync(resourceGroupName, planId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete operation on the plan
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='planId'>
/// Required. Plan name
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IManagedPlanOperations operations, string resourceGroupName, string planId)
{
return operations.DeleteAsync(resourceGroupName, planId, CancellationToken.None);
}
/// <summary>
/// Gets the administrator view of the plan
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='planId'>
/// Required. Plan name
/// </param>
/// <returns>
/// Administrator view of plan for the get operation
/// </returns>
public static ManagedPlanGetResult Get(this IManagedPlanOperations operations, string resourceGroupName, string planId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).GetAsync(resourceGroupName, planId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the administrator view of the plan
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='planId'>
/// Required. Plan name
/// </param>
/// <returns>
/// Administrator view of plan for the get operation
/// </returns>
public static Task<ManagedPlanGetResult> GetAsync(this IManagedPlanOperations operations, string resourceGroupName, string planId)
{
return operations.GetAsync(resourceGroupName, planId, CancellationToken.None);
}
/// <summary>
/// Lists all the plans under the resource group
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='includeDetails'>
/// Required. Flag to specify whether to include details
/// </param>
/// <returns>
/// Result of the plan llist operation
/// </returns>
public static ManagedPlanListResult List(this IManagedPlanOperations operations, string resourceGroupName, bool includeDetails)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).ListAsync(resourceGroupName, includeDetails);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the plans under the resource group
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='includeDetails'>
/// Required. Flag to specify whether to include details
/// </param>
/// <returns>
/// Result of the plan llist operation
/// </returns>
public static Task<ManagedPlanListResult> ListAsync(this IManagedPlanOperations operations, string resourceGroupName, bool includeDetails)
{
return operations.ListAsync(resourceGroupName, includeDetails, CancellationToken.None);
}
}
}
| |
// 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.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// Provides the underlying stream of data for network access.
public class NetworkStream : Stream
{
// Used by the class to hold the underlying socket the stream uses.
private readonly Socket _streamSocket;
// Whether the stream should dispose of the socket when the stream is disposed
private readonly bool _ownsSocket;
// Used by the class to indicate that the stream is m_Readable.
private bool _readable;
// Used by the class to indicate that the stream is writable.
private bool _writeable;
// Creates a new instance of the System.Net.Sockets.NetworkStream class for the specified System.Net.Sockets.Socket.
public NetworkStream(Socket socket)
: this(socket, FileAccess.ReadWrite, ownsSocket: false)
{
}
public NetworkStream(Socket socket, bool ownsSocket)
: this(socket, FileAccess.ReadWrite, ownsSocket)
{
}
public NetworkStream(Socket socket, FileAccess access)
: this(socket, access, ownsSocket: false)
{
}
public NetworkStream(Socket socket, FileAccess access, bool ownsSocket)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
if (socket == null)
{
throw new ArgumentNullException(nameof(socket));
}
if (!socket.Blocking)
{
throw new IOException(SR.net_sockets_blocking);
}
if (!socket.Connected)
{
throw new IOException(SR.net_notconnected);
}
if (socket.SocketType != SocketType.Stream)
{
throw new IOException(SR.net_notstream);
}
_streamSocket = socket;
_ownsSocket = ownsSocket;
switch (access)
{
case FileAccess.Read:
_readable = true;
break;
case FileAccess.Write:
_writeable = true;
break;
case FileAccess.ReadWrite:
default: // assume FileAccess.ReadWrite
_readable = true;
_writeable = true;
break;
}
#if DEBUG
}
#endif
}
// Socket - provides access to socket for stream closing
protected Socket Socket => _streamSocket;
// Used by the class to indicate that the stream is m_Readable.
protected bool Readable
{
get { return _readable; }
set { _readable = value; }
}
// Used by the class to indicate that the stream is writable.
protected bool Writeable
{
get { return _writeable; }
set { _writeable = value; }
}
// Indicates that data can be read from the stream.
// We return the readability of this stream. This is a read only property.
public override bool CanRead => _readable;
// Indicates that the stream can seek a specific location
// in the stream. This property always returns false.
public override bool CanSeek => false;
// Indicates that data can be written to the stream.
public override bool CanWrite => _writeable;
// Indicates whether we can timeout
public override bool CanTimeout => true;
// Set/Get ReadTimeout, note of a strange behavior, 0 timeout == infinite for sockets,
// so we map this to -1, and if you set 0, we cannot support it
public override int ReadTimeout
{
get
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
if (timeout == 0)
{
return -1;
}
return timeout;
#if DEBUG
}
#endif
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
if (value <= 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero);
}
SetSocketTimeoutOption(SocketShutdown.Receive, value, false);
#if DEBUG
}
#endif
}
}
// Set/Get WriteTimeout, note of a strange behavior, 0 timeout == infinite for sockets,
// so we map this to -1, and if you set 0, we cannot support it
public override int WriteTimeout
{
get
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
if (timeout == 0)
{
return -1;
}
return timeout;
#if DEBUG
}
#endif
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
if (value <= 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero);
}
SetSocketTimeoutOption(SocketShutdown.Send, value, false);
#if DEBUG
}
#endif
}
}
// Indicates data is available on the stream to be read.
// This property checks to see if at least one byte of data is currently available
public virtual bool DataAvailable
{
get
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
ThrowIfDisposed();
// Ask the socket how many bytes are available. If it's
// not zero, return true.
return _streamSocket.Available != 0;
#if DEBUG
}
#endif
}
}
// The length of data available on the stream. Always throws NotSupportedException.
public override long Length
{
get
{
throw new NotSupportedException(SR.net_noseek);
}
}
// Gets or sets the position in the stream. Always throws NotSupportedException.
public override long Position
{
get
{
throw new NotSupportedException(SR.net_noseek);
}
set
{
throw new NotSupportedException(SR.net_noseek);
}
}
// Seeks a specific position in the stream. This method is not supported by the
// NetworkStream class.
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.net_noseek);
}
// Read - provide core Read functionality.
//
// Provide core read functionality. All we do is call through to the
// socket Receive functionality.
//
// Input:
//
// Buffer - Buffer to read into.
// Offset - Offset into the buffer where we're to read.
// Count - Number of bytes to read.
//
// Returns:
//
// Number of bytes we read, or 0 if the socket is closed.
public override int Read(byte[] buffer, int offset, int size)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
bool canRead = CanRead; // Prevent race with Dispose.
ThrowIfDisposed();
if (!canRead)
{
throw new InvalidOperationException(SR.net_writeonlystream);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if ((uint)offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if ((uint)size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
try
{
return _streamSocket.Receive(buffer, offset, size, 0);
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
// Some sort of error occurred on the socket call,
// set the SocketException as InnerException and throw.
throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
public override int Read(Span<byte> buffer)
{
if (GetType() != typeof(NetworkStream))
{
// NetworkStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior
// to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload
// should use the behavior of Read(byte[],int,int) overload.
return base.Read(buffer);
}
ThrowIfDisposed();
if (!CanRead) throw new InvalidOperationException(SR.net_writeonlystream);
int bytesRead = _streamSocket.Receive(buffer, SocketFlags.None, out SocketError errorCode);
if (errorCode != SocketError.Success)
{
var exception = new SocketException((int)errorCode);
throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
}
return bytesRead;
}
public override unsafe int ReadByte()
{
byte b;
return Read(new Span<byte>(&b, 1)) == 0 ? -1 : b;
}
// Write - provide core Write functionality.
//
// Provide core write functionality. All we do is call through to the
// socket Send method..
//
// Input:
//
// Buffer - Buffer to write from.
// Offset - Offset into the buffer from where we'll start writing.
// Count - Number of bytes to write.
//
// Returns:
//
// Number of bytes written. We'll throw an exception if we
// can't write everything. It's brutal, but there's no other
// way to indicate an error.
public override void Write(byte[] buffer, int offset, int size)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
bool canWrite = CanWrite; // Prevent race with Dispose.
ThrowIfDisposed();
if (!canWrite)
{
throw new InvalidOperationException(SR.net_readonlystream);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if ((uint)offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if ((uint)size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
try
{
// Since the socket is in blocking mode this will always complete
// after ALL the requested number of bytes was transferred.
_streamSocket.Send(buffer, offset, size, SocketFlags.None);
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
// Some sort of error occurred on the socket call,
// set the SocketException as InnerException and throw.
throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
public override void Write(ReadOnlySpan<byte> buffer)
{
if (GetType() != typeof(NetworkStream))
{
// NetworkStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior
// to this Write(ReadOnlySpan<byte>) overload being introduced. In that case, this Write(ReadOnlySpan<byte>)
// overload should use the behavior of Write(byte[],int,int) overload.
base.Write(buffer);
return;
}
ThrowIfDisposed();
if (!CanWrite) throw new InvalidOperationException(SR.net_readonlystream);
_streamSocket.Send(buffer, SocketFlags.None, out SocketError errorCode);
if (errorCode != SocketError.Success)
{
var exception = new SocketException((int)errorCode);
throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
}
}
public override unsafe void WriteByte(byte value) =>
Write(new ReadOnlySpan<byte>(&value, 1));
private int _closeTimeout = Socket.DefaultCloseTimeout; // -1 = respect linger options
public void Close(int timeout)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
{
#endif
if (timeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
_closeTimeout = timeout;
Dispose();
#if DEBUG
}
#endif
}
private volatile bool _disposed = false;
protected override void Dispose(bool disposing)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
// Mark this as disposed before changing anything else.
bool disposed = _disposed;
_disposed = true;
if (!disposed && disposing)
{
// The only resource we need to free is the network stream, since this
// is based on the client socket, closing the stream will cause us
// to flush the data to the network, close the stream and (in the
// NetoworkStream code) close the socket as well.
_readable = false;
_writeable = false;
if (_ownsSocket)
{
// If we own the Socket (false by default), close it
// ignoring possible exceptions (eg: the user told us
// that we own the Socket but it closed at some point of time,
// here we would get an ObjectDisposedException)
_streamSocket.InternalShutdown(SocketShutdown.Both);
_streamSocket.Close(_closeTimeout);
}
}
#if DEBUG
}
#endif
base.Dispose(disposing);
}
~NetworkStream()
{
#if DEBUG
DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
#endif
Dispose(false);
}
// BeginRead - provide async read functionality.
//
// This method provides async read functionality. All we do is
// call through to the underlying socket async read.
//
// Input:
//
// buffer - Buffer to read into.
// offset - Offset into the buffer where we're to read.
// size - Number of bytes to read.
//
// Returns:
//
// An IASyncResult, representing the read.
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool canRead = CanRead; // Prevent race with Dispose.
ThrowIfDisposed();
if (!canRead)
{
throw new InvalidOperationException(SR.net_writeonlystream);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if ((uint)offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if ((uint)size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
try
{
return _streamSocket.BeginReceive(
buffer,
offset,
size,
SocketFlags.None,
callback,
state);
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
// Some sort of error occurred on the socket call,
// set the SocketException as InnerException and throw.
throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
// EndRead - handle the end of an async read.
//
// This method is called when an async read is completed. All we
// do is call through to the core socket EndReceive functionality.
//
// Returns:
//
// The number of bytes read. May throw an exception.
public override int EndRead(IAsyncResult asyncResult)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
ThrowIfDisposed();
// Validate input parameters.
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
try
{
return _streamSocket.EndReceive(asyncResult);
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
// Some sort of error occurred on the socket call,
// set the SocketException as InnerException and throw.
throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
// BeginWrite - provide async write functionality.
//
// This method provides async write functionality. All we do is
// call through to the underlying socket async send.
//
// Input:
//
// buffer - Buffer to write into.
// offset - Offset into the buffer where we're to write.
// size - Number of bytes to written.
//
// Returns:
//
// An IASyncResult, representing the write.
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
bool canWrite = CanWrite; // Prevent race with Dispose.
ThrowIfDisposed();
if (!canWrite)
{
throw new InvalidOperationException(SR.net_readonlystream);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if ((uint)offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if ((uint)size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
try
{
// Call BeginSend on the Socket.
return _streamSocket.BeginSend(
buffer,
offset,
size,
SocketFlags.None,
callback,
state);
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
// Some sort of error occurred on the socket call,
// set the SocketException as InnerException and throw.
throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
// Handle the end of an asynchronous write.
// This method is called when an async write is completed. All we
// do is call through to the core socket EndSend functionality.
// Returns: The number of bytes read. May throw an exception.
public override void EndWrite(IAsyncResult asyncResult)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
{
#endif
ThrowIfDisposed();
// Validate input parameters.
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
try
{
_streamSocket.EndSend(asyncResult);
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
// Some sort of error occurred on the socket call,
// set the SocketException as InnerException and throw.
throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
// ReadAsync - provide async read functionality.
//
// This method provides async read functionality. All we do is
// call through to the Begin/EndRead methods.
//
// Input:
//
// buffer - Buffer to read into.
// offset - Offset into the buffer where we're to read.
// size - Number of bytes to read.
// cancellationToken - Token used to request cancellation of the operation
//
// Returns:
//
// A Task<int> representing the read.
public override Task<int> ReadAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken)
{
bool canRead = CanRead; // Prevent race with Dispose.
ThrowIfDisposed();
if (!canRead)
{
throw new InvalidOperationException(SR.net_writeonlystream);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if ((uint)offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if ((uint)size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
try
{
return _streamSocket.ReceiveAsync(
new Memory<byte>(buffer, offset, size),
SocketFlags.None,
fromNetworkStream: true,
cancellationToken).AsTask();
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
// Some sort of error occurred on the socket call,
// set the SocketException as InnerException and throw.
throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
}
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
{
bool canRead = CanRead; // Prevent race with Dispose.
ThrowIfDisposed();
if (!canRead)
{
throw new InvalidOperationException(SR.net_writeonlystream);
}
try
{
return _streamSocket.ReceiveAsync(
buffer,
SocketFlags.None,
fromNetworkStream: true,
cancellationToken: cancellationToken);
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
// Some sort of error occurred on the socket call,
// set the SocketException as InnerException and throw.
throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
}
}
// WriteAsync - provide async write functionality.
//
// This method provides async write functionality. All we do is
// call through to the Begin/EndWrite methods.
//
// Input:
//
// buffer - Buffer to write into.
// offset - Offset into the buffer where we're to write.
// size - Number of bytes to write.
// cancellationToken - Token used to request cancellation of the operation
//
// Returns:
//
// A Task representing the write.
public override Task WriteAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken)
{
bool canWrite = CanWrite; // Prevent race with Dispose.
ThrowIfDisposed();
if (!canWrite)
{
throw new InvalidOperationException(SR.net_readonlystream);
}
// Validate input parameters.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if ((uint)offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if ((uint)size > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
try
{
return _streamSocket.SendAsyncForNetworkStream(
new ReadOnlyMemory<byte>(buffer, offset, size),
SocketFlags.None,
cancellationToken).AsTask();
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
// Some sort of error occurred on the socket call,
// set the SocketException as InnerException and throw.
throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
}
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
bool canWrite = CanWrite; // Prevent race with Dispose.
ThrowIfDisposed();
if (!canWrite)
{
throw new InvalidOperationException(SR.net_readonlystream);
}
try
{
return _streamSocket.SendAsyncForNetworkStream(
buffer,
SocketFlags.None,
cancellationToken);
}
catch (Exception exception) when (!(exception is OutOfMemoryException))
{
// Some sort of error occurred on the socket call,
// set the SocketException as InnerException and throw.
throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
}
}
// Flushes data from the stream. This is meaningless for us, so it does nothing.
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
// Sets the length of the stream. Always throws NotSupportedException
public override void SetLength(long value)
{
throw new NotSupportedException(SR.net_noseek);
}
private int _currentReadTimeout = -1;
private int _currentWriteTimeout = -1;
internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, mode, timeout, silent);
if (timeout < 0)
{
timeout = 0; // -1 becomes 0 for the winsock stack
}
if (mode == SocketShutdown.Send || mode == SocketShutdown.Both)
{
if (timeout != _currentWriteTimeout)
{
_streamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout, silent);
_currentWriteTimeout = timeout;
}
}
if (mode == SocketShutdown.Receive || mode == SocketShutdown.Both)
{
if (timeout != _currentReadTimeout)
{
_streamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout, silent);
_currentReadTimeout = timeout;
}
}
}
private void ThrowIfDisposed()
{
if (_disposed)
{
ThrowObjectDisposedException();
}
void ThrowObjectDisposedException() => throw new ObjectDisposedException(GetType().FullName);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using System.Threading;
using System.Security;
namespace System.Text
{
// DBCSCodePageEncoding
//
internal class DBCSCodePageEncoding : BaseCodePageEncoding
{
// Pointers to our memory section parts
[SecurityCritical]
protected unsafe char* mapBytesToUnicode = null; // char 65536
[SecurityCritical]
protected unsafe ushort* mapUnicodeToBytes = null; // byte 65536
protected const char UNKNOWN_CHAR_FLAG = (char)0x0;
protected const char UNICODE_REPLACEMENT_CHAR = (char)0xFFFD;
protected const char LEAD_BYTE_CHAR = (char)0xFFFE; // For lead bytes
// Note that even though we provide bytesUnknown and byteCountUnknown,
// They aren't actually used because of the fallback mechanism. (char is though)
private ushort _bytesUnknown;
private int _byteCountUnknown;
protected char charUnknown = (char)0;
[System.Security.SecurityCritical] // auto-generated
public DBCSCodePageEncoding(int codePage) : this(codePage, codePage)
{
}
[System.Security.SecurityCritical] // auto-generated
internal DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage)
{
}
[System.Security.SecurityCritical] // auto-generated
internal DBCSCodePageEncoding(int codePage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, dataCodePage, enc, dec)
{
}
// MBCS data section:
//
// We treat each multibyte pattern as 2 bytes in our table. If it's a single byte, then the high byte
// for that position will be 0. When the table is loaded, leading bytes are flagged with 0xFFFE, so
// when reading the table look up with each byte. If the result is 0xFFFE, then use 2 bytes to read
// further data. FFFF is a special value indicating that the Unicode code is the same as the
// character code (this helps us support code points < 0x20). FFFD is used as replacement character.
//
// Normal table:
// WCHAR* - Starting with MB code point 0.
// FFFF indicates we are to use the multibyte value for our code point.
// FFFE is the lead byte mark. (This should only appear in positions < 0x100)
// FFFD is the replacement (unknown character) mark.
// 2-20 means to advance the pointer 2-0x20 characters.
// 1 means to advance to the multibyte position contained in the next char.
// 0 has no specific meaning (May not be possible.)
//
// Table ends when multibyte position has advanced to 0xFFFF.
//
// Bytes->Unicode Best Fit table:
// WCHAR* - Same as normal table, except first wchar is byte position to start at.
//
// Unicode->Bytes Best Fit Table:
// WCHAR* - Same as normal table, except first wchar is char position to start at and
// we loop through unicode code points and the table has the byte points that
// correspond to those unicode code points.
// We have a managed code page entry, so load our tables
//
[System.Security.SecurityCritical] // auto-generated
protected override unsafe void LoadManagedCodePage()
{
fixed (byte* pBytes = m_codePageHeader)
{
CodePageHeader* pCodePage = (CodePageHeader*)pBytes;
// Should be loading OUR code page
Debug.Assert(pCodePage->CodePage == dataTableCodePage,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page");
// Make sure we're really a 1-byte code page
if (pCodePage->ByteCount != 2)
throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage));
// Remember our unknown bytes & chars
_bytesUnknown = pCodePage->ByteReplace;
charUnknown = pCodePage->UnicodeReplace;
// Need to make sure the fallback buffer's fallback char is correct
if (DecoderFallback is InternalDecoderBestFitFallback)
{
((InternalDecoderBestFitFallback)(DecoderFallback)).cReplacement = charUnknown;
}
// Is our replacement bytesUnknown a single or double byte character?
_byteCountUnknown = 1;
if (_bytesUnknown > 0xff)
_byteCountUnknown++;
// We use fallback encoder, which uses ?, which so far all of our tables do as well
Debug.Assert(_bytesUnknown == 0x3f,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected 0x3f (?) as unknown byte character");
// Get our mapped section (bytes to allocate = 2 bytes per 65536 Unicode chars + 2 bytes per 65536 DBCS chars)
// Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment)
byte* pNativeMemory = GetNativeMemory(65536 * 2 * 2 + 4 + iExtraBytes);
mapBytesToUnicode = (char*)pNativeMemory;
mapUnicodeToBytes = (ushort*)(pNativeMemory + 65536 * 2);
// Need to read our data file and fill in our section.
// WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide)
// so be careful here. Only stick legal values in here, don't stick temporary values.
// Move to the beginning of the data section
byte[] buffer = new byte[m_dataSize];
lock (s_streamLock)
{
s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(buffer, 0, m_dataSize);
}
fixed (byte* pBuffer = buffer)
{
char* pData = (char*)pBuffer;
// We start at bytes position 0
int bytePosition = 0;
int useBytes = 0;
while (bytePosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytePosition = (int)(*pData);
pData++;
continue;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytePosition += input;
continue;
}
else if (input == 0xFFFF)
{
// Same as our bytePosition
useBytes = bytePosition;
input = unchecked((char)bytePosition);
}
else if (input == LEAD_BYTE_CHAR) // 0xfffe
{
// Lead byte mark
Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100");
useBytes = bytePosition;
// input stays 0xFFFE
}
else if (input == UNICODE_REPLACEMENT_CHAR)
{
// Replacement char is already done
bytePosition++;
continue;
}
else
{
// Use this character
useBytes = bytePosition;
// input == input;
}
// We may need to clean up the selected character & position
if (CleanUpBytes(ref useBytes))
{
// Use this selected character at the selected position, don't do this if not supposed to.
if (input != LEAD_BYTE_CHAR)
{
// Don't do this for lead byte marks.
mapUnicodeToBytes[input] = unchecked((ushort)useBytes);
}
mapBytesToUnicode[useBytes] = input;
}
bytePosition++;
}
}
// See if we have any clean up to do
CleanUpEndBytes(mapBytesToUnicode);
}
}
// Any special processing for this code page
protected virtual bool CleanUpBytes(ref int bytes)
{
return true;
}
// Any special processing for this code page
[System.Security.SecurityCritical] // auto-generated
protected virtual unsafe void CleanUpEndBytes(char* chars)
{
}
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Read in our best fit table
[System.Security.SecurityCritical] // auto-generated
protected unsafe override void ReadBestFitTable()
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// If we got a best fit array already then don't do this
if (arrayUnicodeBestFit == null)
{
//
// Read in Best Fit table.
//
// First we have to advance past original character mapping table
// Move to the beginning of the data section
byte[] buffer = new byte[m_dataSize];
lock (s_streamLock)
{
s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(buffer, 0, m_dataSize);
}
fixed (byte* pBuffer = buffer)
{
char* pData = (char*)pBuffer;
// We start at bytes position 0
int bytesPosition = 0;
while (bytesPosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytesPosition = (int)(*pData);
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytesPosition += input;
}
else
{
// All other cases add 1 to bytes position
bytesPosition++;
}
}
// Now bytesPosition is at start of bytes->unicode best fit table
char* pBytes2Unicode = pData;
// Now pData should be pointing to first word of bytes -> unicode best fit table
// (which we're also not using at the moment)
int iBestFitCount = 0;
bytesPosition = *pData;
pData++;
while (bytesPosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytesPosition = (int)(*pData);
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytesPosition += input;
}
else
{
// Use this character (unless it's unknown, unk just skips 1)
if (input != UNICODE_REPLACEMENT_CHAR)
{
int correctedChar = bytesPosition;
if (CleanUpBytes(ref correctedChar))
{
// Sometimes correction makes them the same as no best fit, skip those.
if (mapBytesToUnicode[correctedChar] != input)
{
iBestFitCount++;
}
}
}
// Position gets incremented in any case.
bytesPosition++;
}
}
// Now we know how big the best fit table has to be
char[] arrayTemp = new char[iBestFitCount * 2];
// Now we know how many best fits we have, so go back & read them in
iBestFitCount = 0;
pData = pBytes2Unicode;
bytesPosition = *pData;
pData++;
bool bOutOfOrder = false;
// Read it all in again
while (bytesPosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytesPosition = (int)(*pData);
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytesPosition += input;
}
else
{
// Use this character (unless its unknown, unk just skips 1)
if (input != UNICODE_REPLACEMENT_CHAR)
{
int correctedChar = bytesPosition;
if (CleanUpBytes(ref correctedChar))
{
// Sometimes correction makes them same as no best fit, skip those.
if (mapBytesToUnicode[correctedChar] != input)
{
if (correctedChar != bytesPosition)
bOutOfOrder = true;
arrayTemp[iBestFitCount++] = unchecked((char)correctedChar);
arrayTemp[iBestFitCount++] = input;
}
}
}
// Position gets incremented in any case.
bytesPosition++;
}
}
// If they're out of order we need to sort them.
if (bOutOfOrder)
{
Debug.Assert((arrayTemp.Length / 2) < 20,
"[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2);
for (int i = 0; i < arrayTemp.Length - 2; i += 2)
{
int iSmallest = i;
char cSmallest = arrayTemp[i];
for (int j = i + 2; j < arrayTemp.Length; j += 2)
{
// Find smallest one for front
if (cSmallest > arrayTemp[j])
{
cSmallest = arrayTemp[j];
iSmallest = j;
}
}
// If smallest one is something else, switch them
if (iSmallest != i)
{
char temp = arrayTemp[iSmallest];
arrayTemp[iSmallest] = arrayTemp[i];
arrayTemp[i] = temp;
temp = arrayTemp[iSmallest + 1];
arrayTemp[iSmallest + 1] = arrayTemp[i + 1];
arrayTemp[i + 1] = temp;
}
}
}
// Remember our array
arrayBytesBestFit = arrayTemp;
// Now were at beginning of Unicode -> Bytes best fit table, need to count them
char* pUnicode2Bytes = pData;
int unicodePosition = *(pData++);
iBestFitCount = 0;
while (unicodePosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
unicodePosition = (int)*pData;
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
unicodePosition += input;
}
else
{
// Same as our unicodePosition or use this character
if (input > 0)
iBestFitCount++;
unicodePosition++;
}
}
// Allocate our table
arrayTemp = new char[iBestFitCount * 2];
// Now do it again to fill the array with real values
pData = pUnicode2Bytes;
unicodePosition = *(pData++);
iBestFitCount = 0;
while (unicodePosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
unicodePosition = (int)*pData;
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
unicodePosition += input;
}
else
{
if (input > 0)
{
// Use this character, may need to clean it up
int correctedChar = (int)input;
if (CleanUpBytes(ref correctedChar))
{
arrayTemp[iBestFitCount++] = unchecked((char)unicodePosition);
// Have to map it to Unicode because best fit will need Unicode value of best fit char.
arrayTemp[iBestFitCount++] = mapBytesToUnicode[correctedChar];
}
}
unicodePosition++;
}
}
// Remember our array
arrayUnicodeBestFit = arrayTemp;
}
}
}
}
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative");
Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
CheckMemorySection();
// Get any left over characters
char charLeftOver = (char)0;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
// Only count if encoder.m_throwOnOverflow
if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType()));
}
// prepare our end
int byteCount = 0;
char* charEnd = chars + count;
// For fallback we will need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
Debug.Assert(encoder != null,
"[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(chars, charEnd, encoder, false);
// This will fallback a pair if *chars is a low surrogate
fallbackHelper.InternalFallback(charLeftOver, ref chars);
}
// Now we may have fallback char[] already (from the encoder)
// We have to use fallback method.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// get byte for this char
ushort sTemp = mapUnicodeToBytes[ch];
// Check for fallback, this'll catch surrogate pairs too.
if (sTemp == 0 && ch != (char)0)
{
if (fallbackBuffer == null)
{
// Initialize the buffer
if (encoder == null)
fallbackBuffer = EncoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(charEnd - count, charEnd, encoder, false);
}
// Get Fallback
fallbackHelper.InternalFallback(ch, ref chars);
continue;
}
// We'll use this one
byteCount++;
if (sTemp >= 0x100)
byteCount++;
}
return (int)byteCount;
}
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null");
Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative");
Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null");
Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
CheckMemorySection();
// For fallback we will need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
// prepare our end
char* charEnd = chars + charCount;
char* charStart = chars;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
// Get any left over characters
char charLeftOver = (char)0;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[DBCSCodePageEncoding.GetBytes]leftover character should be high surrogate");
// Go ahead and get the fallback buffer (need leftover fallback if converting)
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(chars, charEnd, encoder, true);
// If we're not converting we must not have a fallback buffer
if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType()));
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Debug.Assert(encoder != null,
"[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
fallbackHelper.InternalFallback(charLeftOver, ref chars);
}
}
// Now we may have fallback char[] already from the encoder
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// get byte for this char
ushort sTemp = mapUnicodeToBytes[ch];
// Check for fallback, this'll catch surrogate pairs too.
if (sTemp == 0 && ch != (char)0)
{
if (fallbackBuffer == null)
{
// Initialize the buffer
Debug.Assert(encoder == null,
"[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder.");
fallbackBuffer = EncoderFallback.CreateFallbackBuffer();
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
}
// Get Fallback
fallbackHelper.InternalFallback(ch, ref chars);
continue;
}
// We'll use this one (or two)
// Bounds check
// Go ahead and add it, lead byte 1st if necessary
if (sTemp >= 0x100)
{
if (bytes + 1 >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackHelper.bFallingBack == false)
{
Debug.Assert(chars > charStart,
"[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)");
chars--; // don't use last char
}
else
fallbackBuffer.MovePrevious(); // don't use last fallback
ThrowBytesOverflow(encoder, chars == charStart); // throw ?
break; // don't throw, stop
}
*bytes = unchecked((byte)(sTemp >> 8));
bytes++;
}
// Single byte
else if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackHelper.bFallingBack == false)
{
Debug.Assert(chars > charStart,
"[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)");
chars--; // don't use last char
}
else
fallbackBuffer.MovePrevious(); // don't use last fallback
ThrowBytesOverflow(encoder, chars == charStart); // throw ?
break; // don't throw, stop
}
*bytes = unchecked((byte)(sTemp & 0xff));
bytes++;
}
// encoder stuff if we have one
if (encoder != null)
{
// Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases
if (fallbackBuffer != null && !fallbackHelper.bUsedEncoder)
// Clear it in case of MustFlush
encoder.charLeftOver = (char)0;
// Set our chars used count
encoder.m_charsUsed = (int)(chars - charStart);
}
return (int)(bytes - byteStart);
}
// This is internal and called by something else,
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
// Just assert, we're called internally so these should be safe, checked already
Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null");
Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative");
CheckMemorySection();
// Fix our decoder
DBCSDecoder decoder = (DBCSDecoder)baseDecoder;
// Get our fallback
DecoderFallbackBuffer fallbackBuffer = null;
// We'll need to know where the end is
byte* byteEnd = bytes + count;
int charCount = count; // Assume 1 char / byte
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
Debug.Assert(decoder == null ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start");
DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
// If we have a left over byte, use it
if (decoder != null && decoder.bLeftOver > 0)
{
// We have a left over byte?
if (count == 0)
{
// No input though
if (!decoder.MustFlush)
{
// Don't have to flush
return 0;
}
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(bytes, null);
byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) };
return fallbackHelper.InternalFallback(byteBuffer, bytes);
}
// Get our full info
int iBytes = decoder.bLeftOver << 8;
iBytes |= (*bytes);
bytes++;
// This is either 1 known char or fallback
// Already counted 1 char
// Look up our bytes
char cDecoder = mapBytesToUnicode[iBytes];
if (cDecoder == 0 && iBytes != 0)
{
// Deallocate preallocated one
charCount--;
// We'll need a fallback
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - count, null);
// Do fallback, we know there are 2 bytes
byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
charCount += fallbackHelper.InternalFallback(byteBuffer, bytes);
}
// else we already reserved space for this one.
}
// Loop, watch out for fallbacks
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
int iBytes = *bytes;
bytes++;
char c = mapBytesToUnicode[iBytes];
// See if it was a double byte character
if (c == LEAD_BYTE_CHAR)
{
// It's a lead byte
charCount--; // deallocate preallocated lead byte
if (bytes < byteEnd)
{
// Have another to use, so use it
iBytes <<= 8;
iBytes |= *bytes;
bytes++;
c = mapBytesToUnicode[iBytes];
}
else
{
// No input left
if (decoder == null || decoder.MustFlush)
{
// have to flush anyway, set to unknown so we use fallback
charCount++; // reallocate deallocated lead byte
c = UNKNOWN_CHAR_FLAG;
}
else
{
// We'll stick it in decoder
break;
}
}
}
// See if it was unknown.
// Unknown and known chars already allocated, but fallbacks aren't
if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - count, null);
}
// Do fallback
charCount--; // Get rid of preallocated extra char
byte[] byteBuffer = null;
if (iBytes < 0x100)
byteBuffer = new byte[] { unchecked((byte)iBytes) };
else
byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
charCount += fallbackHelper.InternalFallback(byteBuffer, bytes);
}
}
// Shouldn't have anything in fallback buffer for GetChars
Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
return charCount;
}
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null");
Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative");
Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null");
Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative");
CheckMemorySection();
// Fix our decoder
DBCSDecoder decoder = (DBCSDecoder)baseDecoder;
// We'll need to know where the end is
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
char* charStart = chars;
char* charEnd = chars + charCount;
bool bUsedDecoder = false;
// Get our fallback
DecoderFallbackBuffer fallbackBuffer = null;
// Shouldn't have anything in fallback buffer for GetChars
Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
// If we have a left over byte, use it
if (decoder != null && decoder.bLeftOver > 0)
{
// We have a left over byte?
if (byteCount == 0)
{
// No input though
if (!decoder.MustFlush)
{
// Don't have to flush
return 0;
}
// Well, we're flushing, so use '?' or fallback
// fallback leftover byte
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(bytes, charEnd);
// If no room, it's hopeless, this was 1st fallback
byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) };
if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars))
ThrowCharsOverflow(decoder, true);
decoder.bLeftOver = 0;
// Done, return it
return (int)(chars - charStart);
}
// Get our full info
int iBytes = decoder.bLeftOver << 8;
iBytes |= (*bytes);
bytes++;
// Look up our bytes
char cDecoder = mapBytesToUnicode[iBytes];
if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd);
byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars))
ThrowCharsOverflow(decoder, true);
}
else
{
// Do we have output room?, hopeless if not, this is first char
if (chars >= charEnd)
ThrowCharsOverflow(decoder, true);
*(chars++) = cDecoder;
}
}
// Loop, paying attention to our fallbacks.
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
int iBytes = *bytes;
bytes++;
char c = mapBytesToUnicode[iBytes];
// See if it was a double byte character
if (c == LEAD_BYTE_CHAR)
{
// Its a lead byte
if (bytes < byteEnd)
{
// Have another to use, so use it
iBytes <<= 8;
iBytes |= *bytes;
bytes++;
c = mapBytesToUnicode[iBytes];
}
else
{
// No input left
if (decoder == null || decoder.MustFlush)
{
// have to flush anyway, set to unknown so we use fallback
c = UNKNOWN_CHAR_FLAG;
}
else
{
// Stick it in decoder
bUsedDecoder = true;
decoder.bLeftOver = (byte)iBytes;
break;
}
}
}
// See if it was unknown
if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd);
}
// Do fallback
byte[] byteBuffer = null;
if (iBytes < 0x100)
byteBuffer = new byte[] { unchecked((byte)iBytes) };
else
byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get these byte(s)
Debug.Assert(bytes >= byteStart + byteBuffer.Length,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for fallback");
bytes -= byteBuffer.Length; // didn't use these byte(s)
fallbackHelper.InternalReset(); // Didn't fall this back
ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
break; // don't throw, but stop loop
}
}
else
{
// Do we have buffer room?
if (chars >= charEnd)
{
// May or may not throw, but we didn't get these byte(s)
Debug.Assert(bytes > byteStart,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte");
bytes--; // unused byte
if (iBytes >= 0x100)
{
Debug.Assert(bytes > byteStart,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte");
bytes--; // 2nd unused byte
}
ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
break; // don't throw, but stop loop
}
*(chars++) = c;
}
}
// We already stuck it in encoder if necessary, but we have to clear cases where nothing new got into decoder
if (decoder != null)
{
// Clear it in case of MustFlush
if (bUsedDecoder == false)
{
decoder.bLeftOver = 0;
}
// Remember our count
decoder.m_bytesUsed = (int)(bytes - byteStart);
}
// Shouldn't have anything in fallback buffer for GetChars
Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end");
// Return length of our output
return (int)(chars - charStart);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 2 to 1 is worst case. Already considered surrogate fallback
byteCount *= 2;
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// DBCS is pretty much the same, but could have hanging high byte making extra ? and fallback for unknown
long charCount = ((long)byteCount + 1);
// 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer.
if (DecoderFallback.MaxCharCount > 1)
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
public override Decoder GetDecoder()
{
return new DBCSDecoder(this);
}
internal class DBCSDecoder : DecoderNLS
{
// Need a place for the last left over byte
internal byte bLeftOver = 0;
public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding)
{
// Base calls reset
}
public override void Reset()
{
bLeftOver = 0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Anything left in our decoder?
internal override bool HasState
{
get
{
return (bLeftOver != 0);
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Database;
using osu.Game.Extensions;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Taiko;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Carousel;
using osu.Game.Screens.Select.Filter;
using osu.Game.Tests.Resources;
using osuTK.Input;
namespace osu.Game.Tests.Visual.SongSelect
{
[TestFixture]
public class TestScenePlaySongSelect : ScreenTestScene
{
private BeatmapManager manager;
private RulesetStore rulesets;
private MusicController music;
private WorkingBeatmap defaultBeatmap;
private TestSongSelect songSelect;
[BackgroundDependencyLoader]
private void load(GameHost host, AudioManager audio)
{
// These DI caches are required to ensure for interactive runs this test scene doesn't nuke all user beatmaps in the local install.
// At a point we have isolated interactive test runs enough, this can likely be removed.
Dependencies.Cache(rulesets = new RealmRulesetStore(Realm));
Dependencies.Cache(Realm);
Dependencies.Cache(manager = new BeatmapManager(LocalStorage, Realm, rulesets, null, audio, Resources, host, defaultBeatmap = Beatmap.Default));
Dependencies.Cache(music = new MusicController());
// required to get bindables attached
Add(music);
Dependencies.Cache(config = new OsuConfigManager(LocalStorage));
}
private OsuConfigManager config;
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("reset defaults", () =>
{
Ruleset.Value = new OsuRuleset().RulesetInfo;
Beatmap.SetDefault();
songSelect = null;
});
AddStep("delete all beatmaps", () => manager?.Delete());
}
[Test]
public void TestSingleFilterOnEnter()
{
addRulesetImportStep(0);
addRulesetImportStep(0);
createSongSelect();
AddAssert("filter count is 1", () => songSelect.FilterCount == 1);
}
[Test]
public void TestChangeBeatmapBeforeEnter()
{
addRulesetImportStep(0);
createSongSelect();
waitForInitialSelection();
WorkingBeatmap selected = null;
AddStep("store selected beatmap", () => selected = Beatmap.Value);
AddStep("select next and enter", () =>
{
InputManager.Key(Key.Down);
InputManager.Key(Key.Enter);
});
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddAssert("ensure selection changed", () => selected != Beatmap.Value);
}
[Test]
public void TestChangeBeatmapAfterEnter()
{
addRulesetImportStep(0);
createSongSelect();
waitForInitialSelection();
WorkingBeatmap selected = null;
AddStep("store selected beatmap", () => selected = Beatmap.Value);
AddStep("select next and enter", () =>
{
InputManager.Key(Key.Enter);
InputManager.Key(Key.Down);
});
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddAssert("ensure selection didn't change", () => selected == Beatmap.Value);
}
[Test]
public void TestChangeBeatmapViaMouseBeforeEnter()
{
addRulesetImportStep(0);
createSongSelect();
AddUntilStep("wait for initial selection", () => !Beatmap.IsDefault);
WorkingBeatmap selected = null;
AddStep("store selected beatmap", () => selected = Beatmap.Value);
AddUntilStep("wait for beatmaps to load", () => songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmap>().Any());
AddStep("select next and enter", () =>
{
InputManager.MoveMouseTo(songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmap>()
.First(b => !((CarouselBeatmap)b.Item).BeatmapInfo.Equals(songSelect.Carousel.SelectedBeatmapInfo)));
InputManager.Click(MouseButton.Left);
InputManager.Key(Key.Enter);
});
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddAssert("ensure selection changed", () => selected != Beatmap.Value);
}
[Test]
public void TestChangeBeatmapViaMouseAfterEnter()
{
addRulesetImportStep(0);
createSongSelect();
waitForInitialSelection();
WorkingBeatmap selected = null;
AddStep("store selected beatmap", () => selected = Beatmap.Value);
AddStep("select next and enter", () =>
{
InputManager.MoveMouseTo(songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmap>()
.First(b => !((CarouselBeatmap)b.Item).BeatmapInfo.Equals(songSelect.Carousel.SelectedBeatmapInfo)));
InputManager.PressButton(MouseButton.Left);
InputManager.Key(Key.Enter);
InputManager.ReleaseButton(MouseButton.Left);
});
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddAssert("ensure selection didn't change", () => selected == Beatmap.Value);
}
[Test]
public void TestNoFilterOnSimpleResume()
{
addRulesetImportStep(0);
addRulesetImportStep(0);
createSongSelect();
AddStep("push child screen", () => Stack.Push(new TestSceneOsuScreenStack.TestScreen("test child")));
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddStep("return", () => songSelect.MakeCurrent());
AddUntilStep("wait for current", () => songSelect.IsCurrentScreen());
AddAssert("filter count is 1", () => songSelect.FilterCount == 1);
}
[Test]
public void TestFilterOnResumeAfterChange()
{
addRulesetImportStep(0);
addRulesetImportStep(0);
AddStep("change convert setting", () => config.SetValue(OsuSetting.ShowConvertedBeatmaps, false));
createSongSelect();
AddStep("push child screen", () => Stack.Push(new TestSceneOsuScreenStack.TestScreen("test child")));
AddUntilStep("wait for not current", () => !songSelect.IsCurrentScreen());
AddStep("change convert setting", () => config.SetValue(OsuSetting.ShowConvertedBeatmaps, true));
AddStep("return", () => songSelect.MakeCurrent());
AddUntilStep("wait for current", () => songSelect.IsCurrentScreen());
AddAssert("filter count is 2", () => songSelect.FilterCount == 2);
}
[Test]
public void TestAudioResuming()
{
createSongSelect();
addRulesetImportStep(0);
addRulesetImportStep(0);
checkMusicPlaying(true);
AddStep("select first", () => songSelect.Carousel.SelectBeatmap(songSelect.Carousel.BeatmapSets.First().Beatmaps.First()));
checkMusicPlaying(true);
AddStep("manual pause", () => music.TogglePause());
checkMusicPlaying(false);
AddStep("select next difficulty", () => songSelect.Carousel.SelectNext(skipDifficulties: false));
checkMusicPlaying(false);
AddStep("select next set", () => songSelect.Carousel.SelectNext());
checkMusicPlaying(true);
}
[TestCase(false)]
[TestCase(true)]
public void TestAudioRemainsCorrectOnRulesetChange(bool rulesetsInSameBeatmap)
{
createSongSelect();
// start with non-osu! to avoid convert confusion
changeRuleset(1);
if (rulesetsInSameBeatmap)
{
AddStep("import multi-ruleset map", () =>
{
var usableRulesets = rulesets.AvailableRulesets.Where(r => r.OnlineID != 2).ToArray();
manager.Import(TestResources.CreateTestBeatmapSetInfo(rulesets: usableRulesets));
});
}
else
{
addRulesetImportStep(1);
addRulesetImportStep(0);
}
checkMusicPlaying(true);
AddStep("manual pause", () => music.TogglePause());
checkMusicPlaying(false);
changeRuleset(0);
checkMusicPlaying(!rulesetsInSameBeatmap);
}
[Test]
public void TestDummy()
{
createSongSelect();
AddUntilStep("dummy selected", () => songSelect.CurrentBeatmap == defaultBeatmap);
AddUntilStep("dummy shown on wedge", () => songSelect.CurrentBeatmapDetailsBeatmap == defaultBeatmap);
addManyTestMaps();
AddUntilStep("random map selected", () => songSelect.CurrentBeatmap != defaultBeatmap);
}
[Test]
public void TestSorting()
{
createSongSelect();
addManyTestMaps();
AddUntilStep("random map selected", () => songSelect.CurrentBeatmap != defaultBeatmap);
AddStep(@"Sort by Artist", () => config.SetValue(OsuSetting.SongSelectSortingMode, SortMode.Artist));
AddStep(@"Sort by Title", () => config.SetValue(OsuSetting.SongSelectSortingMode, SortMode.Title));
AddStep(@"Sort by Author", () => config.SetValue(OsuSetting.SongSelectSortingMode, SortMode.Author));
AddStep(@"Sort by DateAdded", () => config.SetValue(OsuSetting.SongSelectSortingMode, SortMode.DateAdded));
AddStep(@"Sort by BPM", () => config.SetValue(OsuSetting.SongSelectSortingMode, SortMode.BPM));
AddStep(@"Sort by Length", () => config.SetValue(OsuSetting.SongSelectSortingMode, SortMode.Length));
AddStep(@"Sort by Difficulty", () => config.SetValue(OsuSetting.SongSelectSortingMode, SortMode.Difficulty));
AddStep(@"Sort by Source", () => config.SetValue(OsuSetting.SongSelectSortingMode, SortMode.Source));
}
[Test]
public void TestImportUnderDifferentRuleset()
{
createSongSelect();
addRulesetImportStep(2);
AddUntilStep("no selection", () => songSelect.Carousel.SelectedBeatmapInfo == null);
}
[Test]
public void TestImportUnderCurrentRuleset()
{
createSongSelect();
changeRuleset(2);
addRulesetImportStep(2);
addRulesetImportStep(1);
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo.Ruleset.OnlineID == 2);
changeRuleset(1);
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo.Ruleset.OnlineID == 1);
changeRuleset(0);
AddUntilStep("no selection", () => songSelect.Carousel.SelectedBeatmapInfo == null);
}
[Test]
public void TestPresentNewRulesetNewBeatmap()
{
createSongSelect();
changeRuleset(2);
addRulesetImportStep(2);
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo.Ruleset.OnlineID == 2);
addRulesetImportStep(0);
addRulesetImportStep(0);
addRulesetImportStep(0);
BeatmapInfo target = null;
AddStep("select beatmap/ruleset externally", () =>
{
target = manager.GetAllUsableBeatmapSets()
.Last(b => b.Beatmaps.Any(bi => bi.Ruleset.OnlineID == 0)).Beatmaps.Last();
Ruleset.Value = rulesets.AvailableRulesets.First(r => r.OnlineID == 0);
Beatmap.Value = manager.GetWorkingBeatmap(target);
});
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo.Equals(target));
// this is an important check, to make sure updateComponentFromBeatmap() was actually run
AddUntilStep("selection shown on wedge", () => songSelect.CurrentBeatmapDetailsBeatmap.BeatmapInfo.MatchesOnlineID(target));
}
[Test]
public void TestPresentNewBeatmapNewRuleset()
{
createSongSelect();
changeRuleset(2);
addRulesetImportStep(2);
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo.Ruleset.OnlineID == 2);
addRulesetImportStep(0);
addRulesetImportStep(0);
addRulesetImportStep(0);
BeatmapInfo target = null;
AddStep("select beatmap/ruleset externally", () =>
{
target = manager.GetAllUsableBeatmapSets()
.Last(b => b.Beatmaps.Any(bi => bi.Ruleset.OnlineID == 0)).Beatmaps.Last();
Beatmap.Value = manager.GetWorkingBeatmap(target);
Ruleset.Value = rulesets.AvailableRulesets.First(r => r.OnlineID == 0);
});
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo.Equals(target));
AddUntilStep("has correct ruleset", () => Ruleset.Value.OnlineID == 0);
// this is an important check, to make sure updateComponentFromBeatmap() was actually run
AddUntilStep("selection shown on wedge", () => songSelect.CurrentBeatmapDetailsBeatmap.BeatmapInfo.MatchesOnlineID(target));
}
[Test]
public void TestRulesetChangeResetsMods()
{
createSongSelect();
changeRuleset(0);
changeMods(new OsuModHardRock());
int actionIndex = 0;
int modChangeIndex = 0;
int rulesetChangeIndex = 0;
AddStep("change ruleset", () =>
{
SelectedMods.ValueChanged += onModChange;
songSelect.Ruleset.ValueChanged += onRulesetChange;
Ruleset.Value = new TaikoRuleset().RulesetInfo;
SelectedMods.ValueChanged -= onModChange;
songSelect.Ruleset.ValueChanged -= onRulesetChange;
});
AddAssert("mods changed before ruleset", () => modChangeIndex < rulesetChangeIndex);
AddAssert("empty mods", () => !SelectedMods.Value.Any());
void onModChange(ValueChangedEvent<IReadOnlyList<Mod>> e) => modChangeIndex = actionIndex++;
void onRulesetChange(ValueChangedEvent<RulesetInfo> e) => rulesetChangeIndex = actionIndex++;
}
[Test]
public void TestModsRetainedBetweenSongSelect()
{
AddAssert("empty mods", () => !SelectedMods.Value.Any());
createSongSelect();
addRulesetImportStep(0);
changeMods(new OsuModHardRock());
createSongSelect();
AddAssert("mods retained", () => SelectedMods.Value.Any());
}
[Test]
public void TestStartAfterUnMatchingFilterDoesNotStart()
{
createSongSelect();
addManyTestMaps();
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo != null);
bool startRequested = false;
AddStep("set filter and finalize", () =>
{
songSelect.StartRequested = () => startRequested = true;
songSelect.Carousel.Filter(new FilterCriteria { SearchText = "somestringthatshouldn'tbematchable" });
songSelect.FinaliseSelection();
songSelect.StartRequested = null;
});
AddAssert("start not requested", () => !startRequested);
}
[TestCase(false)]
[TestCase(true)]
public void TestExternalBeatmapChangeWhileFiltered(bool differentRuleset)
{
createSongSelect();
// ensure there is at least 1 difficulty for each of the rulesets
// (catch is excluded inside of addManyTestMaps).
addManyTestMaps(3);
changeRuleset(0);
// used for filter check below
AddStep("allow convert display", () => config.SetValue(OsuSetting.ShowConvertedBeatmaps, true));
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo != null);
AddStep("set filter text", () => songSelect.FilterControl.ChildrenOfType<SearchTextBox>().First().Text = "nonono");
AddUntilStep("dummy selected", () => Beatmap.Value is DummyWorkingBeatmap);
AddUntilStep("has no selection", () => songSelect.Carousel.SelectedBeatmapInfo == null);
BeatmapInfo target = null;
int targetRuleset = differentRuleset ? 1 : 0;
AddStep("select beatmap externally", () =>
{
target = manager.GetAllUsableBeatmapSets()
.First(b => b.Beatmaps.Any(bi => bi.Ruleset.OnlineID == targetRuleset))
.Beatmaps
.First(bi => bi.Ruleset.OnlineID == targetRuleset);
Beatmap.Value = manager.GetWorkingBeatmap(target);
});
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo != null);
AddAssert("selected only shows expected ruleset (plus converts)", () =>
{
var selectedPanel = songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmapSet>().First(s => s.Item.State.Value == CarouselItemState.Selected);
// special case for converts checked here.
return selectedPanel.ChildrenOfType<FilterableDifficultyIcon>().All(i =>
i.IsFiltered || i.Item.BeatmapInfo.Ruleset.OnlineID == targetRuleset || i.Item.BeatmapInfo.Ruleset.OnlineID == 0);
});
AddUntilStep("carousel has correct", () => songSelect.Carousel.SelectedBeatmapInfo?.MatchesOnlineID(target) == true);
AddUntilStep("game has correct", () => Beatmap.Value.BeatmapInfo.MatchesOnlineID(target));
AddStep("reset filter text", () => songSelect.FilterControl.ChildrenOfType<SearchTextBox>().First().Text = string.Empty);
AddAssert("game still correct", () => Beatmap.Value?.BeatmapInfo.MatchesOnlineID(target) == true);
AddAssert("carousel still correct", () => songSelect.Carousel.SelectedBeatmapInfo.MatchesOnlineID(target));
}
[Test]
public void TestExternalBeatmapChangeWhileFilteredThenRefilter()
{
createSongSelect();
// ensure there is at least 1 difficulty for each of the rulesets
// (catch is excluded inside of addManyTestMaps).
addManyTestMaps(3);
changeRuleset(0);
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo != null);
AddStep("set filter text", () => songSelect.FilterControl.ChildrenOfType<SearchTextBox>().First().Text = "nonono");
AddUntilStep("dummy selected", () => Beatmap.Value is DummyWorkingBeatmap);
AddUntilStep("has no selection", () => songSelect.Carousel.SelectedBeatmapInfo == null);
BeatmapInfo target = null;
AddStep("select beatmap externally", () =>
{
target = manager
.GetAllUsableBeatmapSets()
.First(b => b.Beatmaps.Any(bi => bi.Ruleset.OnlineID == 1))
.Beatmaps.First();
Beatmap.Value = manager.GetWorkingBeatmap(target);
});
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo != null);
AddUntilStep("carousel has correct", () => songSelect.Carousel.SelectedBeatmapInfo?.MatchesOnlineID(target) == true);
AddUntilStep("game has correct", () => Beatmap.Value.BeatmapInfo.MatchesOnlineID(target));
AddStep("set filter text", () => songSelect.FilterControl.ChildrenOfType<SearchTextBox>().First().Text = "nononoo");
AddUntilStep("game lost selection", () => Beatmap.Value is DummyWorkingBeatmap);
AddAssert("carousel lost selection", () => songSelect.Carousel.SelectedBeatmapInfo == null);
}
[Test]
public void TestAutoplayViaCtrlEnter()
{
addRulesetImportStep(0);
createSongSelect();
AddUntilStep("wait for selection", () => !Beatmap.IsDefault);
AddStep("press ctrl+enter", () =>
{
InputManager.PressKey(Key.ControlLeft);
InputManager.Key(Key.Enter);
InputManager.ReleaseKey(Key.ControlLeft);
});
AddUntilStep("wait for player", () => Stack.CurrentScreen is PlayerLoader);
AddAssert("autoplay enabled", () => songSelect.Mods.Value.FirstOrDefault() is ModAutoplay);
AddUntilStep("wait for return to ss", () => songSelect.IsCurrentScreen());
AddAssert("mod disabled", () => songSelect.Mods.Value.Count == 0);
}
[Test]
public void TestHideSetSelectsCorrectBeatmap()
{
Guid? previousID = null;
createSongSelect();
addRulesetImportStep(0);
AddStep("Move to last difficulty", () => songSelect.Carousel.SelectBeatmap(songSelect.Carousel.BeatmapSets.First().Beatmaps.Last()));
AddStep("Store current ID", () => previousID = songSelect.Carousel.SelectedBeatmapInfo.ID);
AddStep("Hide first beatmap", () => manager.Hide(songSelect.Carousel.SelectedBeatmapSet.Beatmaps.First()));
AddAssert("Selected beatmap has not changed", () => songSelect.Carousel.SelectedBeatmapInfo.ID == previousID);
}
[Test]
public void TestDifficultyIconSelecting()
{
addRulesetImportStep(0);
createSongSelect();
AddUntilStep("wait for selection", () => !Beatmap.IsDefault);
DrawableCarouselBeatmapSet set = null;
AddStep("Find the DrawableCarouselBeatmapSet", () =>
{
set = songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmapSet>().First();
});
FilterableDifficultyIcon difficultyIcon = null;
AddUntilStep("Find an icon", () =>
{
return (difficultyIcon = set.ChildrenOfType<FilterableDifficultyIcon>()
.FirstOrDefault(icon => getDifficultyIconIndex(set, icon) != getCurrentBeatmapIndex())) != null;
});
AddStep("Click on a difficulty", () =>
{
InputManager.MoveMouseTo(difficultyIcon);
InputManager.Click(MouseButton.Left);
});
AddAssert("Selected beatmap correct", () => getCurrentBeatmapIndex() == getDifficultyIconIndex(set, difficultyIcon));
double? maxBPM = null;
AddStep("Filter some difficulties", () => songSelect.Carousel.Filter(new FilterCriteria
{
BPM = new FilterCriteria.OptionalRange<double>
{
Min = maxBPM = songSelect.Carousel.SelectedBeatmapSet.MaxBPM,
IsLowerInclusive = true
}
}));
BeatmapInfo filteredBeatmap = null;
FilterableDifficultyIcon filteredIcon = null;
AddStep("Get filtered icon", () =>
{
var selectedSet = songSelect.Carousel.SelectedBeatmapSet;
filteredBeatmap = selectedSet.Beatmaps.First(b => b.BPM < maxBPM);
int filteredBeatmapIndex = getBeatmapIndex(selectedSet, filteredBeatmap);
filteredIcon = set.ChildrenOfType<FilterableDifficultyIcon>().ElementAt(filteredBeatmapIndex);
});
AddStep("Click on a filtered difficulty", () =>
{
InputManager.MoveMouseTo(filteredIcon);
InputManager.Click(MouseButton.Left);
});
AddAssert("Selected beatmap correct", () => songSelect.Carousel.SelectedBeatmapInfo.Equals(filteredBeatmap));
}
[Test]
public void TestChangingRulesetOnMultiRulesetBeatmap()
{
int changeCount = 0;
AddStep("change convert setting", () => config.SetValue(OsuSetting.ShowConvertedBeatmaps, false));
AddStep("bind beatmap changed", () =>
{
Beatmap.ValueChanged += onChange;
changeCount = 0;
});
changeRuleset(0);
createSongSelect();
AddStep("import multi-ruleset map", () =>
{
var usableRulesets = rulesets.AvailableRulesets.Where(r => r.OnlineID != 2).ToArray();
manager.Import(TestResources.CreateTestBeatmapSetInfo(3, usableRulesets));
});
int previousSetID = 0;
AddUntilStep("wait for selection", () => !Beatmap.IsDefault);
AddStep("record set ID", () => previousSetID = ((IBeatmapSetInfo)Beatmap.Value.BeatmapSetInfo).OnlineID);
AddAssert("selection changed once", () => changeCount == 1);
AddAssert("Check ruleset is osu!", () => Ruleset.Value.OnlineID == 0);
changeRuleset(3);
AddUntilStep("Check ruleset changed to mania", () => Ruleset.Value.OnlineID == 3);
AddUntilStep("selection changed", () => changeCount > 1);
AddAssert("Selected beatmap still same set", () => Beatmap.Value.BeatmapSetInfo.OnlineID == previousSetID);
AddAssert("Selected beatmap is mania", () => Beatmap.Value.BeatmapInfo.Ruleset.OnlineID == 3);
AddAssert("selection changed only fired twice", () => changeCount == 2);
AddStep("unbind beatmap changed", () => Beatmap.ValueChanged -= onChange);
AddStep("change convert setting", () => config.SetValue(OsuSetting.ShowConvertedBeatmaps, true));
// ReSharper disable once AccessToModifiedClosure
void onChange(ValueChangedEvent<WorkingBeatmap> valueChangedEvent) => changeCount++;
}
[Test]
public void TestDifficultyIconSelectingForDifferentRuleset()
{
changeRuleset(0);
createSongSelect();
AddStep("import multi-ruleset map", () =>
{
var usableRulesets = rulesets.AvailableRulesets.Where(r => r.OnlineID != 2).ToArray();
manager.Import(TestResources.CreateTestBeatmapSetInfo(3, usableRulesets));
});
DrawableCarouselBeatmapSet set = null;
AddUntilStep("Find the DrawableCarouselBeatmapSet", () =>
{
set = songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmapSet>().FirstOrDefault();
return set != null;
});
FilterableDifficultyIcon difficultyIcon = null;
AddUntilStep("Find an icon for different ruleset", () =>
{
difficultyIcon = set.ChildrenOfType<FilterableDifficultyIcon>()
.FirstOrDefault(icon => icon.Item.BeatmapInfo.Ruleset.OnlineID == 3);
return difficultyIcon != null;
});
AddAssert("Check ruleset is osu!", () => Ruleset.Value.OnlineID == 0);
int previousSetID = 0;
AddStep("record set ID", () => previousSetID = ((IBeatmapSetInfo)Beatmap.Value.BeatmapSetInfo).OnlineID);
AddStep("Click on a difficulty", () =>
{
InputManager.MoveMouseTo(difficultyIcon);
InputManager.Click(MouseButton.Left);
});
AddUntilStep("Check ruleset changed to mania", () => Ruleset.Value.OnlineID == 3);
AddAssert("Selected beatmap still same set", () => songSelect.Carousel.SelectedBeatmapInfo.BeatmapSet?.OnlineID == previousSetID);
AddAssert("Selected beatmap is mania", () => Beatmap.Value.BeatmapInfo.Ruleset.OnlineID == 3);
}
[Test]
public void TestGroupedDifficultyIconSelecting()
{
changeRuleset(0);
createSongSelect();
BeatmapSetInfo imported = null;
AddStep("import huge difficulty count map", () =>
{
var usableRulesets = rulesets.AvailableRulesets.Where(r => r.OnlineID != 2).ToArray();
imported = manager.Import(TestResources.CreateTestBeatmapSetInfo(50, usableRulesets))?.Value;
});
AddStep("select the first beatmap of import", () => Beatmap.Value = manager.GetWorkingBeatmap(imported.Beatmaps.First()));
DrawableCarouselBeatmapSet set = null;
AddUntilStep("Find the DrawableCarouselBeatmapSet", () =>
{
set = songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmapSet>().FirstOrDefault();
return set != null;
});
FilterableGroupedDifficultyIcon groupIcon = null;
AddUntilStep("Find group icon for different ruleset", () =>
{
return (groupIcon = set.ChildrenOfType<FilterableGroupedDifficultyIcon>()
.FirstOrDefault(icon => icon.Items.First().BeatmapInfo.Ruleset.OnlineID == 3)) != null;
});
AddAssert("Check ruleset is osu!", () => Ruleset.Value.OnlineID == 0);
AddStep("Click on group", () =>
{
InputManager.MoveMouseTo(groupIcon);
InputManager.Click(MouseButton.Left);
});
AddUntilStep("Check ruleset changed to mania", () => Ruleset.Value.OnlineID == 3);
AddAssert("Check first item in group selected", () => Beatmap.Value.BeatmapInfo.MatchesOnlineID(groupIcon.Items.First().BeatmapInfo));
}
[Test]
public void TestChangeRulesetWhilePresentingScore()
{
BeatmapInfo getPresentBeatmap() => manager.GetAllUsableBeatmapSets().Where(s => !s.DeletePending).SelectMany(s => s.Beatmaps).First(b => b.Ruleset.OnlineID == 0);
BeatmapInfo getSwitchBeatmap() => manager.GetAllUsableBeatmapSets().Where(s => !s.DeletePending).SelectMany(s => s.Beatmaps).First(b => b.Ruleset.OnlineID == 1);
changeRuleset(0);
createSongSelect();
addRulesetImportStep(0);
addRulesetImportStep(1);
AddStep("present score", () =>
{
// this ruleset change should be overridden by the present.
Ruleset.Value = getSwitchBeatmap().Ruleset;
songSelect.PresentScore(new ScoreInfo
{
User = new APIUser { Username = "woo" },
BeatmapInfo = getPresentBeatmap(),
Ruleset = getPresentBeatmap().Ruleset
});
});
AddUntilStep("wait for results screen presented", () => !songSelect.IsCurrentScreen());
AddAssert("check beatmap is correct for score", () => Beatmap.Value.BeatmapInfo.MatchesOnlineID(getPresentBeatmap()));
AddAssert("check ruleset is correct for score", () => Ruleset.Value.OnlineID == 0);
}
[Test]
public void TestChangeBeatmapWhilePresentingScore()
{
BeatmapInfo getPresentBeatmap() => manager.GetAllUsableBeatmapSets().Where(s => !s.DeletePending).SelectMany(s => s.Beatmaps).First(b => b.Ruleset.OnlineID == 0);
BeatmapInfo getSwitchBeatmap() => manager.GetAllUsableBeatmapSets().Where(s => !s.DeletePending).SelectMany(s => s.Beatmaps).First(b => b.Ruleset.OnlineID == 1);
changeRuleset(0);
addRulesetImportStep(0);
addRulesetImportStep(1);
createSongSelect();
AddUntilStep("wait for selection", () => !Beatmap.IsDefault);
AddStep("present score", () =>
{
// this beatmap change should be overridden by the present.
Beatmap.Value = manager.GetWorkingBeatmap(getSwitchBeatmap());
songSelect.PresentScore(TestResources.CreateTestScoreInfo(getPresentBeatmap()));
});
AddUntilStep("wait for results screen presented", () => !songSelect.IsCurrentScreen());
AddAssert("check beatmap is correct for score", () => Beatmap.Value.BeatmapInfo.MatchesOnlineID(getPresentBeatmap()));
AddAssert("check ruleset is correct for score", () => Ruleset.Value.OnlineID == 0);
}
private void waitForInitialSelection()
{
AddUntilStep("wait for initial selection", () => !Beatmap.IsDefault);
AddUntilStep("wait for difficulty panels visible", () => songSelect.Carousel.ChildrenOfType<DrawableCarouselBeatmap>().Any());
}
private int getBeatmapIndex(BeatmapSetInfo set, BeatmapInfo info) => set.Beatmaps.IndexOf(info);
private int getCurrentBeatmapIndex() => getBeatmapIndex(songSelect.Carousel.SelectedBeatmapSet, songSelect.Carousel.SelectedBeatmapInfo);
private int getDifficultyIconIndex(DrawableCarouselBeatmapSet set, FilterableDifficultyIcon icon)
{
return set.ChildrenOfType<FilterableDifficultyIcon>().ToList().FindIndex(i => i == icon);
}
private void addRulesetImportStep(int id)
{
Live<BeatmapSetInfo> imported = null;
AddStep($"import test map for ruleset {id}", () => imported = importForRuleset(id));
// This is specifically for cases where the add is happening post song select load.
// For cases where song select is null, the assertions are provided by the load checks.
AddUntilStep("wait for imported to arrive in carousel", () => songSelect == null || songSelect.Carousel.BeatmapSets.Any(s => s.ID == imported?.ID));
}
private Live<BeatmapSetInfo> importForRuleset(int id) => manager.Import(TestResources.CreateTestBeatmapSetInfo(3, rulesets.AvailableRulesets.Where(r => r.OnlineID == id).ToArray()));
private void checkMusicPlaying(bool playing) =>
AddUntilStep($"music {(playing ? "" : "not ")}playing", () => music.IsPlaying == playing);
private void changeMods(params Mod[] mods) => AddStep($"change mods to {string.Join(", ", mods.Select(m => m.Acronym))}", () => SelectedMods.Value = mods);
private void changeRuleset(int id) => AddStep($"change ruleset to {id}", () => Ruleset.Value = rulesets.AvailableRulesets.First(r => r.OnlineID == id));
private void createSongSelect()
{
AddStep("create song select", () => LoadScreen(songSelect = new TestSongSelect()));
AddUntilStep("wait for present", () => songSelect.IsCurrentScreen());
AddUntilStep("wait for carousel loaded", () => songSelect.Carousel.IsAlive);
}
/// <summary>
/// Imports test beatmap sets to show in the carousel.
/// </summary>
/// <param name="difficultyCountPerSet">
/// The exact count of difficulties to create for each beatmap set.
/// A <see langword="null"/> value causes the count of difficulties to be selected randomly.
/// </param>
private void addManyTestMaps(int? difficultyCountPerSet = null)
{
AddStep("import test maps", () =>
{
var usableRulesets = rulesets.AvailableRulesets.Where(r => r.OnlineID != 2).ToArray();
for (int i = 0; i < 10; i++)
manager.Import(TestResources.CreateTestBeatmapSetInfo(difficultyCountPerSet, usableRulesets));
});
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
rulesets?.Dispose();
}
private class TestSongSelect : PlaySongSelect
{
public Action StartRequested;
public new Bindable<RulesetInfo> Ruleset => base.Ruleset;
public new FilterControl FilterControl => base.FilterControl;
public WorkingBeatmap CurrentBeatmap => Beatmap.Value;
public IWorkingBeatmap CurrentBeatmapDetailsBeatmap => BeatmapDetails.Beatmap;
public new BeatmapCarousel Carousel => base.Carousel;
public new void PresentScore(ScoreInfo score) => base.PresentScore(score);
protected override bool OnStart()
{
StartRequested?.Invoke();
return base.OnStart();
}
public int FilterCount;
protected override void ApplyFilterToCarousel(FilterCriteria criteria)
{
FilterCount++;
base.ApplyFilterToCarousel(criteria);
}
}
}
}
| |
// 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.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
using Xunit.Sdk;
namespace System.Diagnostics
{
/// <summary>Base class used for all tests that need to spawn a remote process.</summary>
public abstract partial class RemoteExecutorTestBase : FileCleanupTestBase
{
/// <summary>A timeout (milliseconds) after which a wait on a remote operation should be considered a failure.</summary>
public const int FailWaitTimeoutMilliseconds = 60 * 1000;
/// <summary>The exit code returned when the test process exits successfully.</summary>
public const int SuccessExitCode = 42;
/// <summary>The name of the test console app.</summary>
protected static readonly string TestConsoleApp = "RemoteExecutorConsoleApp.exe";
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Action method,
RemoteInvokeOptions options = null)
{
// There's no exit code to check
options = options ?? new RemoteInvokeOptions();
options.CheckExitCode = false;
return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<int> method,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<Task<int>> method,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg">The argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, Task<int>> method,
string arg,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, Task<int>> method,
string arg1, string arg2,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg">The argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, int> method,
string arg,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, int> method,
string arg1, string arg2,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="arg3">The third argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, string, int> method,
string arg1, string arg2, string arg3,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="arg3">The third argument to pass to the method.</param>
/// <param name="arg4">The fourth argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, string, string, int> method,
string arg1, string arg2, string arg3, string arg4,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="arg2">The second argument to pass to the method.</param>
/// <param name="arg3">The third argument to pass to the method.</param>
/// <param name="arg4">The fourth argument to pass to the method.</param>
/// <param name="arg5">The fifth argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
Func<string, string, string, string, string, int> method,
string arg1, string arg2, string arg3, string arg4, string arg5,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4, arg5 }, options);
}
/// <summary>Invokes the method from this assembly in another process using the specified arguments without performing any modifications to the arguments.</summary>
/// <param name="method">The method to invoke.</param>
/// <param name="args">The arguments to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvokeRaw(Delegate method, string unparsedArg,
RemoteInvokeOptions options = null)
{
return RemoteInvoke(GetMethodInfo(method), new[] { unparsedArg }, options, pasteArguments: false);
}
private static MethodInfo GetMethodInfo(Delegate d)
{
// RemoteInvoke doesn't support marshaling state on classes associated with
// the delegate supplied (often a display class of a lambda). If such fields
// are used, odd errors result, e.g. NullReferenceExceptions during the remote
// execution. Try to ward off the common cases by proactively failing early
// if it looks like such fields are needed.
if (d.Target != null)
{
// The only fields on the type should be compiler-defined (any fields of the compiler's own
// making generally include '<' and '>', as those are invalid in C# source). Note that this logic
// may need to be revised in the future as the compiler changes, as this relies on the specifics of
// actually how the compiler handles lifted fields for lambdas.
Type targetType = d.Target.GetType();
Assert.All(
targetType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fi => Assert.True(fi.Name.IndexOf('<') != -1, $"Field marshaling is not supported by {nameof(RemoteInvoke)}: {fi.Name}"));
}
return d.GetMethodInfo();
}
/// <summary>A cleanup handle to the Process created for the remote invocation.</summary>
public sealed class RemoteInvokeHandle : IDisposable
{
public RemoteInvokeHandle(Process process, RemoteInvokeOptions options, string assemblyName = null, string className = null, string methodName = null)
{
Process = process;
Options = options;
AssemblyName = assemblyName;
ClassName = className;
MethodName = methodName;
}
public Process Process { get; set; }
public RemoteInvokeOptions Options { get; private set; }
public string AssemblyName { get; private set; }
public string ClassName { get; private set; }
public string MethodName { get; private set; }
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
Assert.True(disposing, $"A test {AssemblyName}!{ClassName}.{MethodName} forgot to Dispose() the result of RemoteInvoke()");
if (Process != null)
{
// A bit unorthodox to do throwing operations in a Dispose, but by doing it here we avoid
// needing to do this in every derived test and keep each test much simpler.
try
{
Assert.True(Process.WaitForExit(Options.TimeOut),
$"Timed out after {Options.TimeOut}ms waiting for remote process {Process.Id}");
if (File.Exists(Options.ExceptionFile))
{
throw new RemoteExecutionException(File.ReadAllText(Options.ExceptionFile));
}
if (Options.CheckExitCode)
{
int expected = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Options.ExpectedExitCode : unchecked((sbyte)Options.ExpectedExitCode);
int actual = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Process.ExitCode : unchecked((sbyte)Process.ExitCode);
Assert.True(expected == actual, $"Exit code was {Process.ExitCode} but it should have been {Options.ExpectedExitCode}");
}
}
finally
{
if (File.Exists(Options.ExceptionFile))
{
File.Delete(Options.ExceptionFile);
}
// Cleanup
try { Process.Kill(); }
catch { } // ignore all cleanup errors
Process.Dispose();
Process = null;
}
}
}
~RemoteInvokeHandle()
{
// Finalizer flags tests that omitted the explicit Dispose() call; they must have it, or they aren't
// waiting on the remote execution
Dispose(disposing: false);
}
private sealed class RemoteExecutionException : XunitException
{
internal RemoteExecutionException(string stackTrace) : base("Remote process failed with an unhandled exception.", stackTrace) { }
}
}
}
/// <summary>Options used with RemoteInvoke.</summary>
public sealed class RemoteInvokeOptions
{
private bool _runAsSudo;
public bool Start { get; set; } = true;
public ProcessStartInfo StartInfo { get; set; } = new ProcessStartInfo();
public bool EnableProfiling { get; set; } = true;
public bool CheckExitCode { get; set; } = true;
public int TimeOut {get; set; } = RemoteExecutorTestBase.FailWaitTimeoutMilliseconds;
public int ExpectedExitCode { get; set; } = RemoteExecutorTestBase.SuccessExitCode;
public string ExceptionFile { get; } = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
public bool RunAsSudo
{
get
{
return _runAsSudo;
}
set
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
throw new PlatformNotSupportedException();
}
_runAsSudo = value;
}
}
}
}
| |
using System;
using NUnit.Framework;
namespace Xsd2Db.CommandLineParser.Test
{
/// <summary>
/// Summary description for ParameterAttributeTest.
/// </summary>
[TestFixture]
public class RegressionTest
{
/// <summary>
/// A boolean parameter bound to a field and having a default value
/// </summary>
[Parameter("defaultBooleanField", "dbf", "A boolean parameter bound to a field and having a default value", Default=true, IsRequired=false)] public bool DefaultBooleanField;
/// <summary>
/// A boolean parameter bound to a property and having a default value
/// </summary>
[Parameter("defaultBooleanProperty", "dbp", "A boolean parameter bound to a property and having a default value", Default=true, IsRequired=false)] public bool DefaultBooleanProperty;
/// <summary>
/// A boolean parameter bound to a field
/// </summary>
[Parameter("booleanField", "bf", "A boolean parameter bound to a field", IsCaseSensitive=false)] public bool BooleanField;
/// <summary>
/// A integer parameter bound to a field
/// </summary>
[Parameter("integerField", "if", "An integer parameter bound to a field")] public int IntegerField;
/// <summary>
/// A DateTime parameter bound to a field
/// </summary>
[Parameter("dateTimeField", "df", "A DateTime parameter bound to a field")] public DateTime DateTimeField;
/// <summary>
/// A string parameter bound to a field
/// </summary>
[Parameter("stringField", "sf", "A string parameter bound to a field")] public string StringField;
/// <summary>
/// A boolean parameter bound to a property
/// </summary>
[Parameter("booleanProperty", "bp", "A boolean parameter bound to a property", IsCaseSensitive=false)]
public bool BooleanProperty
{
get { return this.booleanValue; }
set { this.booleanValue = value; }
}
/// <summary>
/// The underlying value for <see cref="BooleanProperty"/>
/// </summary>
internal bool booleanValue;
/// <summary>
/// A integer parameter bound to a property
/// </summary>
[Parameter("integerProperty", "ip", "An integer parameter bound to a property")]
public int IntegerProperty
{
get { return this.integerValue; }
set { this.integerValue = value; }
}
/// <summary>
/// The underlying value for <see cref="IntegerProperty"/>
/// </summary>
internal int integerValue;
/// <summary>
/// A DateTime parameter bound to a property
/// </summary>
[Parameter("dateTimeProperty", "dp", "A DateTime parameter bound to a property")]
public DateTime DateTimeProperty
{
get { return this.dateTimeValue; }
set { this.dateTimeValue = value; }
}
/// <summary>
/// The underlying value for <see cref="DateTimeProperty"/>
/// </summary>
internal DateTime dateTimeValue;
/// <summary>
/// A string parameter bound to a property
/// </summary>
[Parameter("stringProperty", "sp", "A string parameter bound to a property")]
public string StringProperty
{
get { return this.stringValue; }
set { this.stringValue = value; }
}
/// <summary>
/// The underlying value for <see cref="StringProperty"/>
/// </summary>
internal string stringValue;
/// <summary>
/// An enumeration to used when testing enumeration properties
/// and fields.
/// </summary>
public enum Enumeration
{
/// <summary>
/// The initial value. All enum tests should validate that
/// the field/property does not remain at this value
/// </summary>
Initial,
/// <summary>
/// Some test value
/// </summary>
Value1,
/// <summary>
/// Some test value
/// </summary>
Value2,
/// <summary>
/// Some test value
/// </summary>
Value3,
/// <summary>
/// Some test value
/// </summary>
Value4
}
/// <summary>
/// An enumeration parameter bound to a field
/// </summary>
[Parameter("enumField", "ef", "An enumerated parameter bound to a field")] public Enumeration enumField;
/// <summary>
/// An enumeration parameter bound to a property
/// </summary>
[Parameter("enumProperty", "ep", "An enumerated parameter bound to a property")]
public Enumeration enumProperty
{
get { return this.enumValue; }
set { this.enumValue = value; }
}
/// <summary>
/// The underlying value for <see cref="enumProperty"/>
/// </summary>
internal Enumeration enumValue;
/// <summary>
/// Initialize all fields and properties to a known state.
/// </summary>
[SetUp]
public void SetUp()
{
this.DefaultBooleanField = false;
this.BooleanField = false;
this.IntegerField = 0;
this.StringField = String.Empty;
this.DateTimeField = DateTime.MinValue;
this.enumField = Enumeration.Initial;
this.DefaultBooleanProperty = this.DefaultBooleanField;
this.BooleanProperty = this.BooleanField;
this.IntegerProperty = this.IntegerField;
this.DateTimeProperty = this.DateTimeField;
this.StringProperty = this.StringField;
this.enumProperty = enumField;
}
/// <summary>
/// Ensure that the program name is parsed correctly.
/// </summary>
[Test]
public void ProgramNameText()
{
string text = HelperFunction.MakeCommandLine(String.Empty);
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
Assertion.Assert(
"The program name is incorrect",
c.ProgramName == HelperFunction.ApplicationName);
}
/// <summary>
/// Ensre that that the boolean field is set correctly
/// </summary>
[Test]
public void BooleanFieldTest_01()
{
string text = HelperFunction.MakeCommandLine("-booleanField=true");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.Assert(this.BooleanField);
}
/// <summary>
///
/// </summary>
[Test]
public void BooleanFieldTest_02()
{
string text = HelperFunction.MakeCommandLine("-bF=true");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.Assert(this.BooleanField);
}
/// <summary>
///
/// </summary>
[Test]
public void BooleanFieldTest_03()
{
string text = HelperFunction.MakeCommandLine("-booleanField='True'");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.Assert(this.BooleanField);
}
/// <summary>
///
/// </summary>
[Test]
public void BooleanFieldTest_04()
{
string text = HelperFunction.MakeCommandLine("--Bf:'Yes'");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.Assert(this.BooleanField);
}
/// <summary>
///
/// </summary>
[Test]
public void BooleanPropertyTest_01()
{
string text = HelperFunction.MakeCommandLine("-booleanProperty=true");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.Assert(this.BooleanProperty);
}
/// <summary>
/// Ensure that the boolean property is set using its alias if
/// 'true' is the argument value is supplied on the command line.
/// The alias uses different case, and the parameter is not case
/// sensitive.
/// </summary>
[Test]
public void BooleanPropertyTest_02()
{
string text = HelperFunction.MakeCommandLine("-bP=true");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.Assert(this.BooleanProperty);
}
/// <summary>
/// Ensure that the boolean property is set using its full name if
/// 'True' is the argument value is supplied on the command line.
/// </summary>
[Test]
public void BooleanPropertyTest_03()
{
string text = HelperFunction.MakeCommandLine("-booleanProperty='True'");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.Assert(this.BooleanProperty);
}
/// <summary>
/// Ensure that the boolean property is set using its alias if 'Yes'
/// is the argument value is supplied on the command line.
/// </summary>
[Test]
public void BooleanPropertyTest_04()
{
string text = HelperFunction.MakeCommandLine("--Bp:'Yes'");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.Assert(this.BooleanProperty);
}
/// <summary>
/// Ensure that the default value of the boolean field is set if
/// the matching argument is not supplied on the command line.
/// </summary>
[Test]
public void DefaultBooleanFieldTest()
{
string text = HelperFunction.MakeCommandLine("--someName:'SomeValue'");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.Assert(this.DefaultBooleanField);
}
/// <summary>
/// Ensure that the default value of the boolean property is set if
/// the matching argument is not supplied on the command line.
/// </summary>
[Test]
public void DefaultBooleanPropertyTest()
{
string text = HelperFunction.MakeCommandLine("--someName:'SomeValue'");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.Assert(this.DefaultBooleanProperty);
}
/// <summary>
/// Ensure that the enumeration field gets correctly set using
/// its full name.
/// </summary>
[Test]
public void EnumFieldTest_01()
{
string text = HelperFunction.MakeCommandLine("--enumField:'value1'");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.AssertEquals(
"Wrong enumeration value observed",
Enumeration.Value1,
this.enumField);
}
/// <summary>
/// Ensure that the enumeration field gets correctly set using
/// its alias.
/// </summary>
[Test]
public void EnumFieldTest_02()
{
string text = HelperFunction.MakeCommandLine("--ef:Value2");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.AssertEquals(
"Wrong enumeration value observed",
Enumeration.Value2,
this.enumField);
}
/// <summary>
/// Ensure that the enumeration property gets correctly set using
/// its full name even if the case used to specify the enumeration
/// value is different from the enumeration value (i.e., matching
/// should be not be case sensitive)
/// </summary>
[Test]
public void EnumPropertyTest_01()
{
string text = HelperFunction.MakeCommandLine("--enumProperty:\"vaLUE3\"");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.AssertEquals(
"Wrong enumeration value observed",
Enumeration.Value3,
this.enumProperty);
}
/// <summary>
/// Ensure that the enumeration property gets correctly set using
/// its alias even if the case used to specify the enumeration
/// value is different from the enumeration value (i.e., matching
/// should be not be case sensitive)
/// </summary>
[Test]
public void EnumPropertyTest_02()
{
string text = HelperFunction.MakeCommandLine("--ep:\"vALUe4\"");
CommandLine c = new CommandLine(text);
Assertion.Assert(
"The command line text failed to parse",
c.TextIsValid);
c.Bind(this);
c.Resolve();
Assertion.AssertEquals(
"Wrong enumeration value observed",
Enumeration.Value4,
this.enumProperty);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using PowerLib.System.Linq;
namespace PowerLib.System.Collections
{
public class PwrSortedList<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IAutoCapacitySupport, IStampSupport
{
private IList<T> _innerList;
private Comparison<T> _sortComparison;
private SortingOption _sortingOption;
#region Constructors
public PwrSortedList(Comparison<T> sortComparison, SortingOption sortingOption = SortingOption.None)
: this(new PwrList<T>(), sortComparison, sortingOption)
{
}
public PwrSortedList(int capacity, Comparison<T> sortComparison, SortingOption sortingOption = SortingOption.None)
: this(new PwrList<T>(capacity), sortComparison, sortingOption)
{
}
public PwrSortedList(IEnumerable<T> coll, Comparison<T> sortComparison, SortingOption sortingOption = SortingOption.None, bool readOnly = false)
: this(coll != null ? coll
.ToSortedPwrList(sortComparison, sortingOption)
.WithIf(list => readOnly, list => list.Restrict(CollectionRestrictions.ReadOnly)) : new PwrList<T>(), sortComparison, sortingOption)
{
}
public PwrSortedList(IComparer<T> sortComparer, SortingOption sortingOption = SortingOption.None)
: this(new PwrList<T>(), (sortComparer ?? Comparer<T>.Default).Compare, sortingOption)
{
}
public PwrSortedList(int capacity, IComparer<T> sortComparer, SortingOption sortingOption = SortingOption.None)
: this(new PwrList<T>(capacity), (sortComparer ?? Comparer<T>.Default).Compare, sortingOption)
{
}
public PwrSortedList(IEnumerable<T> coll, IComparer<T> sortComparer, SortingOption sortingOption = SortingOption.None, bool readOnly = false)
: this(coll != null ? coll
.ToSortedPwrList((sortComparer ?? Comparer<T>.Default).Compare, sortingOption)
.WithIf(list => readOnly, list => list.Restrict(CollectionRestrictions.ReadOnly)) : new PwrList<T>(),
(sortComparer != null ? sortComparer : Comparer<T>.Default).Compare, sortingOption)
{
}
protected PwrSortedList(IList<T> innerList, Comparison<T> sortComparison, SortingOption sortingOption = SortingOption.None)
{
if (innerList == null)
throw new ArgumentNullException("innerList");
if (sortComparison == null)
throw new ArgumentNullException("sortComparison");
_innerList = innerList;
_sortComparison = sortComparison;
_sortingOption = sortingOption;
}
#endregion
#region Instance properties
#region Internal properties
protected IList<T> InnerList
{
get
{
return _innerList;
}
}
protected Comparison<T> SortComparison
{
get
{
return _sortComparison;
}
}
protected SortingOption SortingOption
{
get
{
return _sortingOption;
}
}
#endregion
#region Public properties
public bool IsReadOnly
{
get
{
return InnerList.IsReadOnly;
}
}
public int Count
{
get
{
return InnerList.Count;
}
}
public T this[int index]
{
get
{
return InnerList[index];
}
set
{
if (!InnerList.SetSorted(index, value, SortComparison, SortingOption))
throw new InvalidOperationException("Cannot set item at specified position");
}
}
#endregion
#endregion
#region Instance methods
#region Manipulation methods
public void Clear()
{
InnerList.Clear();
}
public void Add(T item)
{
if (InnerList.AddSorted(item, SortComparison, SortingOption) < 0)
throw new ArgumentException("Duplicate item found in list.");
}
public void AddRange(IEnumerable<T> coll)
{
if (SortingOption == SortingOption.Unique)
{
var list = coll.ToSortedPwrList(SortComparison, SortingOption.Unique);
for (int i = 0, index = 0; i < list.Count; i++)
if ((index = InnerList.BinarySearch(t => SortComparison(t, list[i]), SortingOption)) >= 0)
throw new ArgumentException("Duplicate item found in list.");
coll = list;
}
foreach (var item in coll)
if (InnerList.AddSorted(item, SortComparison, SortingOption) < 0)
throw new InvalidOperationException("Duplicate item found in list.");
}
public void Insert(int index, T item)
{
if (!InnerList.InsertSorted(index, item, SortComparison, SortingOption))
throw new ArgumentException("Cannot insert item at specified position");
}
public bool Remove(T value)
{
int index = IndexOf(value);
if (index >= 0)
RemoveAt(index);
return (index >= 0);
}
public void RemoveAt(int index)
{
InnerList.RemoveAt(index);
}
public void RemoveRange(int index, int count)
{
InnerList.RemoveRange(index, count);
}
#endregion
#region Extraction methods
public void CopyTo(T[] array, int arrayIndex)
{
CopyTo(array, arrayIndex, 0, InnerList.Count);
}
public void CopyTo(T[] array, int arrayIndex, int index, int count)
{
InnerList.CopyTo(array, arrayIndex, index, count);
}
public T[] ToArray()
{
return ToArray(0, InnerList.Count);
}
public T[] ToArray(int index, int count)
{
T[] array = new T[count];
CopyTo(array, 0, index, count);
return array;
}
#endregion
#region Retrieval methods
public bool Match(Func<T, bool> match, bool all)
{
return Match(0, InnerList.Count, match, all);
}
public bool Match(int index, Func<T, bool> match, bool all)
{
return Match(index, InnerList.Count - index, match, all);
}
public bool Match(int index, int count, Func<T, bool> match, bool all)
{
return InnerList.Match(index, count, match, all);
}
public T Find(Func<T, bool> match)
{
return Find(0, InnerList.Count, match);
}
public T Find(int index, Func<T, bool> match)
{
return Find(index, InnerList.Count - index, match);
}
public T Find(int index, int count, Func<T, bool> match)
{
int i = InnerList.FindIndex(index, count, match);
return i >= 0 ? InnerList[i] : default(T);
}
public T FindLast(Func<T, bool> match)
{
return FindLast(0, InnerList.Count, match);
}
public T FindLast(int index, Func<T, bool> match)
{
return FindLast(index, InnerList.Count - index, match);
}
public T FindLast(int index, int count, Func<T, bool> match)
{
int i = InnerList.FindLastIndex(index, count, match);
return i >= 0 ? InnerList[i] : default(T);
}
public PwrList<T> FindAll(Func<T, bool> match)
{
return FindAll(0, InnerList.Count, match);
}
public PwrList<T> FindAll(int index, Func<T, bool> match)
{
return FindAll(index, InnerList.Count - index, match);
}
public PwrList<T> FindAll(int index, int count, Func<T, bool> match)
{
return new PwrList<T>(InnerList.FindAll(index, count, match), CollectionRestrictions.ReadOnly);
}
public int FindIndex(Func<T, bool> match)
{
return FindIndex(0, InnerList.Count, match);
}
public int FindIndex(int index, Func<T, bool> match)
{
return FindIndex(index, InnerList.Count - index, match);
}
public int FindIndex(int index, int count, Func<T, bool> match)
{
return InnerList.FindIndex(index, count, match);
}
public int FindLastIndex(Func<T, bool> match)
{
return FindLastIndex(0, InnerList.Count, match);
}
public int FindLastIndex(int index, Func<T, bool> match)
{
return FindLastIndex(index, InnerList.Count - index, match);
}
public int FindLastIndex(int index, int count, Func<T, bool> match)
{
return InnerList.FindLastIndex(index, count, match);
}
public PwrList<int> FindAllIndices(Func<T, bool> match)
{
return FindAllIndices(0, InnerList.Count, match);
}
public PwrList<int> FindAllIndices(int index, Func<T, bool> match)
{
return FindAllIndices(index, InnerList.Count - index, match);
}
public PwrList<int> FindAllIndices(int index, int count, Func<T, bool> match)
{
return new PwrList<int>(InnerList.FindAllIndices(index, count, match), CollectionRestrictions.ReadOnly);
}
public bool Contains(T value)
{
return Contains(value, 0, InnerList.Count);
}
public bool Contains(T value, int index)
{
return Contains(value, index, InnerList.Count - index);
}
public bool Contains(T value, int index, int count)
{
int i = InnerList.BinarySearch(index, count, t => SortComparison(t, value), SortingOption.First);
if (i >= 0)
for (; i < InnerList.Count && SortComparison(InnerList[i], value) == 0; i++)
if (EqualityComparer<T>.Default.Equals(InnerList[i], value))
return true;
return false;
}
public int IndexOf(T value)
{
return IndexOf(value, 0, InnerList.Count);
}
public int IndexOf(T value, int index)
{
return IndexOf(value, index, InnerList.Count - index);
}
public int IndexOf(T value, int index, int count)
{
int i = InnerList.BinarySearch(index, count, t => SortComparison(t, value), SortingOption.First);
if (i >= 0)
for (; i < InnerList.Count && SortComparison(InnerList[i], value) == 0; i++)
if (EqualityComparer<T>.Default.Equals(InnerList[i], value))
return i;
return -1;
}
public int LastIndexOf(T value)
{
return LastIndexOf(value, 0, InnerList.Count);
}
public int LastIndexOf(T value, int index)
{
return LastIndexOf(value, index, InnerList.Count - index);
}
public int LastIndexOf(T value, int index, int count)
{
int i = InnerList.BinarySearch(index, count, t => SortComparison(t, value), SortingOption.Last);
if (i >= 0)
for (; i >= 0 && SortComparison(InnerList[i], value) == 0; i--)
if (EqualityComparer<T>.Default.Equals(InnerList[i], value))
return i;
return -1;
}
public int BinarySearch(T value, SortingOption sortingOption = SortingOption.None)
{
return BinarySearch(value, 0, InnerList.Count, sortingOption);
}
public int BinarySearch(T value, int index, SortingOption sortingOption = SortingOption.None)
{
return BinarySearch(value, index, InnerList.Count - index, sortingOption);
}
public int BinarySearch(T value, int index, int count, SortingOption sortingOption = SortingOption.None)
{
return InnerList.BinarySearch(index, count, t => SortComparison(t, value), sortingOption);
}
#endregion
#endregion
#region Interface implementation
#region IEnumerable<T> implementation
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return InnerList.GetEnumerator();
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
return InnerList.GetEnumerator();
}
#endregion
#region ICapacitySupport
public void TrimExcess()
{
var capacitySupport = InnerList as ICapacitySupport;
if (capacitySupport == null)
throw new NotSupportedException();
capacitySupport.TrimExcess();
}
public float LoadFactor
{
get
{
var capacitySupport = InnerList as ICapacitySupport;
if (capacitySupport == null)
throw new NotSupportedException();
return capacitySupport.LoadFactor;
}
}
public float GrowFactor
{
get
{
IAutoCapacitySupport capacitySupport = InnerList as IAutoCapacitySupport;
if (capacitySupport == null)
throw new NotSupportedException();
return capacitySupport.GrowFactor;
}
set
{
IAutoCapacitySupport capacitySupport = InnerList as IAutoCapacitySupport;
if (capacitySupport == null)
throw new NotSupportedException();
capacitySupport.GrowFactor = value ;
}
}
public float TrimFactor
{
get
{
IAutoCapacitySupport capacitySupport = InnerList as IAutoCapacitySupport;
if (capacitySupport == null)
throw new NotSupportedException();
return capacitySupport.TrimFactor;
}
set
{
IAutoCapacitySupport capacitySupport = InnerList as IAutoCapacitySupport;
if (capacitySupport == null)
throw new NotSupportedException();
capacitySupport.TrimFactor = value ;
}
}
public bool AutoTrim
{
get
{
IAutoCapacitySupport capacitySupport = InnerList as IAutoCapacitySupport;
if (capacitySupport == null)
throw new NotSupportedException();
return capacitySupport.AutoTrim;
}
set
{
IAutoCapacitySupport capacitySupport = InnerList as IAutoCapacitySupport;
if (capacitySupport == null)
throw new NotSupportedException();
capacitySupport.AutoTrim = value ;
}
}
public int Capacity
{
get
{
ICapacitySupport capacitySupport = InnerList as ICapacitySupport;
if (capacitySupport == null)
throw new NotSupportedException();
return capacitySupport.Capacity;
}
set
{
ICapacitySupport capacitySupport = InnerList as ICapacitySupport;
if (capacitySupport == null)
throw new NotSupportedException();
capacitySupport.Capacity = value;
}
}
#endregion
#region IChangeStampSupport
int IStampSupport.Stamp
{
get
{
var stampSupport = InnerList as IStampSupport;
if (stampSupport == null)
throw new NotSupportedException();
return stampSupport.Stamp;
}
}
#endregion
#endregion
}
}
| |
#region Apache License
//
// 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.
//
#endregion
// .NET Compact Framework has no support for Marshal.StringToHGlobalAnsi
#if !NETCF
using System;
using System.Runtime.InteropServices;
using log4net.Core;
using log4net.Appender;
using log4net.Util;
using log4net.Layout;
namespace log4net.Appender
{
/// <summary>
/// Logs events to a local syslog service.
/// </summary>
/// <remarks>
/// <note>
/// This appender uses the POSIX libc library functions <c>openlog</c>, <c>syslog</c>, and <c>closelog</c>.
/// If these functions are not available on the local system then this appender will not work!
/// </note>
/// <para>
/// The functions <c>openlog</c>, <c>syslog</c>, and <c>closelog</c> are specified in SUSv2 and
/// POSIX 1003.1-2001 standards. These are used to log messages to the local syslog service.
/// </para>
/// <para>
/// This appender talks to a local syslog service. If you need to log to a remote syslog
/// daemon and you cannot configure your local syslog service to do this you may be
/// able to use the <see cref="RemoteSyslogAppender"/> to log via UDP.
/// </para>
/// <para>
/// Syslog messages must have a facility and and a severity. The severity
/// is derived from the Level of the logging event.
/// The facility must be chosen from the set of defined syslog
/// <see cref="SyslogFacility"/> values. The facilities list is predefined
/// and cannot be extended.
/// </para>
/// <para>
/// An identifier is specified with each log message. This can be specified
/// by setting the <see cref="Identity"/> property. The identity (also know
/// as the tag) must not contain white space. The default value for the
/// identity is the application name (from <see cref="SystemInfo.ApplicationFriendlyName"/>).
/// </para>
/// </remarks>
/// <author>Rob Lyon</author>
/// <author>Nicko Cadell</author>
public class LocalSyslogAppender : AppenderSkeleton
{
#region Enumerations
/// <summary>
/// syslog severities
/// </summary>
/// <remarks>
/// <para>
/// The log4net Level maps to a syslog severity using the
/// <see cref="LocalSyslogAppender.AddMapping"/> method and the <see cref="LevelSeverity"/>
/// class. The severity is set on <see cref="LevelSeverity.Severity"/>.
/// </para>
/// </remarks>
public enum SyslogSeverity
{
/// <summary>
/// system is unusable
/// </summary>
Emergency = 0,
/// <summary>
/// action must be taken immediately
/// </summary>
Alert = 1,
/// <summary>
/// critical conditions
/// </summary>
Critical = 2,
/// <summary>
/// error conditions
/// </summary>
Error = 3,
/// <summary>
/// warning conditions
/// </summary>
Warning = 4,
/// <summary>
/// normal but significant condition
/// </summary>
Notice = 5,
/// <summary>
/// informational
/// </summary>
Informational = 6,
/// <summary>
/// debug-level messages
/// </summary>
Debug = 7
};
/// <summary>
/// syslog facilities
/// </summary>
/// <remarks>
/// <para>
/// The syslog facility defines which subsystem the logging comes from.
/// This is set on the <see cref="Facility"/> property.
/// </para>
/// </remarks>
public enum SyslogFacility
{
/// <summary>
/// kernel messages
/// </summary>
Kernel = 0,
/// <summary>
/// random user-level messages
/// </summary>
User = 1,
/// <summary>
/// mail system
/// </summary>
Mail = 2,
/// <summary>
/// system daemons
/// </summary>
Daemons = 3,
/// <summary>
/// security/authorization messages
/// </summary>
Authorization = 4,
/// <summary>
/// messages generated internally by syslogd
/// </summary>
Syslog = 5,
/// <summary>
/// line printer subsystem
/// </summary>
Printer = 6,
/// <summary>
/// network news subsystem
/// </summary>
News = 7,
/// <summary>
/// UUCP subsystem
/// </summary>
Uucp = 8,
/// <summary>
/// clock (cron/at) daemon
/// </summary>
Clock = 9,
/// <summary>
/// security/authorization messages (private)
/// </summary>
Authorization2 = 10,
/// <summary>
/// ftp daemon
/// </summary>
Ftp = 11,
/// <summary>
/// NTP subsystem
/// </summary>
Ntp = 12,
/// <summary>
/// log audit
/// </summary>
Audit = 13,
/// <summary>
/// log alert
/// </summary>
Alert = 14,
/// <summary>
/// clock daemon
/// </summary>
Clock2 = 15,
/// <summary>
/// reserved for local use
/// </summary>
Local0 = 16,
/// <summary>
/// reserved for local use
/// </summary>
Local1 = 17,
/// <summary>
/// reserved for local use
/// </summary>
Local2 = 18,
/// <summary>
/// reserved for local use
/// </summary>
Local3 = 19,
/// <summary>
/// reserved for local use
/// </summary>
Local4 = 20,
/// <summary>
/// reserved for local use
/// </summary>
Local5 = 21,
/// <summary>
/// reserved for local use
/// </summary>
Local6 = 22,
/// <summary>
/// reserved for local use
/// </summary>
Local7 = 23
}
#endregion // Enumerations
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LocalSyslogAppender" /> class.
/// </summary>
/// <remarks>
/// This instance of the <see cref="LocalSyslogAppender" /> class is set up to write
/// to a local syslog service.
/// </remarks>
public LocalSyslogAppender()
{
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Message identity
/// </summary>
/// <remarks>
/// <para>
/// An identifier is specified with each log message. This can be specified
/// by setting the <see cref="Identity"/> property. The identity (also know
/// as the tag) must not contain white space. The default value for the
/// identity is the application name (from <see cref="SystemInfo.ApplicationFriendlyName"/>).
/// </para>
/// </remarks>
public string Identity
{
get { return m_identity; }
set { m_identity = value; }
}
/// <summary>
/// Syslog facility
/// </summary>
/// <remarks>
/// Set to one of the <see cref="SyslogFacility"/> values. The list of
/// facilities is predefined and cannot be extended. The default value
/// is <see cref="SyslogFacility.User"/>.
/// </remarks>
public SyslogFacility Facility
{
get { return m_facility; }
set { m_facility = value; }
}
#endregion // Public Instance Properties
/// <summary>
/// Add a mapping of level to severity
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Adds a <see cref="LevelSeverity"/> to this appender.
/// </para>
/// </remarks>
public void AddMapping(LevelSeverity mapping)
{
m_levelMapping.Add(mapping);
}
#region IOptionHandler Implementation
/// <summary>
/// Initialize the appender based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
public override void ActivateOptions()
{
base.ActivateOptions();
m_levelMapping.ActivateOptions();
string identString = m_identity;
if (identString == null)
{
// Set to app name by default
identString = SystemInfo.ApplicationFriendlyName;
}
// create the native heap ansi string. Note this is a copy of our string
// so we do not need to hold on to the string itself, holding on to the
// handle will keep the heap ansi string alive.
m_handleToIdentity = Marshal.StringToHGlobalAnsi(identString);
// open syslog
openlog(m_handleToIdentity, 1, m_facility);
}
#endregion // IOptionHandler Implementation
#region AppenderSkeleton Implementation
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes the event to a remote syslog daemon.
/// </para>
/// <para>
/// The format of the output will depend on the appender's layout.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
protected override void Append(LoggingEvent loggingEvent)
{
int priority = GeneratePriority(m_facility, GetSeverity(loggingEvent.Level));
string message = RenderLoggingEvent(loggingEvent);
// Call the local libc syslog method
// The second argument is a printf style format string
syslog(priority, "%s", message);
}
/// <summary>
/// Close the syslog when the appender is closed
/// </summary>
/// <remarks>
/// <para>
/// Close the syslog when the appender is closed
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
protected override void OnClose()
{
base.OnClose();
try
{
// close syslog
closelog();
}
catch(DllNotFoundException)
{
// Ignore dll not found at this point
}
if (m_handleToIdentity != IntPtr.Zero)
{
// free global ident
Marshal.FreeHGlobal(m_handleToIdentity);
}
}
/// <summary>
/// This appender requires a <see cref="AppenderSkeleton.Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="AppenderSkeleton.Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion // AppenderSkeleton Implementation
#region Protected Members
/// <summary>
/// Translates a log4net level to a syslog severity.
/// </summary>
/// <param name="level">A log4net level.</param>
/// <returns>A syslog severity.</returns>
/// <remarks>
/// <para>
/// Translates a log4net level to a syslog severity.
/// </para>
/// </remarks>
virtual protected SyslogSeverity GetSeverity(Level level)
{
LevelSeverity levelSeverity = m_levelMapping.Lookup(level) as LevelSeverity;
if (levelSeverity != null)
{
return levelSeverity.Severity;
}
//
// Fallback to sensible default values
//
if (level >= Level.Alert)
{
return SyslogSeverity.Alert;
}
else if (level >= Level.Critical)
{
return SyslogSeverity.Critical;
}
else if (level >= Level.Error)
{
return SyslogSeverity.Error;
}
else if (level >= Level.Warn)
{
return SyslogSeverity.Warning;
}
else if (level >= Level.Notice)
{
return SyslogSeverity.Notice;
}
else if (level >= Level.Info)
{
return SyslogSeverity.Informational;
}
// Default setting
return SyslogSeverity.Debug;
}
#endregion // Protected Members
#region Public Static Members
/// <summary>
/// Generate a syslog priority.
/// </summary>
/// <param name="facility">The syslog facility.</param>
/// <param name="severity">The syslog severity.</param>
/// <returns>A syslog priority.</returns>
private static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity)
{
return ((int)facility * 8) + (int)severity;
}
#endregion // Public Static Members
#region Private Instances Fields
/// <summary>
/// The facility. The default facility is <see cref="SyslogFacility.User"/>.
/// </summary>
private SyslogFacility m_facility = SyslogFacility.User;
/// <summary>
/// The message identity
/// </summary>
private string m_identity;
/// <summary>
/// Marshaled handle to the identity string. We have to hold on to the
/// string as the <c>openlog</c> and <c>syslog</c> APIs just hold the
/// pointer to the ident and dereference it for each log message.
/// </summary>
private IntPtr m_handleToIdentity = IntPtr.Zero;
/// <summary>
/// Mapping from level object to syslog severity
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
#endregion // Private Instances Fields
#region External Members
/// <summary>
/// Open connection to system logger.
/// </summary>
[DllImport("libc")]
private static extern void openlog(IntPtr ident, int option, SyslogFacility facility);
/// <summary>
/// Generate a log message.
/// </summary>
/// <remarks>
/// <para>
/// The libc syslog method takes a format string and a variable argument list similar
/// to the classic printf function. As this type of vararg list is not supported
/// by C# we need to specify the arguments explicitly. Here we have specified the
/// format string with a single message argument. The caller must set the format
/// string to <c>"%s"</c>.
/// </para>
/// </remarks>
[DllImport("libc", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
private static extern void syslog(int priority, string format, string message);
/// <summary>
/// Close descriptor used to write to system logger.
/// </summary>
[DllImport("libc")]
private static extern void closelog();
#endregion // External Members
#region LevelSeverity LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the syslog severity that is should be logged at.
/// </summary>
/// <remarks>
/// <para>
/// A class to act as a mapping between the level that a logging call is made at and
/// the syslog severity that is should be logged at.
/// </para>
/// </remarks>
public class LevelSeverity : LevelMappingEntry
{
private SyslogSeverity m_severity;
/// <summary>
/// The mapped syslog severity for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped syslog severity for the specified level
/// </para>
/// </remarks>
public SyslogSeverity Severity
{
get { return m_severity; }
set { m_severity = value; }
}
}
#endregion // LevelSeverity LevelMapping Entry
}
}
#endif
| |
//#define USE_ANALYTICS
//#define RUN_UNIT_TESTS
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Facebook.MiniJSON;
using SimpleJSON;
#if USE_ANALYTICS
using Analytics;
#endif
public struct GameMatchData
{
public bool ValidMatchData { get; set; }
public bool MatchComplete { get; set; }
public int MatchType { get; set; }
public int MatchRound { get; set; }
public int MatchScore { get; set; }
public int MatchMaxSpeed { get; set; }
public string TournamentID { get; set; }
public string MatchID { get; set; }
public string YourNickname { get; set; }
public string YourAvatarURL { get; set; }
public string TheirNickname { get; set; }
public string TheirAvatarURL { get; set; }
}
public enum SocialPost
{
NONE,
INVITE,
SHARE
}
public class FuelHandler : MonoBehaviour
{
#if USE_ANALYTICS
[Header("Flurry Settings")]
[SerializeField] private string _iosApiKey = "RMD3XX7P4FY999T2JR9X";
[SerializeField] private string _androidApiKey = "JC6T8PMDXXD7524RRN8K";
IAnalytics flurryService;
#endif
public static FuelHandler Instance { get; private set; }
#if PROPELLER_SDK
private fuelSDKListener m_listener;
#endif
private GameMatchData m_matchData;
private bool useFaceBook;
private bool useFuelCompete;
private SocialPost socialPost;
private Dictionary<string, string> socialPostData;
public string fbname;
public string fbfirstname;//use this as nickname for now
public string fbemail;
public string fbgender;
public const int MATCH_TYPE_SINGLE = 0;
public const int MATCH_TYPE_MULTI = 1;
public float GearFriction { get; set; }
public int GearShapeType { get; set; }
public int GameTime { get; set; }
public int ShowDebug { get; set; }
public int FBIcon { get; set; }
public string Split1Name { get; set; }
public GameMatchData getMatchData()
{
return m_matchData;
}
/*
-----------------------------------------------------
Awake
-----------------------------------------------------
*/
void Awake ()
{
Debug.Log ("Awake");
if (Instance != null && Instance != this)
{
//destroy other instances
Destroy (gameObject);
}
else if( Instance == null )
{
#if USE_ANALYTICS
flurryService = Flurry.Instance;
//AssertNotNull(service, "Unable to create Flurry instance!", this);
//Assert(!string.IsNullOrEmpty(_iosApiKey), "_iosApiKey is empty!", this);
//Assert(!string.IsNullOrEmpty(_androidApiKey), "_androidApiKey is empty!", this);
flurryService.StartSession(_iosApiKey, _androidApiKey);
#endif
#if PROPELLER_SDK
m_listener = new fuelSDKListener ();
if(m_listener == null)
{
throw new Exception();
}
#endif
m_matchData = new GameMatchData ();
m_matchData.ValidMatchData = false;
m_matchData.MatchComplete = false;
socialPost = SocialPost.NONE;
socialPostData = null;
useFaceBook = true;
useFuelCompete = true;
if(useFaceBook)
{
Debug.Log ("FB.Init");
FB.Init(SetInit, OnHideUnity);
}
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
/*
-----------------------------------------------------
Start
-----------------------------------------------------
*/
void Start ()
{
Debug.Log ("Start");
SetLanguageLocale ();
#if PROPELLER_SDK
// enable push notifications
PropellerSDK.EnableNotification ( PropellerSDK.NotificationType.push );
// disable local notifications
//PropellerSDK.DisableNotification ( PropellerSDK.NotificationType.local );
// validate enabled notifications - result is false since local notifications are disabled
bool fuelEnabled = PropellerSDK.IsNotificationEnabled( PropellerSDK.NotificationType.all );
if (fuelEnabled)
{
Debug.Log ("fuelEnabled NotificationEnabled!");
}
#endif
GearFriction = 0.98f;
GearShapeType = 5;
GameTime = 7;
ShowDebug = 0;
FBIcon = 0;
Split1Name = "none";
//get stored dynamic values
if (PlayerPrefs.HasKey ("gearfriction")) {
GearFriction = PlayerPrefs.GetFloat("gearfriction");
}
if (PlayerPrefs.HasKey ("geartype")) {
GearShapeType = PlayerPrefs.GetInt("geartype");
}
if (PlayerPrefs.HasKey ("gametime")) {
GameTime = PlayerPrefs.GetInt("gametime");
}
if (PlayerPrefs.HasKey ("showdebug")) {
ShowDebug = PlayerPrefs.GetInt("showdebug");
}
if (PlayerPrefs.HasKey ("fbicon")) {
FBIcon = PlayerPrefs.GetInt("fbicon");
}
if (PlayerPrefs.HasKey ("splitgroup")) {
Split1Name = PlayerPrefs.GetString("splitgroup");
}
if (PlayerPrefs.HasKey ("numLaunches"))
{
int numLaunches = PlayerPrefs.GetInt ("numLaunches");
numLaunches++;
PlayerPrefs.SetInt("numLaunches", numLaunches);
}
setUserConditions ();
}
void OnApplicationPause(bool paused)
{
// application entering background
if (paused)
{
#if UNITY_IOS
UnityEngine.iOS.NotificationServices.ClearLocalNotifications ();
UnityEngine.iOS.NotificationServices.ClearRemoteNotifications ();
#endif
}
}
/*
-----------------------------------------------------
Update
-----------------------------------------------------
*/
void Update ()
{
}
/*
-----------------------------------------------------
Access to mainmenu this pointer
-----------------------------------------------------
*/
private InitMainMenu getMainMenuClass()
{
GameObject _mainmenu = GameObject.Find("InitMainMenu");
if (_mainmenu != null) {
InitMainMenu _mainmenuScript = _mainmenu.GetComponent<InitMainMenu> ();
if(_mainmenuScript != null) {
return _mainmenuScript;
}
throw new Exception();
}
throw new Exception();
}
/*
-----------------------------------------------------
Launch Routines
-----------------------------------------------------
*/
private void LaunchDashBoard()
{
Debug.Log ("LaunchDashBoard");
#if PROPELLER_SDK
NotificationCenter.DefaultCenter.PostNotification (getMainMenuClass(), "AddTransOverlay");
PropellerSDK.Launch (m_listener);
#endif
}
public bool tryLaunchFuelSDK()
{
Debug.Log ("tryLaunchFuelSDK");
if (m_matchData.MatchComplete == true && m_matchData.MatchType == MATCH_TYPE_MULTI)
{
m_matchData.MatchComplete = false;
LaunchDashBoard();
return true;
}
return false;
}
public void launchSinglePlayerGame()
{
m_matchData.MatchType = MATCH_TYPE_SINGLE;
m_matchData.ValidMatchData = false;
NotificationCenter.DefaultCenter.PostNotification (getMainMenuClass(), "LaunchGamePlay");
}
public void LaunchMultiplayerGame(Dictionary<string, string> matchResult)
{
m_matchData.MatchType = MATCH_TYPE_MULTI;
m_matchData.ValidMatchData = true;
m_matchData.TournamentID = matchResult ["tournamentID"];
m_matchData.MatchID = matchResult ["matchID"];
// extract the params data
string paramsJSON = matchResult ["paramsJSON"];
JSONNode json = JSONNode.Parse (paramsJSON);
m_matchData.MatchRound = json ["round"].AsInt;
JSONClass you = json ["you"].AsObject;
m_matchData.YourNickname = you ["name"];
m_matchData.YourAvatarURL = you ["avatar"];
JSONClass them = json ["them"].AsObject;
m_matchData.TheirNickname = them ["name"];
m_matchData.TheirAvatarURL = them ["avatar"];
Debug.Log ( "__LaunchMultiplayerGame__" + "\n" +
"ValidMatchData = " + m_matchData.ValidMatchData + "\n" +
"TournamentID = " + m_matchData.TournamentID + "\n" +
"MatchID = " + m_matchData.MatchID + "\n" +
"MatchRound = " + m_matchData.MatchRound + "\n" +
"adsAllowed = " + "\n" +
"fairPlay = " + "\n" +
"YourNickname = " + m_matchData.YourNickname + "\n" +
"YourAvatarURL = " + m_matchData.YourAvatarURL + "\n" +
"TheirNickname = " + m_matchData.TheirNickname + "\n" +
"TheirAvatarURL = " + m_matchData.TheirAvatarURL + "\n"
);
m_matchData.MatchComplete = false;
NotificationCenter.DefaultCenter.PostNotification (getMainMenuClass(), "LaunchGamePlay");
}
private void sendMatchResult (long score)
{
Debug.Log ("sendMatchResult");
long visualScore = score;
Dictionary<string, object> matchResult = new Dictionary<string, object> ();
matchResult.Add ("tournamentID", m_matchData.TournamentID);
matchResult.Add ("matchID", m_matchData.MatchID);
matchResult.Add ("score", m_matchData.MatchScore);
string visualScoreStr = visualScore.ToString() + " : " + m_matchData.MatchMaxSpeed.ToString() + " mps";
matchResult.Add ("visualScore", visualScoreStr);
#if PROPELLER_SDK
PropellerSDK.SubmitMatchResult (matchResult);
#endif
}
//not currently being used
private void sendCustomMatchResult (long score, float visualScore)
{
Debug.Log ("sendCustomMatchResult");
// construct custom leader board score currency dictionary for auxScore1
Dictionary<string, object> auxScore1Currency = new Dictionary<string, object> ();
auxScore1Currency.Add ("id", "visualScore");
auxScore1Currency.Add ("score", visualScore);
auxScore1Currency.Add ("visualScore", visualScore.ToString ());
// construct array of custom leader board score currencies
List<object> currencies = new List<object> ();
currencies.Add (auxScore1Currency);
// construct match data dictionary
Dictionary<string, object> matchData = new Dictionary<string, object> ();
matchData.Add ("currencies", currencies);
Dictionary<string, object> matchResult = new Dictionary<string, object> ();
matchResult.Add ("tournamentID", m_matchData.TournamentID);
matchResult.Add ("matchID", m_matchData.MatchID);
matchResult.Add ("score", m_matchData.MatchScore);
matchResult.Add ("matchData", matchData);
#if PROPELLER_SDK
PropellerSDK.SubmitMatchResult (matchResult);
NotificationCenter.DefaultCenter.PostNotification (getMainMenuClass(), "AddTransOverlay");
PropellerSDK.Launch (m_listener);
#endif
}
public void launchPropeller ()
{
if (useFuelCompete == false)
{
return;
}
Debug.Log ("launchPropeller");
#if PROPELLER_SDK
if (m_listener == null)
{
throw new Exception();
}
NotificationCenter.DefaultCenter.PostNotification (getMainMenuClass(), "AddTransOverlay");
PropellerSDK.Launch (m_listener);
#endif
}
public void updateLoginText ()
{
GameObject gameObj = GameObject.Find ("LoginStatusText");
if (gameObj != null)
{
if (FB.IsLoggedIn) {
if (gameObj) {
TextMesh tmesh = (TextMesh)gameObj.GetComponent (typeof(TextMesh));
tmesh.text = "LogOut";
}
} else {
if (gameObj) {
TextMesh tmesh = (TextMesh)gameObj.GetComponent (typeof(TextMesh));
tmesh.text = "Log In";
}
}
}
}
public void SetMatchScore(int scoreValue, int speedValue)
{
Debug.Log ("SetMatchScore = " + scoreValue);
m_matchData.MatchScore = scoreValue;
m_matchData.MatchMaxSpeed = speedValue;
//hmmm, better clean up this check
if (m_matchData.ValidMatchData == true)
{
m_matchData.MatchComplete = true;
}
//timer has run out. this is the earliest the score can be set
//early score reporting
sendMatchResult (m_matchData.MatchScore);
}
/*
-----------------------------------------------------
Challenge Counts
-----------------------------------------------------
*/
public void SyncChallengeCounts ()
{
if (useFuelCompete == false) {
return;
}
#if PROPELLER_SDK
PropellerSDK.SyncChallengeCounts ();
#endif
}
public void OnPropellerSDKChallengeCountUpdated (string count)
{
int countValue;
if (!int.TryParse(count, out countValue)) {
return;
}
Debug.Log ("OnPropellerSDKChallengeCountUpdated : countValue = " + countValue);
Hashtable ccTable = new Hashtable();
ccTable.Add("cc", countValue);
getMainMenuClass().RefreshChallengeCount(ccTable);
//NotificationCenter.DefaultCenter.PostNotification (getMainMenuClass(), "RefreshChallengeCount", ccTable );
}
/*
-----------------------------------------------------
Tournament Info
-----------------------------------------------------
*/
public void SyncTournamentInfo ()
{
if (useFuelCompete == false)
{
return;
}
#if PROPELLER_SDK
PropellerSDK.SyncTournamentInfo ();
#endif
}
public void OnPropellerSDKTournamentInfo (Dictionary<string, string> tournamentInfo)
{
Debug.Log ("OnPropellerSDKTournamentInfo");
if ((tournamentInfo == null) || (tournamentInfo.Count == 0))
{
Debug.Log ("....no tournaments currently running");
}
else
{
Debug.Log ("name");
string tournyname = tournamentInfo["name"];
Debug.Log ("campaignName");
string campaignName = tournamentInfo["campaignName"];
Debug.Log ("startDate");
string startDate = tournamentInfo["startDate"];
Debug.Log ("endDate");
string endDate = tournamentInfo["endDate"];
Debug.Log ("logo");
string logo = tournamentInfo["logo"];
Debug.Log
(
"*** TournamentInfo ***" + "\n" +
"tournyname = " + tournyname + "\n" +
"campaignName = " + campaignName + "\n" +
"startDate = " + startDate + "\n" +
"endDate = " + endDate + "\n" +
"logo = " + logo + "\n"
);
Hashtable tournyTable = new Hashtable();
tournyTable.Add("running", true);
tournyTable.Add("tournyname", tournyname);
tournyTable.Add("startDate", startDate);
tournyTable.Add("endDate", endDate);
getMainMenuClass().RefreshTournamentInfo(tournyTable);
//notification not passing hashtable properly (runtime error)
//NotificationCenter.DefaultCenter.PostNotification (getMainMenuClass(), "RefreshTournamentInfo", tournyTable );
}
}
/*
-----------------------------------------------------
Virtual Goods
-----------------------------------------------------
*/
public void SyncVirtualGoods ()
{
if (useFuelCompete == false)
{
return;
}
#if RUN_UNIT_TESTS
VirtualGoodUnitTest ();
#endif
#if PROPELLER_SDK
PropellerSDK.SyncVirtualGoods ();
#endif
}
public void OnPropellerSDKVirtualGoodList (Dictionary<string, object> virtualGoodInfo)
{
string transactionId = (string) virtualGoodInfo["transactionID"];
List<string> virtualGoods = (List<string>) virtualGoodInfo["virtualGoods"];
Debug.Log ("OnPropellerSDKVirtualGoodList: transactionId = " + transactionId);
Hashtable goodsTable = new Hashtable();
goodsTable["addGold"] = 0;
goodsTable["addOil"] = 0;
goodsTable["showTrophy"] = 0;
bool virtualGoodsTaken = false;
foreach (string vg in virtualGoods)
{
Debug.Log (":virtual good = " + vg);
if(vg == "golddrop")
{
goodsTable["addGold"] = 2;
virtualGoodsTaken = true;
}
else if(vg == "oildrop")
{
goodsTable["addOil"] = 2;
virtualGoodsTaken = true;
}
else if(vg == "trophydrop")
{
goodsTable["showTrophy"] = 1;
virtualGoodsTaken = true;
}
}
if(virtualGoodsTaken == true) {
getMainMenuClass().RefreshVirtualGoods(goodsTable);
//NotificationCenter.DefaultCenter.PostNotification (getMainMenuClass(), "RefreshVirtualGoods", goodsTable);
}
#if PROPELLER_SDK
// Acknowledge the receipt of the virtual goods list
PropellerSDK.AcknowledgeVirtualGoods(transactionId, true);
#endif
}
public void OnPropellerSDKVirtualGoodRollback (string transactionId)
{
Debug.Log ("OnPropellerSDKVirtualGoodRollback");
// Rollback the virtual good transaction for the given transaction ID
}
/*
---------------------------------------------------------------------
Face Book Unity Plugin
---------------------------------------------------------------------
*/
public void LoginButtonPressed()
{
if (useFaceBook == false)
{
return;
}
trySocialLogin (false);
}
public void LogoutButtonPressed()
{
/*
if (useFaceBook == false)
{
return;
}
if (FB.IsLoggedIn)
{
Debug.Log("LogoutButtonPressed: LOGGING OUT!");
FB.Logout();
}
*/
}
void LoginCallback(FBResult result)
{
Debug.Log("LoginCallback");
if (!FB.IsLoggedIn) {
if (result.Error != null) {
Debug.Log ("LoginCallback - login request failed: " + result.Error);
} else {
Debug.Log ("LoginCallback - login request cancelled");
}
#if PROPELLER_SDK
PropellerSDK.SdkSocialLoginCompleted(null);
#endif
if (socialPost != SocialPost.NONE) {
#if PROPELLER_SDK
switch (socialPost) {
case SocialPost.INVITE:
PropellerSDK.SdkSocialInviteCompleted ();
break;
case SocialPost.SHARE:
PropellerSDK.SdkSocialShareCompleted ();
break;
}
#endif
socialPost = SocialPost.NONE;
socialPostData = null;
}
return;
}
OnLoggedIn ();
}
void OnLoggedIn()
{
Debug.Log("OnLoggedIn");
FB.API("me?fields=name,email,gender,first_name", Facebook.HttpMethod.GET, UserCallBack);
}
void UserCallBack(FBResult result)
{
Debug.Log("UserCallBack");
if (result.Error != null) {
Debug.Log("UserCallBack - user graph request failed: " + result.Error + " - " + result.Text);
#if PROPELLER_SDK
PropellerSDK.SdkSocialLoginCompleted (null);
#endif
if (socialPost != SocialPost.NONE) {
#if PROPELLER_SDK
switch (socialPost) {
case SocialPost.INVITE:
PropellerSDK.SdkSocialInviteCompleted ();
break;
case SocialPost.SHARE:
PropellerSDK.SdkSocialShareCompleted ();
break;
}
#endif
socialPost = SocialPost.NONE;
socialPostData = null;
}
return;
}
string get_data = result.Text;
var dict = Json.Deserialize(get_data) as IDictionary;
fbname = dict ["name"].ToString();
fbemail = dict ["email"].ToString();
fbgender = dict ["gender"].ToString();
fbfirstname = dict ["first_name"].ToString();
PushFBDataToFuel ();
if (socialPost != SocialPost.NONE) {
switch (socialPost) {
case SocialPost.INVITE:
onSocialInviteClicked (socialPostData);
break;
case SocialPost.SHARE:
onSocialShareClicked (socialPostData);
break;
}
}
}
public void trySocialLogin(bool allowCache)
{
Debug.Log("trySocialLogin");
if (FB.IsLoggedIn) {
if (allowCache == true) {
PushFBDataToFuel ();
return;
}
FB.Logout ();
}
FB.Login("public_profile,email,publish_actions", LoginCallback);
}
public void PushFBDataToFuel()
{
Debug.Log("PushFBDataToFuel");
string provider = "facebook";
string email = fbemail;
string id = FB.UserId;
string token = FB.AccessToken;
DateTime expireDate = FB.AccessTokenExpiresAt;
string nickname = fbfirstname;//not available from FB using first name
string name = fbname;
string gender = fbgender;
Dictionary<string, string> loginInfo = null;
loginInfo = new Dictionary<string, string> ();
loginInfo.Add ("provider", provider);
loginInfo.Add ("email", email);
loginInfo.Add ("id", id);
loginInfo.Add ("token", token);
loginInfo.Add ("nickname", nickname);
loginInfo.Add ("name", name);
loginInfo.Add ("gender", gender);
Debug.Log
(
"*** loginInfo ***" + "\n" +
"provider = " + loginInfo ["provider"].ToString () + "\n" +
"email = " + loginInfo ["email"].ToString () + "\n" +
"id = " + loginInfo ["id"].ToString () + "\n" +
"token = " + loginInfo ["token"].ToString () + "\n" +
"nickname = " + loginInfo ["nickname"].ToString () + "\n" +
"name = " + loginInfo ["name"].ToString () + "\n" +
"gender = " + loginInfo ["gender"].ToString () + "\n" +
"expireDate = " + expireDate.ToLongDateString ()
);
#if PROPELLER_SDK
PropellerSDK.SdkSocialLoginCompleted (loginInfo);
#endif
}
/*
-----------------------------------------------------
FaceBook Init - private
-----------------------------------------------------
*/
private void SetInit()
{
Debug.Log("Facebook SetInit");
if (FB.IsLoggedIn)
{
Debug.Log ("....Already logged in");
OnLoggedIn ();
}
}
private void OnHideUnity(bool isGameShown)
{
Debug.Log("Facebook OnHideUnity");
if (!isGameShown)
{
// pause the game - we will need to hide
Time.timeScale = 0;
}
else
{
// start the game back up - we're getting focus again
Time.timeScale = 1;
}
}
/*
-----------------------------------------------------
FaceBook Invite
-----------------------------------------------------
*/
public void onSocialInviteClicked(Dictionary<string, string> inviteInfo)
{
Debug.Log("onSocialInviteClicked");
/*
string message,
string[] to = null,
List<object> filters = null,
string[] excludeIds = null,
int? maxRecipients = null,
string data = "",
string title = "",
FacebookDelegate callback = null)
*/
if (FB.IsLoggedIn)
{
FB.AppRequest (
inviteInfo ["long"],
null,
null,
null,
null,
null,
inviteInfo ["subject"],
appRequestCallback);
}
else
{
if (socialPost != SocialPost.NONE) {
socialPost = SocialPost.NONE;
socialPostData = null;
#if PROPELLER_SDK
PropellerSDK.SdkSocialInviteCompleted ();
#endif
return;
}
socialPost = SocialPost.INVITE;
socialPostData = inviteInfo;
trySocialLogin (false);
}
}
private void appRequestCallback (FBResult result)
{
Debug.Log("appRequestCallback");
if (result.Error != null) {
Debug.Log ("appRequestCallback - invite request failed: " + result.Error);
} else {
var responseObject = Json.Deserialize(result.Text) as Dictionary<string, object>;
object obj = null;
if (responseObject.TryGetValue ("cancelled", out obj)) {
Debug.Log("appRequestCallback - invite request cancelled");
} else if (responseObject.TryGetValue ("request", out obj)) {
Debug.Log("appRequestCallback - invite request sent");
}
}
#if PROPELLER_SDK
PropellerSDK.SdkSocialInviteCompleted();
#endif
}
/*
-----------------------------------------------------
FaceBook Share
-----------------------------------------------------
*/
public void onSocialShareClicked(Dictionary<string, string> shareInfo)
{
Debug.Log("onSocialShareClicked");
/*
string toId = "",
string link = "",
string linkName = "",
string linkCaption = "",
string linkDescription = "",
string picture = "",
string mediaSource = "",
string actionName = "",
string actionLink = "",
string reference = "",
Dictionary<string, string[]> properties = null,
FacebookDelegate callback = null)
*/
if (FB.IsLoggedIn)
{
FB.Feed (
FB.UserId,
shareInfo ["link"],
shareInfo ["subject"],
shareInfo ["short"],
shareInfo ["long"],
shareInfo ["picture"],
null,
null,
null,
null,
null,
appFeedCallback);
}
else
{
if (socialPost != SocialPost.NONE) {
socialPost = SocialPost.NONE;
socialPostData = null;
#if PROPELLER_SDK
PropellerSDK.SdkSocialShareCompleted ();
#endif
return;
}
socialPost = SocialPost.SHARE;
socialPostData = shareInfo;
trySocialLogin (false);
}
}
private void appFeedCallback (FBResult result)
{
Debug.Log("appFeedCallback");
if (result.Error != null) {
Debug.Log ("appFeedCallback - share request failed: " + result.Error);
} else {
var responseObject = Json.Deserialize(result.Text) as Dictionary<string, object>;
object obj = null;
if (responseObject.TryGetValue ("cancelled", out obj)) {
Debug.Log("appFeedCallback - share request cancelled");
} else if (responseObject.TryGetValue ("request", out obj)) {
Debug.Log("appFeedCallback - share request sent");
}
}
#if PROPELLER_SDK
PropellerSDK.SdkSocialShareCompleted();
#endif
}
/*
---------------------------------------------------------------------
Fuel Dynamics
---------------------------------------------------------------------
*/
private int getNumLaunches ()
{
int numLaunches = 0;
if (PlayerPrefs.HasKey ("numLaunches"))
{
numLaunches = PlayerPrefs.GetInt ("numLaunches");
}
Debug.Log ("....numLaunches = " + numLaunches);
return numLaunches;
}
private int getNumSessions ()
{
int numSessions = 0;
if (PlayerPrefs.HasKey ("numSessions"))
{
numSessions = PlayerPrefs.GetInt ("numSessions");
}
Debug.Log ("....numSessions = " + numSessions);
return numSessions;
}
private int getUserAge ()
{
TimeSpan span = DateTime.Now.Subtract (new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
int _currentTimeStamp = (int)span.TotalSeconds;
int _seconds = 0;
if (PlayerPrefs.HasKey ("installTimeStamp"))
{
int _installTimeStamp = PlayerPrefs.GetInt ("installTimeStamp");
_seconds = _currentTimeStamp - _installTimeStamp;
}
int userAge = _seconds / 86400;
Debug.Log ("....userAge = " + userAge + " <--- " + _seconds + "/ 86400");
return userAge;
}
public void setUserConditions ()
{
Debug.Log ("setUserConditions");
String isTablet = "FALSE";
if( isDeviceTablet() == true) {
isTablet = "TRUE";
}
int userAge = getUserAge ();
int numLaunches = getNumLaunches ();
int numSessions = getNumSessions ();
Dictionary<string, string> conditions = new Dictionary<string, string> ();
//required
conditions.Add ("userAge", userAge.ToString());
conditions.Add ("numSessions", numSessions.ToString());
conditions.Add ("numLaunches", numLaunches.ToString());
conditions.Add ("isTablet", isTablet);
conditions.Add ("gameVersion", "1.0.2");
//standardized
conditions.Add ("orientation", "portrait");
conditions.Add ("daysSinceFirstPayment", "-1");
conditions.Add ("daysSinceLastPayment", "-1");
conditions.Add ("language", "en");
conditions.Add ("gender", "female");
conditions.Add ("age", "16");
//non standardized
#if PROPELLER_SDK
PropellerSDK.SetUserConditions (conditions);
#endif
Debug.Log
(
"*** conditions ***" + "\n" +
"userAge = " + userAge.ToString() + "\n" +
"numSessions = " + numSessions.ToString() + "\n" +
"numLaunches = " + numLaunches.ToString() + "\n" +
"isTablet = " + isTablet + "\n" +
"orientation = " + "portrait" + "\n" +
"daysSinceFirstPayment = " + "-1" + "\n" +
"daysSinceLastPayment = " + "-1" + "\n" +
"language = " + "en" + "\n" +
"gender = " + "female" + "\n" +
"age = " + "16" + "\n" +
"gameVersion = " + "1.0.2"
);
}
public void syncUserValues()
{
#if PROPELLER_SDK
PropellerSDK.SyncUserValues();
#endif
}
public void OnPropellerSDKUserValues (Dictionary<string, string> userValuesInfo)
{
Debug.Log("OnPropellerSDKUserValues");
//Game Values - defined in the CSV
String _friction = "friction";
String _geartype = "geartype";
String _gametime = "gametime";
String _showdebug = "showdebug";
String _fbicon = "fbicon";
String _split1name = "split1name";
string value;
if (userValuesInfo.TryGetValue (_friction, out value)) {
GearFriction = float.Parse (value.ToString ());
} else {
Debug.Log("friction not found in userValueInfo");
}
if (userValuesInfo.TryGetValue (_geartype, out value)) {
GearShapeType = int.Parse(value.ToString());
} else {
Debug.Log("friction not found in userValueInfo");
}
if (userValuesInfo.TryGetValue (_gametime, out value)) {
GameTime = int.Parse(value.ToString());
} else {
Debug.Log("friction not found in userValueInfo");
}
if (userValuesInfo.TryGetValue (_showdebug, out value)) {
ShowDebug = int.Parse(value.ToString());
} else {
Debug.Log("showdebug not found in userValueInfo");
}
if (userValuesInfo.TryGetValue (_fbicon, out value)) {
FBIcon = int.Parse(value.ToString());
} else {
Debug.Log("fbicon not found in userValueInfo");
}
if (userValuesInfo.TryGetValue (_split1name, out value)) {
Split1Name = value.ToString();
} else {
Debug.Log("split1name not found in userValueInfo");
}
Debug.Log ("TryGetValue:: friction = " + GearFriction + ", geartype = " + GearShapeType + ", gametime = " + GameTime + ", showdebug = " + ShowDebug + ", fbicon = " + FBIcon + ", split1name = " + Split1Name);
//store values
if (PlayerPrefs.HasKey ("gearfriction")) {
PlayerPrefs.SetFloat("gearfriction", GearFriction);
}
if (PlayerPrefs.HasKey ("geartype")) {
PlayerPrefs.SetInt("geartype", GearShapeType);
}
if (PlayerPrefs.HasKey ("gametime")) {
PlayerPrefs.SetInt("gametime", GameTime);
}
if (PlayerPrefs.HasKey ("showdebug")) {
PlayerPrefs.SetInt("showdebug", ShowDebug);
}
if (PlayerPrefs.HasKey ("fbicon")) {
PlayerPrefs.SetInt("fbicon", FBIcon);
}
if (PlayerPrefs.HasKey ("splitgroup")) {
PlayerPrefs.SetString("splitgroup", Split1Name);
}
NotificationCenter.DefaultCenter.PostNotification(getMainMenuClass(), "RefreshDebugText");
#if USE_ANALYTICS
flurryService.LogEvent("OnFuelDynamicsUserValues", analyticResult);
#endif
}
private bool isDeviceTablet ()
{
bool isTablet = false;
#if UNITY_IOS
if (Application.platform == RuntimePlatform.IPhonePlayer) {
if(UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadUnknown ||
UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad1Gen ||
UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad2Gen ||
UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad3Gen ||
UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad4Gen ||
UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadMini1Gen)
{
isTablet = true;
}
}
#else
float screenWidth = Screen.width / Screen.dpi;
float screenHeight = Screen.height / Screen.dpi;
float size = Mathf.Sqrt(Mathf.Pow(screenWidth, 2) + Mathf.Pow(screenHeight, 2));
size = (float)Mathf.Round(size * 10f) / 10f;
Debug.Log("IsTablet inches = " + size);
if(size >= 7.0)
isTablet = true;
else
isTablet = false;
#endif
return isTablet;
}
//Unit Tests
private void VirtualGoodUnitTest()
{
Hashtable goodsTable = new Hashtable();
goodsTable["addGold"] = 2;
goodsTable["addOil"] = 2;
goodsTable["showTrophy"] = 1;
getMainMenuClass().RefreshVirtualGoods(goodsTable);
}
/*
---------------------------------------------------------------------
Notifications & Deep Linking
---------------------------------------------------------------------
*/
public void OnPropellerSDKNotification(string applicationState)
{
Debug.Log("OnPropellerSDKNotification");
AutoLauncher.Instance ().ValidateAutoLauncher (applicationState);
}
private void SetLanguageLocale()
{
Dictionary<string, string> langLookup = new Dictionary<string, string> ();
langLookup.Add ("English", "en");
langLookup.Add ("French", "fr");
langLookup.Add ("German", "de");
langLookup.Add ("Spanish", "es");
langLookup.Add ("Italian", "it");
langLookup.Add ("Portuguese", "pt");
langLookup.Add ("Chinese", "zh");
langLookup.Add ("ChineseSimplified", "zh");
langLookup.Add ("Korean", "ko");
langLookup.Add ("Japanese", "ja");
langLookup.Add ("Russian", "ru");
langLookup.Add ("Arabic", "ar");
var unityLang = Application.systemLanguage;
string langCode;
if (langLookup.TryGetValue (unityLang.ToString (), out langCode)) {
#if PROPELLER_SDK
PropellerSDK.SetLanguageCode (langCode);
#endif
} else {
Debug.Log("SetLanguageLocale Error: " + unityLang.ToString() + " not supported.");
#if PROPELLER_SDK
PropellerSDK.SetLanguageCode ("en");
#endif
}
}
}
| |
using System;
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding {
/** Floods the area completely for easy computation of any path to a single point.
* This path is a bit special, because it does not do anything useful by itself. What it does is that it calculates paths to all nodes it can reach, it floods the graph.
* This data will remain stored in the path. Then you can call a FloodPathTracer path, that path will trace the path from it's starting point all the way to where this path started flooding and thus generating a path extremely quickly.\n
* It is very useful in for example TD (Tower Defence) games where all your AIs will walk to the same point, but from different places, and you do not update the graph or change the target point very often,
* what changes is their positions and new AIs spawn all the time (which makes it hard to use the MultiTargetPath).\n
*
* With this path type, it can all be handled easily.
* - At start, you simply start ONE FloodPath and save the reference (it will be needed later).
* - Then when a unit is spawned or needs its path recalculated, start a FloodPathTracer path from it's position.
* It will then find the shortest path to the point specified when you called the FloodPath extremely quickly.
* - If you update the graph (for example place a tower in a TD game) or need to change the target point, you simply call a new FloodPath (and store it's reference).
*
* \version From 3.2 and up, path traversal data is now stored in the path class.
* So you can now use other path types in parallel with this one.
*
* Here follows some example code of the above list of steps:
* \code
* public static FloodPath fpath;
*
* public void Start () {
* fpath = FloodPath.Construct (someTargetPosition, null);
* AstarPath.StartPath (fpath);
* }
* \endcode
*
* When searching for a new path to \a someTargetPosition from let's say \a transform.position, you do
* \code
* FloodPathTracer fpathTrace = FloodPathTracer.Construct (transform.position,fpath,null);
* seeker.StartPath (fpathTrace,OnPathComplete);
* \endcode
* Where OnPathComplete is your callback function.
* \n
* Another thing to note is that if you are using NNConstraints on the FloodPathTracer, they must always inherit from Pathfinding.PathIDConstraint.\n
* The easiest is to just modify the instance of PathIDConstraint which is created as the default one.
*
* \astarpro
*
* \shadowimage{floodPathExample.png}
*
* \ingroup paths
*
*/
public class FloodPath : Path {
public Vector3 originalStartPoint;
public Vector3 startPoint;
public GraphNode startNode;
/** If false, will not save any information.
* Used by some internal parts of the system which doesn't need it.
*/
public bool saveParents = true;
protected Dictionary<GraphNode, GraphNode> parents;
public override bool FloodingPath {
get {
return true;
}
}
public bool HasPathTo (GraphNode node) {
return parents != null && parents.ContainsKey (node);
}
public GraphNode GetParent (GraphNode node) {
return parents[node];
}
/** Default constructor.
* Do not use this. Instead use the static Construct method which can handle path pooling.
*/
public FloodPath () {}
public static FloodPath Construct (Vector3 start, OnPathDelegate callback = null) {
var p = PathPool.GetPath<FloodPath>();
p.Setup(start, callback);
return p;
}
public static FloodPath Construct (GraphNode start, OnPathDelegate callback = null) {
if (start == null) throw new ArgumentNullException("start");
var p = PathPool.GetPath<FloodPath>();
p.Setup(start, callback);
return p;
}
protected void Setup (Vector3 start, OnPathDelegate callback) {
this.callback = callback;
originalStartPoint = start;
startPoint = start;
heuristic = Heuristic.None;
}
protected void Setup (GraphNode start, OnPathDelegate callback) {
this.callback = callback;
originalStartPoint = (Vector3)start.position;
startNode = start;
startPoint = (Vector3)start.position;
heuristic = Heuristic.None;
}
public override void Reset () {
base.Reset();
originalStartPoint = Vector3.zero;
startPoint = Vector3.zero;
startNode = null;
/** \todo Avoid this allocation */
parents = new Dictionary<GraphNode, GraphNode>();
saveParents = true;
}
public override void Prepare () {
AstarProfiler.StartProfile("Get Nearest");
if (startNode == null) {
//Initialize the NNConstraint
nnConstraint.tags = enabledTags;
NNInfo startNNInfo = AstarPath.active.GetNearest(originalStartPoint, nnConstraint);
startPoint = startNNInfo.clampedPosition;
startNode = startNNInfo.node;
} else {
startPoint = (Vector3)startNode.position;
}
AstarProfiler.EndProfile();
#if ASTARDEBUG
Debug.DrawLine((Vector3)startNode.position, startPoint, Color.blue);
#endif
if (startNode == null) {
Error();
LogError("Couldn't find a close node to the start point");
return;
}
if (!startNode.Walkable) {
#if ASTARDEBUG
Debug.DrawRay(startPoint, Vector3.up, Color.red);
Debug.DrawLine(startPoint, (Vector3)startNode.position, Color.red);
#endif
Error();
LogError("The node closest to the start point is not walkable");
return;
}
}
public override void Initialize () {
PathNode startRNode = pathHandler.GetPathNode(startNode);
startRNode.node = startNode;
startRNode.pathID = pathHandler.PathID;
startRNode.parent = null;
startRNode.cost = 0;
startRNode.G = GetTraversalCost(startNode);
startRNode.H = CalculateHScore(startNode);
parents[startNode] = null;
startNode.Open(this, startRNode, pathHandler);
searchedNodes++;
// Any nodes left to search?
if (pathHandler.HeapEmpty()) {
CompleteState = PathCompleteState.Complete;
}
currentR = pathHandler.PopNode();
}
/** Opens nodes until there are none left to search (or until the max time limit has been exceeded) */
public override void CalculateStep (long targetTick) {
int counter = 0;
//Continue to search while there hasn't ocurred an error and the end hasn't been found
while (CompleteState == PathCompleteState.NotCalculated) {
searchedNodes++;
AstarProfiler.StartFastProfile(4);
//Debug.DrawRay ((Vector3)currentR.node.Position, Vector3.up*2,Color.red);
//Loop through all walkable neighbours of the node and add them to the open list.
currentR.node.Open(this, currentR, pathHandler);
// Insert into internal search tree
if (saveParents) parents[currentR.node] = currentR.parent.node;
AstarProfiler.EndFastProfile(4);
//any nodes left to search?
if (pathHandler.HeapEmpty()) {
CompleteState = PathCompleteState.Complete;
break;
}
//Select the node with the lowest F score and remove it from the open list
AstarProfiler.StartFastProfile(7);
currentR = pathHandler.PopNode();
AstarProfiler.EndFastProfile(7);
//Check for time every 500 nodes, roughly every 0.5 ms usually
if (counter > 500) {
//Have we exceded the maxFrameTime, if so we should wait one frame before continuing the search since we don't want the game to lag
if (DateTime.UtcNow.Ticks >= targetTick) {
//Return instead of yield'ing, a separate function handles the yield (CalculatePaths)
return;
}
counter = 0;
if (searchedNodes > 1000000) {
throw new Exception("Probable infinite loop. Over 1,000,000 nodes searched");
}
}
counter++;
}
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009 Oracle. All rights reserved.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml;
using NUnit.Framework;
using BerkeleyDB;
namespace CsharpAPITest {
[TestFixture]
public class ForeignKeyTest {
private string testFixtureHome;
private string testFixtureName;
private string testName;
private string testHome;
[TestFixtureSetUp]
public void RunBeforeTests() {
testFixtureName = "ForeignKeyTest";
testFixtureHome = "./TestOut/" + testFixtureName;
}
[Test]
public void TestAbortBTree() {
testName = "TestAbortBTree";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.BTREE, ForeignKeyDeleteAction.ABORT);
}
[Test]
public void TestAbortHash() {
testName = "TestAbortHash";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.HASH, ForeignKeyDeleteAction.ABORT);
}
[Test]
public void TestAbortQueue() {
testName = "TestAbortQueue";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.QUEUE, ForeignKeyDeleteAction.ABORT);
}
[Test]
public void TestAbortRecno() {
testName = "TestAbortRecno";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.RECNO, ForeignKeyDeleteAction.ABORT);
}
[Test]
public void TestCascadeBTree() {
testName = "TestCascadeBTree";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.BTREE, ForeignKeyDeleteAction.CASCADE);
}
[Test]
public void TestCascadeHash() {
testName = "TestCascadeHash";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.HASH, ForeignKeyDeleteAction.CASCADE);
}
[Test]
public void TestCascadeQueue() {
testName = "TestCascadeQueue";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.QUEUE, ForeignKeyDeleteAction.CASCADE);
}
[Test]
public void TestCascadeRecno() {
testName = "TestCascadeRecno";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.RECNO, ForeignKeyDeleteAction.CASCADE);
}
[Test]
public void TestNullifyBTree() {
testName = "TestNullifyBTree";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.BTREE, ForeignKeyDeleteAction.NULLIFY);
}
[Test]
public void TestNullifyHash() {
testName = "TestNullifyHash";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.HASH, ForeignKeyDeleteAction.NULLIFY);
}
[Test]
public void TestNullifyQueue() {
testName = "TestNullifyQueue";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.QUEUE, ForeignKeyDeleteAction.NULLIFY);
}
[Test]
public void TestNullifyRecno() {
testName = "TestNullifyRecno";
testHome = testFixtureHome + "/" + testName;
TestForeignKeyDelete(DatabaseType.RECNO, ForeignKeyDeleteAction.NULLIFY);
}
public void TestForeignKeyDelete(DatabaseType dbtype, ForeignKeyDeleteAction action) {
string dbFileName = testHome + "/" + testName + ".db";
string fdbFileName = testHome + "/" + testName + "foreign.db";
string sdbFileName = testHome + "/" + testName + "sec.db";
Configuration.ClearDir(testHome);
Database primaryDB, fdb;
SecondaryDatabase secDB;
// Open primary database.
if (dbtype == DatabaseType.BTREE) {
BTreeDatabaseConfig btConfig = new BTreeDatabaseConfig();
btConfig.Creation = CreatePolicy.ALWAYS;
primaryDB = BTreeDatabase.Open(dbFileName, btConfig);
fdb = BTreeDatabase.Open(fdbFileName, btConfig);
} else if (dbtype == DatabaseType.HASH) {
HashDatabaseConfig hConfig = new HashDatabaseConfig();
hConfig.Creation = CreatePolicy.ALWAYS;
primaryDB = HashDatabase.Open(dbFileName, hConfig);
fdb = HashDatabase.Open(fdbFileName, hConfig);
} else if (dbtype == DatabaseType.QUEUE) {
QueueDatabaseConfig qConfig = new QueueDatabaseConfig();
qConfig.Creation = CreatePolicy.ALWAYS;
qConfig.Length = 4;
primaryDB = QueueDatabase.Open(dbFileName, qConfig);
fdb = QueueDatabase.Open(fdbFileName, qConfig);
} else if (dbtype == DatabaseType.RECNO) {
RecnoDatabaseConfig rConfig = new RecnoDatabaseConfig();
rConfig.Creation = CreatePolicy.ALWAYS;
primaryDB = RecnoDatabase.Open(dbFileName, rConfig);
fdb = RecnoDatabase.Open(fdbFileName, rConfig);
} else {
throw new ArgumentException("Invalid DatabaseType");
}
// Open secondary database.
if (dbtype == DatabaseType.BTREE) {
SecondaryBTreeDatabaseConfig secbtConfig =
new SecondaryBTreeDatabaseConfig(primaryDB,
new SecondaryKeyGenDelegate(SecondaryKeyGen));
secbtConfig.Creation = CreatePolicy.ALWAYS;
secbtConfig.Duplicates = DuplicatesPolicy.SORTED;
if (action == ForeignKeyDeleteAction.NULLIFY)
secbtConfig.SetForeignKeyConstraint(fdb, action, new ForeignKeyNullifyDelegate(Nullify));
else
secbtConfig.SetForeignKeyConstraint(fdb, action);
secDB = SecondaryBTreeDatabase.Open(sdbFileName, secbtConfig);
} else if (dbtype == DatabaseType.HASH) {
SecondaryHashDatabaseConfig sechConfig =
new SecondaryHashDatabaseConfig(primaryDB,
new SecondaryKeyGenDelegate(SecondaryKeyGen));
sechConfig.Creation = CreatePolicy.ALWAYS;
sechConfig.Duplicates = DuplicatesPolicy.SORTED;
if (action == ForeignKeyDeleteAction.NULLIFY)
sechConfig.SetForeignKeyConstraint(fdb, action, new ForeignKeyNullifyDelegate(Nullify));
else
sechConfig.SetForeignKeyConstraint(fdb, action);
secDB = SecondaryHashDatabase.Open(sdbFileName, sechConfig);
} else if (dbtype == DatabaseType.QUEUE) {
SecondaryQueueDatabaseConfig secqConfig =
new SecondaryQueueDatabaseConfig(primaryDB,
new SecondaryKeyGenDelegate(SecondaryKeyGen));
secqConfig.Creation = CreatePolicy.ALWAYS;
secqConfig.Length = 4;
if (action == ForeignKeyDeleteAction.NULLIFY)
secqConfig.SetForeignKeyConstraint(fdb, action, new ForeignKeyNullifyDelegate(Nullify));
else
secqConfig.SetForeignKeyConstraint(fdb, action);
secDB = SecondaryQueueDatabase.Open(sdbFileName, secqConfig);
} else if (dbtype == DatabaseType.RECNO) {
SecondaryRecnoDatabaseConfig secrConfig =
new SecondaryRecnoDatabaseConfig(primaryDB,
new SecondaryKeyGenDelegate(SecondaryKeyGen));
secrConfig.Creation = CreatePolicy.ALWAYS;
if (action == ForeignKeyDeleteAction.NULLIFY)
secrConfig.SetForeignKeyConstraint(fdb, action, new ForeignKeyNullifyDelegate(Nullify));
else
secrConfig.SetForeignKeyConstraint(fdb, action);
secDB = SecondaryRecnoDatabase.Open(sdbFileName, secrConfig);
} else {
throw new ArgumentException("Invalid DatabaseType");
}
/* Use integer keys for Queue/Recno support. */
fdb.Put(new DatabaseEntry(BitConverter.GetBytes(100)),
new DatabaseEntry(BitConverter.GetBytes(1001)));
fdb.Put(new DatabaseEntry(BitConverter.GetBytes(200)),
new DatabaseEntry(BitConverter.GetBytes(2002)));
fdb.Put(new DatabaseEntry(BitConverter.GetBytes(300)),
new DatabaseEntry(BitConverter.GetBytes(3003)));
primaryDB.Put(new DatabaseEntry(BitConverter.GetBytes(1)),
new DatabaseEntry(BitConverter.GetBytes(100)));
primaryDB.Put(new DatabaseEntry(BitConverter.GetBytes(2)),
new DatabaseEntry(BitConverter.GetBytes(200)));
if (dbtype == DatabaseType.BTREE || dbtype == DatabaseType.HASH)
primaryDB.Put(new DatabaseEntry(BitConverter.GetBytes(3)),
new DatabaseEntry(BitConverter.GetBytes(100)));
try {
fdb.Delete(new DatabaseEntry(BitConverter.GetBytes(100)));
} catch (ForeignConflictException) {
Assert.AreEqual(action, ForeignKeyDeleteAction.ABORT);
}
if (action == ForeignKeyDeleteAction.ABORT) {
Assert.IsTrue(secDB.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
Assert.IsTrue(primaryDB.Exists(new DatabaseEntry(BitConverter.GetBytes(1))));
Assert.IsTrue(fdb.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
} else if (action == ForeignKeyDeleteAction.CASCADE) {
try {
Assert.IsFalse(secDB.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
} catch (KeyEmptyException) {
Assert.IsTrue(dbtype == DatabaseType.QUEUE || dbtype == DatabaseType.RECNO);
}
try {
Assert.IsFalse(primaryDB.Exists(new DatabaseEntry(BitConverter.GetBytes(1))));
} catch (KeyEmptyException) {
Assert.IsTrue(dbtype == DatabaseType.QUEUE || dbtype == DatabaseType.RECNO);
}
try {
Assert.IsFalse(fdb.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
} catch (KeyEmptyException) {
Assert.IsTrue(dbtype == DatabaseType.QUEUE || dbtype == DatabaseType.RECNO);
}
} else if (action == ForeignKeyDeleteAction.NULLIFY) {
try {
Assert.IsFalse(secDB.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
} catch (KeyEmptyException) {
Assert.IsTrue(dbtype == DatabaseType.QUEUE || dbtype == DatabaseType.RECNO);
}
Assert.IsTrue(primaryDB.Exists(new DatabaseEntry(BitConverter.GetBytes(1))));
try {
Assert.IsFalse(fdb.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
} catch (KeyEmptyException) {
Assert.IsTrue(dbtype == DatabaseType.QUEUE || dbtype == DatabaseType.RECNO);
}
}
// Close secondary database.
secDB.Close();
// Close primary database.
primaryDB.Close();
// Close foreign database
fdb.Close();
}
public DatabaseEntry SecondaryKeyGen(
DatabaseEntry key, DatabaseEntry data) {
DatabaseEntry dbtGen;
int skey = BitConverter.ToInt32(data.Data, 0);
// don't index secondary key of 0
if (skey == 0)
return null;
dbtGen = new DatabaseEntry(data.Data);
return dbtGen;
}
public DatabaseEntry Nullify(DatabaseEntry key, DatabaseEntry data, DatabaseEntry fkey) {
DatabaseEntry ret = new DatabaseEntry(BitConverter.GetBytes(0));
return ret;
}
}
}
| |
// 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 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// HttpClientFailure operations.
/// </summary>
public partial interface IHttpClientFailure
{
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Head400WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get400WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Put400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Patch400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Post400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 400 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Delete400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 401 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Head401WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 402 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get402WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 403 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get403WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 404 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Put404WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 405 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Patch405WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 406 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Post406WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 407 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Delete407WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 409 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Put409WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 410 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Head410WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 411 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get411WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 412 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get412WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 413 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Put413WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 414 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Patch414WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 415 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Post415WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 416 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Get416WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 417 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Delete417WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 429 status code - should be represented in the client as an
/// error
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> Head429WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using UnityEngine;
using System.Collections.Generic;
namespace GameResource
{
public class AssetBundleManager : ResourceSingleton<AssetBundleManager>
{
#region public
public AssetBundle Load(ulong hashID)
{
int bundleID = ResourceMainfest.GetBundleID(hashID);
if (bundleID == -1)
{
return null;
}
AssetBundleData assetBundleData = _LoadAssetBundleDataWithDepend(bundleID);
return assetBundleData.GetAssetBundle();
}
public void Unload(ulong hashID)
{
int bundleID = ResourceMainfest.GetBundleID(hashID);
if (bundleID != -1)
{
_UnloadAssetBundleDataWithDepend(bundleID);
}
}
public void UnloadUnusedAssets(List<ulong> resHashs)
{
for (int i = 0; i < resHashs.Count; ++i)
{
int bundleID = ResourceMainfest.GetBundleID(resHashs[i]);
if (bundleID != -1)
{
_UpdateBundleRef(bundleID, true);
}
}
_UnloadUnloadingAssetBundle(false);
for (int i = 0; i < resHashs.Count; ++i)
{
int bundleID = ResourceMainfest.GetBundleID(resHashs[i]);
if (bundleID != -1)
{
_UpdateBundleRef(bundleID, false);
}
}
}
public void ReloadAssetBundle()
{
_UnloadUnloadingAssetBundle(true);
ResourceMainfest.ReloadMainfest();
_LoadPreLoadBundle();
}
#endregion
#region init
protected override bool Init()
{
ResourceUpdater.Instance.RegisterUpdater(Update);
_LoadPreLoadBundle();
return base.Init();
}
protected override bool UnInit()
{
ResourceUpdater.Instance.UnRegisterUpdater(Update);
return base.UnInit();
}
protected void Update()
{
_UpdateCacheBundeList(false);
}
#endregion
#region private
private void _LoadPreLoadBundle()
{
List<BundleState> preLoadList = ResourceMainfest.GetPreloadBundleList();
for (int i = 0; i < preLoadList.Count; ++i)
{
_LoadAssetBundleData(preLoadList[i].bundleId);
}
}
private AssetBundleData _LoadAssetBundleDataWithDepend(int bundleId)
{
int cur = ResourceMainfest.GetDependFirst(bundleId);
while (cur != -1)
{
int depBundleId = ResourceMainfest.GetDependValue(cur);
cur = ResourceMainfest.GetDependNext(cur);
_LoadAssetBundleData(depBundleId);
}
return _LoadAssetBundleData(bundleId);
}
private void _UnloadAssetBundleDataWithDepend(int bundleId)
{
AssetBundleData bundleData = null;
if (!m_assetBundleDict.TryGetValue(bundleId, out bundleData))
{
return;
}
int cur = ResourceMainfest.GetDependFirst(bundleId);
while (cur != -1)
{
int depBundleId = ResourceMainfest.GetDependValue(cur);
cur = ResourceMainfest.GetDependNext(cur);
AssetBundleData depBundle = null;
m_assetBundleDict.TryGetValue(depBundleId, out depBundle);
if (depBundle != null)
{
depBundle.Release();
}
}
bundleData.Release();
if (bundleData.Unloadable())
{
_UnloadBundleData(bundleData);
}
}
private AssetBundleData _LoadAssetBundleData(int bundleId)
{
AssetBundleData ret = null;
if (!m_assetBundleDict.TryGetValue(bundleId, out ret))
{
ret = new AssetBundleData(bundleId);
ret.Load();
m_assetBundleDict.Add(bundleId, ret);
}
ret.AddRef();
return ret;
}
private void _UpdateCacheBundeList(bool force)
{
if (m_cacheUnloadBundle.Count == 0) return;
int bundleId = m_cacheUnloadBundle.First.Value;
AssetBundleData bundleData = null;
m_assetBundleDict.TryGetValue(bundleId, out bundleData);
if (bundleData == null || !bundleData.Unloadable())
{
m_cacheUnloadBundle.RemoveFirst();
return;
}
if (force || bundleData.TimeOut())
{
m_cacheUnloadBundle.RemoveFirst();
bundleData.Unload(false);
m_assetBundleDict.Remove(bundleId);
}
}
private void _UnloadUnloadingAssetBundle(bool all)
{
if (m_assetBundleDict.Count == 0) return;
List<int> unloadBundleList = new List<int>(m_assetBundleDict.Count);
using (var itor = m_assetBundleDict.GetEnumerator())
{
while (itor.MoveNext())
{
if (!all && !itor.Current.Value.Unloadable())
{
continue;
}
unloadBundleList.Add(itor.Current.Key);
}
}
for (int i = 0; i < unloadBundleList.Count; ++i)
{
AssetBundleData bundleData = null;
if (m_assetBundleDict.TryGetValue(unloadBundleList[i], out bundleData))
{
if (bundleData != null) bundleData.Unload(false);
m_assetBundleDict.Remove(unloadBundleList[i]);
}
}
unloadBundleList.Clear();
}
private void _UpdateBundleDataRef(AssetBundleData bundleData, bool addRef)
{
if (bundleData != null)
{
if (addRef)
{
bundleData.AddRef();
}
else
{
bundleData.Release();
}
}
}
private void _UpdateBundleRef(int bundleId, bool addRef)
{
AssetBundleData bundleData = null;
if (m_assetBundleDict.TryGetValue(bundleId, out bundleData))
{
_UpdateBundleDataRef(bundleData, addRef);
}
int cur = ResourceMainfest.GetDependFirst(bundleId);
while (cur != -1)
{
int value = ResourceMainfest.GetDependValue(cur);
cur = ResourceMainfest.GetDependNext(cur);
if (m_assetBundleDict.TryGetValue(value, out bundleData))
{
_UpdateBundleDataRef(bundleData, addRef);
}
}
}
private void _UnloadBundleData(AssetBundleData bundleData)
{
if (bundleData == null || !bundleData.Unloadable()) return;
if (m_cacheUnloadBundle.Contains(bundleData.GetBundleId())) return;
if (m_cacheUnloadBundle.Count >= ResourceConfig.MAX_CACHE_BUNDLE_SIZE)
{
bundleData.AddRef();
_UpdateCacheBundeList(true);
bundleData.Release();
}
m_cacheUnloadBundle.AddLast(bundleData.GetBundleId());
}
private LinkedList<int> m_cacheUnloadBundle = new LinkedList<int>();
private Dictionary<int, AssetBundleData> m_assetBundleDict = new Dictionary<int, AssetBundleData>();
#endregion
}
}
| |
//
// 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 Objects taken from Geoff Chappell's website:
// http://www.geoffchappell.com/viewer.htm?doc=notes/windows/boot/bcd/objects.htm
//
//
namespace DiscUtils.BootConfig
{
using System;
using System.Collections.Generic;
/// <summary>
/// Represents a Boot Configuration Database object (application, device or inherited settings).
/// </summary>
public class BcdObject
{
/// <summary>
/// Well-known object for Emergency Management Services settings.
/// </summary>
public const string EmsSettingsGroupId = "{0CE4991B-E6B3-4B16-B23C-5E0D9250E5D9}";
/// <summary>
/// Well-known object for the Resume boot loader.
/// </summary>
public const string ResumeLoaderSettingsGroupId = "{1AFA9C49-16AB-4A5C-4A90-212802DA9460}";
/// <summary>
/// Alias for the Default boot entry.
/// </summary>
public const string DefaultBootEntryId = "{1CAE1EB7-A0DF-4D4D-9851-4860E34EF535}";
/// <summary>
/// Well-known object for Emergency Management Services settings.
/// </summary>
public const string DebuggerSettingsGroupId = "{4636856E-540F-4170-A130-A84776F4C654}";
/// <summary>
/// Well-known object for NTLDR application.
/// </summary>
public const string WindowsLegacyNtldrId = "{466F5A88-0AF2-4F76-9038-095B170DC21C}";
/// <summary>
/// Well-known object for bad memory settings.
/// </summary>
public const string BadMemoryGroupId = "{5189B25C-5558-4BF2-BCA4-289B11BD29E2}";
/// <summary>
/// Well-known object for Boot Loader settings.
/// </summary>
public const string BootLoaderSettingsGroupId = "{6EFB52BF-1766-41DB-A6B3-0EE5EFF72BD7}";
/// <summary>
/// Well-known object for EFI setup.
/// </summary>
public const string WindowsSetupEfiId = "{7254A080-1510-4E85-AC0F-E7FB3D444736}";
/// <summary>
/// Well-known object for Global settings.
/// </summary>
public const string GlobalSettingsGroupId = "{7EA2E1AC-2E61-4728-AAA3-896D9D0A9F0E}";
/// <summary>
/// Well-known object for Windows Boot Manager.
/// </summary>
public const string WindowsBootManagerId = "{9DEA862C-5CDD-4E70-ACC1-F32B344D4795}";
/// <summary>
/// Well-known object for PCAT Template.
/// </summary>
public const string WindowsOsTargetTemplatePcatId = "{A1943BBC-EA85-487C-97C7-C9EDE908A38A}";
/// <summary>
/// Well-known object for Firmware Boot Manager.
/// </summary>
public const string FirmwareBootManagerId = "{A5A30FA2-3D06-4E9F-B5F4-A01DF9D1FCBA}";
/// <summary>
/// Well-known object for Windows Setup RAMDISK options.
/// </summary>
public const string WindowsSetupRamdiskOptionsId = "{AE5534E0-A924-466C-B836-758539A3EE3A}";
/// <summary>
/// Well-known object for EFI template.
/// </summary>
public const string WindowsOsTargetTemplateEfiId = "{B012B84D-C47C-4ED5-B722-C0C42163E569}";
/// <summary>
/// Well-known object for Windows memory tester application.
/// </summary>
public const string WindowsMemoryTesterId = "{B2721D73-1DB4-4C62-BF78-C548A880142D}";
/// <summary>
/// Well-known object for Windows PCAT setup.
/// </summary>
public const string WindowsSetupPcatId = "{CBD971BF-B7B8-4885-951A-FA03044F5D71}";
/// <summary>
/// Alias for the current boot entry.
/// </summary>
public const string CurrentBootEntryId = "{FA926493-6F1C-4193-A414-58F0B2456D1E}";
private static Dictionary<string, Guid> s_nameToGuid;
private static Dictionary<Guid, string> s_guidToName;
private BaseStorage _storage;
private Guid _id;
private int _type;
static BcdObject()
{
s_nameToGuid = new Dictionary<string, Guid>();
s_guidToName = new Dictionary<Guid, string>();
AddMapping("{emssettings}", EmsSettingsGroupId);
AddMapping("{resumeloadersettings}", ResumeLoaderSettingsGroupId);
AddMapping("{default}", DefaultBootEntryId);
AddMapping("{dbgsettings}", DebuggerSettingsGroupId);
AddMapping("{legacy}", WindowsLegacyNtldrId);
AddMapping("{ntldr}", WindowsLegacyNtldrId);
AddMapping("{badmemory}", BadMemoryGroupId);
AddMapping("{bootloadersettings}", BootLoaderSettingsGroupId);
AddMapping("{globalsettings}", GlobalSettingsGroupId);
AddMapping("{bootmgr}", WindowsBootManagerId);
AddMapping("{fwbootmgr}", FirmwareBootManagerId);
AddMapping("{ramdiskoptions}", WindowsSetupRamdiskOptionsId);
AddMapping("{memdiag}", WindowsMemoryTesterId);
AddMapping("{current}", CurrentBootEntryId);
}
internal BcdObject(BaseStorage store, Guid id)
{
_storage = store;
_id = id;
_type = _storage.GetObjectType(id);
}
/// <summary>
/// Gets the identity of this object.
/// </summary>
public Guid Identity
{
get { return _id; }
}
/// <summary>
/// Gets the friendly name for this object, if known.
/// </summary>
public string FriendlyName
{
get
{
string name;
if (s_guidToName.TryGetValue(_id, out name))
{
return name;
}
return _id.ToString("B");
}
}
/// <summary>
/// Gets the object type for this object.
/// </summary>
public ObjectType ObjectType
{
get { return (ObjectType)((_type >> 28) & 0xF); }
}
/// <summary>
/// Gets the image type for this application.
/// </summary>
public ApplicationImageType ApplicationImageType
{
get { return IsApplication ? (ApplicationImageType)((_type & 0x00F00000) >> 20) : 0; }
}
/// <summary>
/// Gets the application type for this application.
/// </summary>
public ApplicationType ApplicationType
{
get { return IsApplication ? (ApplicationType)(_type & 0xFFFFF) : 0; }
}
/// <summary>
/// Gets the elements in this object.
/// </summary>
public IEnumerable<Element> Elements
{
get
{
foreach (var el in _storage.EnumerateElements(_id))
{
yield return new Element(_storage, _id, ApplicationType, el);
}
}
}
private bool IsApplication
{
get { return ObjectType == ObjectType.Application; }
}
/// <summary>
/// Indicates if the settings in this object are inheritable by another object.
/// </summary>
/// <param name="type">The type of the object to test for inheritability</param>
/// <returns><c>true</c> if the settings can be inherited, else <c>false</c></returns>
public bool IsInheritableBy(ObjectType type)
{
if (type == ObjectType.Inherit)
{
throw new ArgumentException("Can not test inheritability by inherit objects", "type");
}
if (ObjectType != ObjectType.Inherit)
{
return false;
}
InheritType setting = (InheritType)((_type & 0x00F00000) >> 20);
return setting == InheritType.AnyObject
|| (setting == InheritType.ApplicationObjects && type == ObjectType.Application)
|| (setting == InheritType.DeviceObjects && type == ObjectType.Device);
}
/// <summary>
/// Indicates if this object has a specific element.
/// </summary>
/// <param name="id">The identity of the element to look for.</param>
/// <returns><c>true</c> if present, else <c>false</c></returns>
public bool HasElement(int id)
{
return _storage.HasValue(_id, id);
}
/// <summary>
/// Indicates if this object has a specific element.
/// </summary>
/// <param name="id">The identity of the element to look for.</param>
/// <returns><c>true</c> if present, else <c>false</c></returns>
public bool HasElement(WellKnownElement id)
{
return HasElement((int)id);
}
/// <summary>
/// Gets a specific element in this object.
/// </summary>
/// <param name="id">The identity of the element to look for.</param>
/// <returns>The element object</returns>
public Element GetElement(int id)
{
if (HasElement(id))
{
return new Element(_storage, _id, ApplicationType, id);
}
return null;
}
/// <summary>
/// Gets a specific element in this object.
/// </summary>
/// <param name="id">The identity of the element to look for.</param>
/// <returns>The element object</returns>
public Element GetElement(WellKnownElement id)
{
return GetElement((int)id);
}
/// <summary>
/// Adds an element in this object.
/// </summary>
/// <param name="id">The identity of the element to add.</param>
/// <param name="initialValue">The initial value of the element</param>
/// <returns>The element object</returns>
public Element AddElement(int id, ElementValue initialValue)
{
_storage.CreateElement(_id, id);
Element el = new Element(_storage, _id, ApplicationType, id);
el.Value = initialValue;
return el;
}
/// <summary>
/// Adds an element in this object.
/// </summary>
/// <param name="id">The identity of the element to add.</param>
/// <param name="initialValue">The initial value of the element</param>
/// <returns>The element object</returns>
public Element AddElement(WellKnownElement id, ElementValue initialValue)
{
return AddElement((int)id, initialValue);
}
/// <summary>
/// Removes a specific element
/// </summary>
/// <param name="id">The element to remove</param>
public void RemoveElement(int id)
{
_storage.DeleteElement(_id, id);
}
/// <summary>
/// Removes a specific element
/// </summary>
/// <param name="id">The element to remove</param>
public void RemoveElement(WellKnownElement id)
{
RemoveElement((int)id);
}
/// <summary>
/// Returns the object identity as a GUID string.
/// </summary>
/// <returns>A string representation, with surrounding curly braces</returns>
public override string ToString()
{
return _id.ToString("B");
}
internal static int MakeApplicationType(ApplicationImageType imageType, ApplicationType appType)
{
return 0x10000000 | (((int)imageType << 20) & 0x00F00000) | ((int)appType & 0x0000FFFF);
}
internal static int MakeInheritType(InheritType inheritType)
{
return 0x20000000 | (((int)inheritType << 20) & 0x00F00000);
}
private static void AddMapping(string name, string id)
{
Guid guid = new Guid(id);
s_nameToGuid[name] = guid;
s_guidToName[guid] = name;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2016 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using Mono.Options;
namespace NUnit.Gui
{
/// <summary>
/// GuiOptions encapsulates the option settingsServiceServiceService for
/// the nunit-console program. It inherits from the Mono
/// Options OptionSet class and provides a central location
/// for defining and parsing options.
/// </summary>
public class CommandLineOptions : OptionSet
{
private bool validated;
#region Constructor
public CommandLineOptions(params string[] args)
{
// NOTE: The order in which patterns are added
// determines the display order for the help.
// Old Options no longer supported:
// test
// console
// include
// exclude
// Old Options to continue supporting:
// lang
// cleanup
// help
// Options to be added:
// test
// trace
// Select Tests
//this.Insert("test=", "Comma-separated list of {NAMES} of tests to run or explore. This option may be repeated.",
// v => ((List<string>)TestList).AddRange(TestNameParser.Parse(RequiredValue(v, "--test"))));
this.Add("config=", "Project {CONFIG} to load (e.g.: Debug).",
v => ActiveConfig = RequiredValue(v, "--config"));
this.Add("noload", "Suppress loading of most recent project.",
v => NoLoad = v != null);
this.Add("run", "Automatically run the loaded project.",
v => RunAllTests = v != null);
//this.Add("runselected", "Automatically run last selected tests.",
// v => RunSelectedTests = v != null);
// Output GuiELement
this.Add("trace=", "Set internal trace {LEVEL}.",
v => InternalTraceLevel = RequiredValue(v, "--trace", "Off", "Error", "Warning", "Info", "Verbose", "Debug"));
this.Add("help|h", "Display this message and exit.",
v => ShowHelp = v != null);
// Default
this.Add("<>", v =>
{
if (v.StartsWith("-") || v.StartsWith("/") && Path.DirectorySeparatorChar != '/')
ErrorMessages.Add("Invalid argument: " + v);
else
InputFiles.Add(v);
});
if (args != null)
this.Parse(args);
}
#endregion
#region Properties
// Action to Perform
public bool ShowHelp { get; private set; }
public bool NoLoad { get; private set; }
public bool RunAllTests { get; private set; }
//public bool RunSelectedTests { get; private set; }
// Select tests
private List<string> inputFiles = new List<string>();
public IList<string> InputFiles { get { return inputFiles; } }
//private List<string> testList = new List<string>();
//public IList<string> TestList { get { return testList; } }
public string ActiveConfig { get; private set; }
// Where to Run Tests
//public string ProcessModel { get; private set; }
//public string DomainUsage { get; private set; }
// Output GuiELement
public string InternalTraceLevel { get; private set; }
// Error Processing
public List<string> errorMessages = new List<string>();
public IList<string> ErrorMessages { get { return errorMessages; } }
#endregion
#region Public Methods
public bool Validate()
{
if (!validated)
{
// Additional Checks here
validated = true;
}
return ErrorMessages.Count == 0;
}
#endregion
#region Helper Methods
private string RequiredValue(string val, string option, params string[] validValues)
{
if (val == null || val == string.Empty)
ErrorMessages.Add("Missing required value for option '" + option + "'.");
bool isValid = true;
if (validValues != null && validValues.Length > 0)
{
isValid = false;
foreach (string valid in validValues)
if (string.Compare(valid, val, true) == 0)
isValid = true;
}
if (!isValid)
ErrorMessages.Add(string.Format("The value '{0}' is not valid for option '{1}'.", val, option));
return val;
}
private int RequiredInt(string val, string option)
{
// We have to return something even though the val will
// be ignored if an error is reported. The -1 val seems
// like a safe bet in case it isn't ignored due to a bug.
int result = -1;
if (val == null || val == string.Empty)
ErrorMessages.Add("Missing required value for option '" + option + "'.");
else
{
int r;
if (int.TryParse(val, out r))
result = r;
else
ErrorMessages.Add("An int value was exprected for option '{0}' but a value of '{1}' was used");
}
return result;
}
//private void RequiredIntError(string option)
//{
// ErrorMessages.Insert("An int val is required for option '" + option + "'.");
//}
//private void ProcessIntOption(string v, ref int field)
//{
// if (!int.TryParse(v, out field))
// ErrorMessages.Insert("Invalid argument val: " + v);
//}
//private void ProcessEnumOption<T>(string v, ref T field)
//{
// if (Enum.IsDefined(typeof(T), v))
// field = (T)Enum.Parse(typeof(T), v);
// else
// ErrorMessages.Insert("Invalid argument val: " + v);
//}
//private object ParseEnumOption(Type enumType, string val)
//{
// foreach (string name in Enum.GetNames(enumType))
// if (val.ToLower() == name.ToLower())
// return Enum.Parse(enumType, val);
// this.ErrorMessages.Insert(val);
// return null;
//}
#endregion
}
}
| |
// Copyright 2018 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using pb = Google.Protobuf;
using pbwkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Speech.V1P1Beta1
{
/// <summary>
/// Settings for a <see cref="SpeechClient"/>.
/// </summary>
public sealed partial class SpeechSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="SpeechSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="SpeechSettings"/>.
/// </returns>
public static SpeechSettings GetDefault() => new SpeechSettings();
/// <summary>
/// Constructs a new <see cref="SpeechSettings"/> object with default settings.
/// </summary>
public SpeechSettings() { }
private SpeechSettings(SpeechSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
RecognizeSettings = existing.RecognizeSettings;
LongRunningRecognizeSettings = existing.LongRunningRecognizeSettings;
LongRunningRecognizeOperationsSettings = existing.LongRunningRecognizeOperationsSettings?.Clone();
StreamingRecognizeSettings = existing.StreamingRecognizeSettings;
StreamingRecognizeStreamingSettings = existing.StreamingRecognizeStreamingSettings;
OnCopy(existing);
}
partial void OnCopy(SpeechSettings existing);
/// <summary>
/// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="SpeechClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="grpccore::StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } =
gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="SpeechClient"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="grpccore::StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } =
gaxgrpc::RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="SpeechClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="SpeechClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="SpeechClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings(
delay: sys::TimeSpan.FromMilliseconds(100),
maxDelay: sys::TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="SpeechClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="SpeechClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="SpeechClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 1000000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 1000000 milliseconds</description></item>
/// </list>
/// </remarks>
public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings(
delay: sys::TimeSpan.FromMilliseconds(1000000),
maxDelay: sys::TimeSpan.FromMilliseconds(1000000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SpeechClient.Recognize</c> and <c>SpeechClient.RecognizeAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>SpeechClient.Recognize</c> and
/// <c>SpeechClient.RecognizeAsync</c> <see cref="gaxgrpc::RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 1000000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 1000000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 5000000 milliseconds.
/// </remarks>
public gaxgrpc::CallSettings RecognizeSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming(
gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(5000000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SpeechClient.LongRunningRecognize</c> and <c>SpeechClient.LongRunningRecognizeAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>SpeechClient.LongRunningRecognize</c> and
/// <c>SpeechClient.LongRunningRecognizeAsync</c> <see cref="gaxgrpc::RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 1000000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 1000000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description>No status codes</description></item>
/// </list>
/// Default RPC expiration is 5000000 milliseconds.
/// </remarks>
public gaxgrpc::CallSettings LongRunningRecognizeSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming(
gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(5000000)),
retryFilter: NonIdempotentRetryFilter
)));
/// <summary>
/// Long Running Operation settings for calls to <c>SpeechClient.LongRunningRecognize</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45000 milliseconds</description></item>
/// <item><description>Total timeout: 86400000 milliseconds</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings LongRunningRecognizeOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(
gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(86400000L)),
sys::TimeSpan.FromMilliseconds(20000L),
1.5,
sys::TimeSpan.FromMilliseconds(45000L))
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for calls to <c>SpeechClient.StreamingRecognize</c>.
/// </summary>
/// <remarks>
/// Default RPC expiration is 5000000 milliseconds.
/// </remarks>
public gaxgrpc::CallSettings StreamingRecognizeSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming(
gaxgrpc::CallTiming.FromTimeout(sys::TimeSpan.FromMilliseconds(5000000)));
/// <summary>
/// <see cref="gaxgrpc::BidirectionalStreamingSettings"/> for calls to
/// <c>SpeechClient.StreamingRecognize</c>.
/// </summary>
/// <remarks>
/// The default local send queue size is 100.
/// </remarks>
public gaxgrpc::BidirectionalStreamingSettings StreamingRecognizeStreamingSettings { get; set; } =
new gaxgrpc::BidirectionalStreamingSettings(100);
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="SpeechSettings"/> object.</returns>
public SpeechSettings Clone() => new SpeechSettings(this);
}
/// <summary>
/// Speech client wrapper, for convenient use.
/// </summary>
public abstract partial class SpeechClient
{
/// <summary>
/// The default endpoint for the Speech service, which is a host of "speech.googleapis.com" and a port of 443.
/// </summary>
public static gaxgrpc::ServiceEndpoint DefaultEndpoint { get; } = new gaxgrpc::ServiceEndpoint("speech.googleapis.com", 443);
/// <summary>
/// The default Speech scopes.
/// </summary>
/// <remarks>
/// The default Speech scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
});
private static readonly gaxgrpc::ChannelPool s_channelPool = new gaxgrpc::ChannelPool(DefaultScopes);
/// <summary>
/// Asynchronously creates a <see cref="SpeechClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary. See the example for how to use custom credentials.
/// </summary>
/// <example>
/// This sample shows how to create a client using default credentials:
/// <code>
/// using Google.Cloud.Speech.V1P1Beta1;
/// ...
/// // When running on Google Cloud Platform this will use the project Compute Credential.
/// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON
/// // credential file to use that credential.
/// SpeechClient client = await SpeechClient.CreateAsync();
/// </code>
/// This sample shows how to create a client using credentials loaded from a JSON file:
/// <code>
/// using Google.Cloud.Speech.V1P1Beta1;
/// using Google.Apis.Auth.OAuth2;
/// using Grpc.Auth;
/// using Grpc.Core;
/// ...
/// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json");
/// Channel channel = new Channel(
/// SpeechClient.DefaultEndpoint.Host, SpeechClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
/// SpeechClient client = SpeechClient.Create(channel);
/// ...
/// // Shutdown the channel when it is no longer required.
/// await channel.ShutdownAsync();
/// </code>
/// </example>
/// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="SpeechSettings"/>.</param>
/// <returns>The task representing the created <see cref="SpeechClient"/>.</returns>
public static async stt::Task<SpeechClient> CreateAsync(gaxgrpc::ServiceEndpoint endpoint = null, SpeechSettings settings = null)
{
grpccore::Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="SpeechClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary. See the example for how to use custom credentials.
/// </summary>
/// <example>
/// This sample shows how to create a client using default credentials:
/// <code>
/// using Google.Cloud.Speech.V1P1Beta1;
/// ...
/// // When running on Google Cloud Platform this will use the project Compute Credential.
/// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON
/// // credential file to use that credential.
/// SpeechClient client = SpeechClient.Create();
/// </code>
/// This sample shows how to create a client using credentials loaded from a JSON file:
/// <code>
/// using Google.Cloud.Speech.V1P1Beta1;
/// using Google.Apis.Auth.OAuth2;
/// using Grpc.Auth;
/// using Grpc.Core;
/// ...
/// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json");
/// Channel channel = new Channel(
/// SpeechClient.DefaultEndpoint.Host, SpeechClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
/// SpeechClient client = SpeechClient.Create(channel);
/// ...
/// // Shutdown the channel when it is no longer required.
/// channel.ShutdownAsync().Wait();
/// </code>
/// </example>
/// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="SpeechSettings"/>.</param>
/// <returns>The created <see cref="SpeechClient"/>.</returns>
public static SpeechClient Create(gaxgrpc::ServiceEndpoint endpoint = null, SpeechSettings settings = null)
{
grpccore::Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="SpeechClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="grpccore::Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="SpeechSettings"/>.</param>
/// <returns>The created <see cref="SpeechClient"/>.</returns>
public static SpeechClient Create(grpccore::Channel channel, SpeechSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(channel, nameof(channel));
return Create(new grpccore::DefaultCallInvoker(channel), settings);
}
/// <summary>
/// Creates a <see cref="SpeechClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="SpeechSettings"/>.</param>
/// <returns>The created <see cref="SpeechClient"/>.</returns>
public static SpeechClient Create(grpccore::CallInvoker callInvoker, SpeechSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpccore::Interceptors.Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpccore::Interceptors.CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
Speech.SpeechClient grpcClient = new Speech.SpeechClient(callInvoker);
return new SpeechClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(gaxgrpc::ServiceEndpoint, SpeechSettings)"/>
/// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, SpeechSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(gaxgrpc::ServiceEndpoint, SpeechSettings)"/>
/// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, SpeechSettings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC Speech client.
/// </summary>
public virtual Speech.SpeechClient GrpcClient
{
get { throw new sys::NotImplementedException(); }
}
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="config">
/// *Required* Provides information to the recognizer that specifies how to
/// process the request.
/// </param>
/// <param name="audio">
/// *Required* The audio data to be recognized.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<RecognizeResponse> RecognizeAsync(
RecognitionConfig config,
RecognitionAudio audio,
gaxgrpc::CallSettings callSettings = null) => RecognizeAsync(
new RecognizeRequest
{
Config = gax::GaxPreconditions.CheckNotNull(config, nameof(config)),
Audio = gax::GaxPreconditions.CheckNotNull(audio, nameof(audio)),
},
callSettings);
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="config">
/// *Required* Provides information to the recognizer that specifies how to
/// process the request.
/// </param>
/// <param name="audio">
/// *Required* The audio data to be recognized.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="st::CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<RecognizeResponse> RecognizeAsync(
RecognitionConfig config,
RecognitionAudio audio,
st::CancellationToken cancellationToken) => RecognizeAsync(
config,
audio,
gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="config">
/// *Required* Provides information to the recognizer that specifies how to
/// process the request.
/// </param>
/// <param name="audio">
/// *Required* The audio data to be recognized.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual RecognizeResponse Recognize(
RecognitionConfig config,
RecognitionAudio audio,
gaxgrpc::CallSettings callSettings = null) => Recognize(
new RecognizeRequest
{
Config = gax::GaxPreconditions.CheckNotNull(config, nameof(config)),
Audio = gax::GaxPreconditions.CheckNotNull(audio, nameof(audio)),
},
callSettings);
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<RecognizeResponse> RecognizeAsync(
RecognizeRequest request,
gaxgrpc::CallSettings callSettings = null)
{
throw new sys::NotImplementedException();
}
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="st::CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<RecognizeResponse> RecognizeAsync(
RecognizeRequest request,
st::CancellationToken cancellationToken) => RecognizeAsync(
request,
gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual RecognizeResponse Recognize(
RecognizeRequest request,
gaxgrpc::CallSettings callSettings = null)
{
throw new sys::NotImplementedException();
}
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="config">
/// *Required* Provides information to the recognizer that specifies how to
/// process the request.
/// </param>
/// <param name="audio">
/// *Required* The audio data to be recognized.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync(
RecognitionConfig config,
RecognitionAudio audio,
gaxgrpc::CallSettings callSettings = null) => LongRunningRecognizeAsync(
new LongRunningRecognizeRequest
{
Config = gax::GaxPreconditions.CheckNotNull(config, nameof(config)),
Audio = gax::GaxPreconditions.CheckNotNull(audio, nameof(audio)),
},
callSettings);
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="config">
/// *Required* Provides information to the recognizer that specifies how to
/// process the request.
/// </param>
/// <param name="audio">
/// *Required* The audio data to be recognized.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="st::CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync(
RecognitionConfig config,
RecognitionAudio audio,
st::CancellationToken cancellationToken) => LongRunningRecognizeAsync(
config,
audio,
gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="config">
/// *Required* Provides information to the recognizer that specifies how to
/// process the request.
/// </param>
/// <param name="audio">
/// *Required* The audio data to be recognized.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> LongRunningRecognize(
RecognitionConfig config,
RecognitionAudio audio,
gaxgrpc::CallSettings callSettings = null) => LongRunningRecognize(
new LongRunningRecognizeRequest
{
Config = gax::GaxPreconditions.CheckNotNull(config, nameof(config)),
Audio = gax::GaxPreconditions.CheckNotNull(audio, nameof(audio)),
},
callSettings);
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync(
LongRunningRecognizeRequest request,
gaxgrpc::CallSettings callSettings = null)
{
throw new sys::NotImplementedException();
}
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>LongRunningRecognizeAsync</c>.
/// </summary>
/// <param name="operationName">The name of a previously invoked operation. Must not be <c>null</c> or empty.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> PollOnceLongRunningRecognizeAsync(
string operationName,
gaxgrpc::CallSettings callSettings = null) => lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>.PollOnceFromNameAsync(
gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)),
LongRunningRecognizeOperationsClient,
callSettings);
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> LongRunningRecognize(
LongRunningRecognizeRequest request,
gaxgrpc::CallSettings callSettings = null)
{
throw new sys::NotImplementedException();
}
/// <summary>
/// The long-running operations client for <c>LongRunningRecognize</c>.
/// </summary>
public virtual lro::OperationsClient LongRunningRecognizeOperationsClient
{
get { throw new sys::NotImplementedException(); }
}
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>LongRunningRecognize</c>.
/// </summary>
/// <param name="operationName">The name of a previously invoked operation. Must not be <c>null</c> or empty.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> PollOnceLongRunningRecognize(
string operationName,
gaxgrpc::CallSettings callSettings = null) => lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>.PollOnceFromName(
gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)),
LongRunningRecognizeOperationsClient,
callSettings);
/// <summary>
/// Performs bidirectional streaming speech recognition: receive results while
/// sending audio. This method is only available via the gRPC API (not REST).
/// </summary>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <param name="streamingSettings">
/// If not null, applies streaming overrides to this RPC call.
/// </param>
/// <returns>
/// The client-server stream.
/// </returns>
public virtual StreamingRecognizeStream StreamingRecognize(
gaxgrpc::CallSettings callSettings = null,
gaxgrpc::BidirectionalStreamingSettings streamingSettings = null)
{
throw new sys::NotImplementedException();
}
/// <summary>
/// Bidirectional streaming methods for <c>StreamingRecognize</c>.
/// </summary>
public abstract partial class StreamingRecognizeStream : gaxgrpc::BidirectionalStreamingBase<StreamingRecognizeRequest, StreamingRecognizeResponse>
{
}
}
/// <summary>
/// Speech client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class SpeechClientImpl : SpeechClient
{
private readonly gaxgrpc::ApiCall<RecognizeRequest, RecognizeResponse> _callRecognize;
private readonly gaxgrpc::ApiCall<LongRunningRecognizeRequest, lro::Operation> _callLongRunningRecognize;
private readonly gaxgrpc::ApiBidirectionalStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> _callStreamingRecognize;
/// <summary>
/// Constructs a client wrapper for the Speech service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="SpeechSettings"/> used within this client </param>
public SpeechClientImpl(Speech.SpeechClient grpcClient, SpeechSettings settings)
{
GrpcClient = grpcClient;
SpeechSettings effectiveSettings = settings ?? SpeechSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
LongRunningRecognizeOperationsClient = new lro::OperationsClientImpl(
grpcClient.CreateOperationsClient(), effectiveSettings.LongRunningRecognizeOperationsSettings);
_callRecognize = clientHelper.BuildApiCall<RecognizeRequest, RecognizeResponse>(
GrpcClient.RecognizeAsync, GrpcClient.Recognize, effectiveSettings.RecognizeSettings);
_callLongRunningRecognize = clientHelper.BuildApiCall<LongRunningRecognizeRequest, lro::Operation>(
GrpcClient.LongRunningRecognizeAsync, GrpcClient.LongRunningRecognize, effectiveSettings.LongRunningRecognizeSettings);
_callStreamingRecognize = clientHelper.BuildApiCall<StreamingRecognizeRequest, StreamingRecognizeResponse>(
GrpcClient.StreamingRecognize, effectiveSettings.StreamingRecognizeSettings, effectiveSettings.StreamingRecognizeStreamingSettings);
Modify_ApiCall(ref _callRecognize);
Modify_RecognizeApiCall(ref _callRecognize);
Modify_ApiCall(ref _callLongRunningRecognize);
Modify_LongRunningRecognizeApiCall(ref _callLongRunningRecognize);
Modify_ApiCall(ref _callStreamingRecognize);
Modify_StreamingRecognizeApiCall(ref _callStreamingRecognize);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
// Partial methods are named to (mostly) ensure there cannot be conflicts with RPC method names.
// Partial methods called for every ApiCall on construction.
// Allows modification of all the underlying ApiCall objects.
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call)
where TRequest : class, pb::IMessage<TRequest>
where TResponse : class, pb::IMessage<TResponse>;
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiBidirectionalStreamingCall<TRequest, TResponse> call)
where TRequest : class, pb::IMessage<TRequest>
where TResponse : class, pb::IMessage<TResponse>;
// Partial methods called for each ApiCall on construction.
// Allows per-RPC-method modification of the underlying ApiCall object.
partial void Modify_RecognizeApiCall(ref gaxgrpc::ApiCall<RecognizeRequest, RecognizeResponse> call);
partial void Modify_LongRunningRecognizeApiCall(ref gaxgrpc::ApiCall<LongRunningRecognizeRequest, lro::Operation> call);
partial void Modify_StreamingRecognizeApiCall(ref gaxgrpc::ApiBidirectionalStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> call);
partial void OnConstruction(Speech.SpeechClient grpcClient, SpeechSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>
/// The underlying gRPC Speech client.
/// </summary>
public override Speech.SpeechClient GrpcClient { get; }
// Partial methods called on each request.
// Allows per-RPC-call modification to the request and CallSettings objects,
// before the underlying RPC is performed.
partial void Modify_RecognizeRequest(ref RecognizeRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_LongRunningRecognizeRequest(ref LongRunningRecognizeRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_StreamingRecognizeRequestCallSettings(ref gaxgrpc::CallSettings settings);
partial void Modify_StreamingRecognizeRequestRequest(ref StreamingRecognizeRequest request);
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override stt::Task<RecognizeResponse> RecognizeAsync(
RecognizeRequest request,
gaxgrpc::CallSettings callSettings = null)
{
Modify_RecognizeRequest(ref request, ref callSettings);
return _callRecognize.Async(request, callSettings);
}
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override RecognizeResponse Recognize(
RecognizeRequest request,
gaxgrpc::CallSettings callSettings = null)
{
Modify_RecognizeRequest(ref request, ref callSettings);
return _callRecognize.Sync(request, callSettings);
}
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override async stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync(
LongRunningRecognizeRequest request,
gaxgrpc::CallSettings callSettings = null)
{
Modify_LongRunningRecognizeRequest(ref request, ref callSettings);
return new lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>(
await _callLongRunningRecognize.Async(request, callSettings).ConfigureAwait(false), LongRunningRecognizeOperationsClient);
}
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> LongRunningRecognize(
LongRunningRecognizeRequest request,
gaxgrpc::CallSettings callSettings = null)
{
Modify_LongRunningRecognizeRequest(ref request, ref callSettings);
return new lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>(
_callLongRunningRecognize.Sync(request, callSettings), LongRunningRecognizeOperationsClient);
}
/// <summary>
/// The long-running operations client for <c>LongRunningRecognize</c>.
/// </summary>
public override lro::OperationsClient LongRunningRecognizeOperationsClient { get; }
/// <summary>
/// Performs bidirectional streaming speech recognition: receive results while
/// sending audio. This method is only available via the gRPC API (not REST).
/// </summary>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <param name="streamingSettings">
/// If not null, applies streaming overrides to this RPC call.
/// </param>
/// <returns>
/// The client-server stream.
/// </returns>
public override StreamingRecognizeStream StreamingRecognize(
gaxgrpc::CallSettings callSettings = null,
gaxgrpc::BidirectionalStreamingSettings streamingSettings = null)
{
Modify_StreamingRecognizeRequestCallSettings(ref callSettings);
gaxgrpc::BidirectionalStreamingSettings effectiveStreamingSettings =
streamingSettings ?? _callStreamingRecognize.StreamingSettings;
grpccore::AsyncDuplexStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> call =
_callStreamingRecognize.Call(callSettings);
gaxgrpc::BufferedClientStreamWriter<StreamingRecognizeRequest> writeBuffer =
new gaxgrpc::BufferedClientStreamWriter<StreamingRecognizeRequest>(
call.RequestStream, effectiveStreamingSettings.BufferedClientWriterCapacity);
return new StreamingRecognizeStreamImpl(this, call, writeBuffer);
}
internal sealed partial class StreamingRecognizeStreamImpl : StreamingRecognizeStream
{
/// <summary>
/// Construct the bidirectional streaming method for <c>StreamingRecognize</c>.
/// </summary>
/// <param name="service">The service containing this streaming method.</param>
/// <param name="call">The underlying gRPC duplex streaming call.</param>
/// <param name="writeBuffer">The <see cref="gaxgrpc::BufferedClientStreamWriter{StreamingRecognizeRequest}"/>
/// instance associated with this streaming call.</param>
public StreamingRecognizeStreamImpl(
SpeechClientImpl service,
grpccore::AsyncDuplexStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> call,
gaxgrpc::BufferedClientStreamWriter<StreamingRecognizeRequest> writeBuffer)
{
_service = service;
GrpcCall = call;
_writeBuffer = writeBuffer;
}
private SpeechClientImpl _service;
private gaxgrpc::BufferedClientStreamWriter<StreamingRecognizeRequest> _writeBuffer;
private StreamingRecognizeRequest ModifyRequest(StreamingRecognizeRequest request)
{
_service.Modify_StreamingRecognizeRequestRequest(ref request);
return request;
}
/// <inheritdoc/>
public override grpccore::AsyncDuplexStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> GrpcCall { get; }
/// <inheritdoc/>
public override stt::Task TryWriteAsync(StreamingRecognizeRequest message) =>
_writeBuffer.TryWriteAsync(ModifyRequest(message));
/// <inheritdoc/>
public override stt::Task WriteAsync(StreamingRecognizeRequest message) =>
_writeBuffer.WriteAsync(ModifyRequest(message));
/// <inheritdoc/>
public override stt::Task TryWriteAsync(StreamingRecognizeRequest message, grpccore::WriteOptions options) =>
_writeBuffer.TryWriteAsync(ModifyRequest(message), options);
/// <inheritdoc/>
public override stt::Task WriteAsync(StreamingRecognizeRequest message, grpccore::WriteOptions options) =>
_writeBuffer.WriteAsync(ModifyRequest(message), options);
/// <inheritdoc/>
public override stt::Task TryWriteCompleteAsync() =>
_writeBuffer.TryWriteCompleteAsync();
/// <inheritdoc/>
public override stt::Task WriteCompleteAsync() =>
_writeBuffer.WriteCompleteAsync();
/// <inheritdoc/>
public override scg::IAsyncEnumerator<StreamingRecognizeResponse> ResponseStream =>
GrpcCall.ResponseStream;
}
}
// Partial classes to enable page-streaming
// Partial Grpc class to enable LRO client creation
public static partial class Speech
{
public partial class SpeechClient
{
/// <summary>
/// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as this client.
/// </summary>
/// <returns>A new Operations client for the same target as this client.</returns>
public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker);
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Threading;
using Enyim.Caching.Configuration;
using Microsoft.Extensions.Logging;
namespace Enyim.Caching.Memcached
{
public class DefaultServerPool : IServerPool, IDisposable
{
private readonly ILogger _logger;
private IMemcachedNode[] allNodes;
private readonly IMemcachedClientConfiguration configuration;
private readonly IOperationFactory factory;
private IMemcachedNodeLocator nodeLocator;
private readonly object DeadSync = new Object();
private System.Threading.Timer resurrectTimer;
private bool isTimerActive;
private readonly int deadTimeoutMsec;
private bool isDisposed;
private event Action<IMemcachedNode> nodeFailed;
public DefaultServerPool(
IMemcachedClientConfiguration configuration,
IOperationFactory opFactory,
ILogger logger)
{
if (configuration == null) throw new ArgumentNullException("socketConfig");
if (opFactory == null) throw new ArgumentNullException("opFactory");
this.configuration = configuration;
this.factory = opFactory;
this.deadTimeoutMsec = (int)this.configuration.SocketPool.DeadTimeout.TotalMilliseconds;
_logger = logger;
}
~DefaultServerPool()
{
try { ((IDisposable)this).Dispose(); }
catch { }
}
protected virtual IMemcachedNode CreateNode(EndPoint endpoint)
{
return new MemcachedNode(endpoint, this.configuration.SocketPool, _logger);
}
private void rezCallback(object state)
{
var isDebug = _logger.IsEnabled(LogLevel.Debug);
if (isDebug) _logger.LogDebug("Checking the dead servers.");
// how this works:
// 1. timer is created but suspended
// 2. Locate encounters a dead server, so it starts the timer which will trigger after deadTimeout has elapsed
// 3. if another server goes down before the timer is triggered, nothing happens in Locate (isRunning == true).
// however that server will be inspected sooner than Dead Timeout.
// S1 died S2 died dead timeout
// |----*--------*------------*-
// | |
// timer start both servers are checked here
// 4. we iterate all the servers and record it in another list
// 5. if we found a dead server whihc responds to Ping(), the locator will be reinitialized
// 6. if at least one server is still down (Ping() == false), we restart the timer
// 7. if all servers are up, we set isRunning to false, so the timer is suspended
// 8. GOTO 2
lock (this.DeadSync)
{
if (this.isDisposed)
{
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("IsAlive timer was triggered but the pool is already disposed. Ignoring.");
return;
}
var nodes = this.allNodes;
var aliveList = new List<IMemcachedNode>(nodes.Length);
var changed = false;
var deadCount = 0;
for (var i = 0; i < nodes.Length; i++)
{
var n = nodes[i];
if (n.IsAlive)
{
if (isDebug) _logger.LogDebug("Alive: {0}", n.EndPoint);
aliveList.Add(n);
}
else
{
if (isDebug) _logger.LogDebug("Dead: {0}", n.EndPoint);
if (n.Ping())
{
changed = true;
aliveList.Add(n);
if (isDebug) _logger.LogDebug("Ping ok.");
}
else
{
if (isDebug) _logger.LogDebug("Still dead.");
deadCount++;
}
}
}
// reinit the locator
if (changed)
{
if (isDebug) _logger.LogDebug("Reinitializing the locator.");
this.nodeLocator.Initialize(aliveList);
}
// stop or restart the timer
if (deadCount == 0)
{
if (isDebug) _logger.LogDebug("deadCount == 0, stopping the timer.");
this.isTimerActive = false;
}
else
{
if (isDebug) _logger.LogDebug("deadCount == {0}, starting the timer.", deadCount);
this.resurrectTimer.Change(this.deadTimeoutMsec, Timeout.Infinite);
}
}
}
private void NodeFail(IMemcachedNode node)
{
var isDebug = _logger.IsEnabled(LogLevel.Debug);
if (isDebug) _logger.LogDebug("Node {0} is dead.", node.EndPoint);
// the timer is stopped until we encounter the first dead server
// when we have one, we trigger it and it will run after DeadTimeout has elapsed
lock (this.DeadSync)
{
if (this.isDisposed)
{
if (_logger.IsEnabled(LogLevel.Warning)) _logger.LogWarning("Got a node fail but the pool is already disposed. Ignoring.");
return;
}
// bubble up the fail event to the client
var fail = this.nodeFailed;
if (fail != null)
fail(node);
// re-initialize the locator
var newLocator = this.configuration.CreateNodeLocator();
newLocator.Initialize(allNodes.Where(n => n.IsAlive).ToArray());
Interlocked.Exchange(ref this.nodeLocator, newLocator);
// the timer is stopped until we encounter the first dead server
// when we have one, we trigger it and it will run after DeadTimeout has elapsed
if (!this.isTimerActive)
{
if (isDebug) _logger.LogDebug("Starting the recovery timer.");
if (this.resurrectTimer == null)
this.resurrectTimer = new Timer(this.rezCallback, null, this.deadTimeoutMsec, Timeout.Infinite);
else
this.resurrectTimer.Change(this.deadTimeoutMsec, Timeout.Infinite);
this.isTimerActive = true;
if (isDebug) _logger.LogDebug("Timer started.");
}
}
}
#region [ IServerPool ]
IMemcachedNode IServerPool.Locate(string key)
{
var node = this.nodeLocator.Locate(key);
return node;
}
IOperationFactory IServerPool.OperationFactory
{
get { return this.factory; }
}
IEnumerable<IMemcachedNode> IServerPool.GetWorkingNodes()
{
return this.nodeLocator.GetWorkingNodes();
}
void IServerPool.Start()
{
this.allNodes = this.configuration.Servers.
Select(ep =>
{
var node = this.CreateNode(ep);
node.Failed += this.NodeFail;
return node;
}).
ToArray();
// initialize the locator
var locator = this.configuration.CreateNodeLocator();
locator.Initialize(allNodes);
this.nodeLocator = locator;
}
event Action<IMemcachedNode> IServerPool.NodeFailed
{
add { this.nodeFailed += value; }
remove { this.nodeFailed -= value; }
}
#endregion
#region [ IDisposable ]
void IDisposable.Dispose()
{
GC.SuppressFinalize(this);
lock (this.DeadSync)
{
if (this.isDisposed) return;
this.isDisposed = true;
// dispose the locator first, maybe it wants to access
// the nodes one last time
var nd = this.nodeLocator as IDisposable;
if (nd != null)
try { nd.Dispose(); }
catch (Exception e) { _logger.LogError(nameof(DefaultServerPool), e); }
this.nodeLocator = null;
for (var i = 0; i < this.allNodes.Length; i++)
try { this.allNodes[i].Dispose(); }
catch (Exception e) { _logger.LogError(nameof(DefaultServerPool), e); }
// stop the timer
if (this.resurrectTimer != null)
using (this.resurrectTimer)
this.resurrectTimer.Change(Timeout.Infinite, Timeout.Infinite);
this.allNodes = null;
this.resurrectTimer = null;
}
}
#endregion
}
}
#region [ License information ]
/* ************************************************************
*
* Copyright (c) 2010 Attila Kisk? enyim.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ************************************************************/
#endregion
| |
// ImageListView - A listview control for image files
// Copyright (C) 2009 Ozgur Ozcitak
//
// 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.
//
// Ozgur Ozcitak (ozcitak@yahoo.com)
//
// Theme support coded by Robby
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Reflection;
namespace Manina.Windows.Forms
{
/// <summary>
/// Represents the color palette of the image list view.
/// </summary>
[TypeConverter(typeof(ImageListViewColorTypeConverter))]
public class ImageListViewColor
{
#region Member Variables
// control background color
Color mControlBackColor;
Color mDisabledBackColor;
// item colors
Color mBackColor;
Color mBorderColor;
Color mUnFocusedColor1;
Color mUnFocusedColor2;
Color mUnFocusedBorderColor;
Color mUnFocusedForeColor;
Color mForeColor;
Color mHoverColor1;
Color mHoverColor2;
Color mHoverBorderColor;
Color mInsertionCaretColor;
Color mSelectedColor1;
Color mSelectedColor2;
Color mSelectedBorderColor;
Color mSelectedForeColor;
Color mDisabledColor1;
Color mDisabledColor2;
Color mDisabledBorderColor;
Color mDisabledForeColor;
// thumbnail & pane
Color mImageInnerBorderColor;
Color mImageOuterBorderColor;
// details view
Color mCellForeColor;
Color mColumnHeaderBackColor1;
Color mColumnHeaderBackColor2;
Color mColumnHeaderForeColor;
Color mColumnHeaderHoverColor1;
Color mColumnHeaderHoverColor2;
Color mColumnSelectColor;
Color mColumnSeparatorColor;
Color mAlternateBackColor;
Color mAlternateCellForeColor;
// pane
Color mPaneBackColor;
Color mPaneSeparatorColor;
Color mPaneLabelColor;
// selection rectangle
Color mSelectionRectangleColor1;
Color mSelectionRectangleColor2;
Color mSelectionRectangleBorderColor;
#endregion
#region Properties
/// <summary>
/// Gets or sets the background color of the ImageListView control.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background color of the ImageListView control.")]
[DefaultValue(typeof(Color), "Window")]
public Color ControlBackColor
{
get { return mControlBackColor; }
set { mControlBackColor = value; }
}
/// <summary>
/// Gets or sets the background color of the ImageListView control in its disabled state.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background color of the ImageListView control in its disabled state.")]
[DefaultValue(typeof(Color), "Control")]
public Color DisabledBackColor
{
get { return mDisabledBackColor; }
set { mDisabledBackColor = value; }
}
/// <summary>
/// Gets or sets the background color of the ImageListViewItem.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background color of the ImageListViewItem.")]
[DefaultValue(typeof(Color), "Window")]
public Color BackColor
{
get { return mBackColor; }
set { mBackColor = value; }
}
/// <summary>
/// Gets or sets the background color of alternating cells in Details View.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the background color of alternating cells in Details View.")]
[DefaultValue(typeof(Color), "Window")]
public Color AlternateBackColor
{
get { return mAlternateBackColor; }
set { mAlternateBackColor = value; }
}
/// <summary>
/// Gets or sets the border color of the ImageListViewItem.
/// </summary>
[Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem.")]
[DefaultValue(typeof(Color), "64, 128, 128, 128")]
public Color BorderColor
{
get { return mBorderColor; }
set { mBorderColor = value; }
}
/// <summary>
/// Gets or sets the foreground color of the ImageListViewItem.
/// </summary>
[Category("Appearance"), Description("Gets or sets the foreground color of the ImageListViewItem.")]
[DefaultValue(typeof(Color), "ControlText")]
public Color ForeColor
{
get { return mForeColor; }
set { mForeColor = value; }
}
/// <summary>
/// Gets or sets the background gradient color1 of the ImageListViewItem if the control is not focused.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color1 of the ImageListViewItem if the control is not focused.")]
[DefaultValue(typeof(Color), "16, 128, 128, 128")]
public Color UnFocusedColor1
{
get { return mUnFocusedColor1; }
set { mUnFocusedColor1 = value; }
}
/// <summary>
/// Gets or sets the background gradient color2 of the ImageListViewItem if the control is not focused.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color2 of the ImageListViewItem if the control is not focused.")]
[DefaultValue(typeof(Color), "64, 128, 128, 128")]
public Color UnFocusedColor2
{
get { return mUnFocusedColor2; }
set { mUnFocusedColor2 = value; }
}
/// <summary>
/// Gets or sets the border color of the ImageListViewItem if the control is not focused.
/// </summary>
[Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the control is not focused.")]
[DefaultValue(typeof(Color), "128, 128, 128, 128")]
public Color UnFocusedBorderColor
{
get { return mUnFocusedBorderColor; }
set { mUnFocusedBorderColor = value; }
}
/// <summary>
/// Gets or sets the fore color of the ImageListViewItem if the control is not focused.
/// </summary>
[Category("Appearance"), Description("Gets or sets the fore color of the ImageListViewItem if the control is not focused.")]
[DefaultValue(typeof(Color), "ControlText")]
public Color UnFocusedForeColor
{
get { return mUnFocusedForeColor; }
set { mUnFocusedForeColor = value; }
}
/// <summary>
/// Gets or sets the background gradient color1 if the ImageListViewItem is hovered.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color1 if the ImageListViewItem is hovered.")]
[DefaultValue(typeof(Color), "8, 10, 36, 106")]
public Color HoverColor1
{
get { return mHoverColor1; }
set { mHoverColor1 = value; }
}
/// <summary>
/// Gets or sets the background gradient color2 if the ImageListViewItem is hovered.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color2 if the ImageListViewItem is hovered.")]
[DefaultValue(typeof(Color), "64, 10, 36, 106")]
public Color HoverColor2
{
get { return mHoverColor2; }
set { mHoverColor2 = value; }
}
/// <summary>
/// Gets or sets the border color of the ImageListViewItem if the item is hovered.
/// </summary>
[Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the item is hovered.")]
[DefaultValue(typeof(Color), "64, 10, 36, 106")]
public Color HoverBorderColor
{
get { return mHoverBorderColor; }
set { mHoverBorderColor = value; }
}
/// <summary>
/// Gets or sets the color of the insertion caret.
/// </summary>
[Category("Appearance"), Description("Gets or sets the color of the insertion caret.")]
[DefaultValue(typeof(Color), "Highlight")]
public Color InsertionCaretColor
{
get { return mInsertionCaretColor; }
set { mInsertionCaretColor = value; }
}
/// <summary>
/// Gets or sets the background gradient color1 if the ImageListViewItem is selected.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color1 if the ImageListViewItem is selected.")]
[DefaultValue(typeof(Color), "16, 10, 36, 106")]
public Color SelectedColor1
{
get { return mSelectedColor1; }
set { mSelectedColor1 = value; }
}
/// <summary>
/// Gets or sets the background gradient color2 if the ImageListViewItem is selected.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color2 if the ImageListViewItem is selected.")]
[DefaultValue(typeof(Color), "128, 10, 36, 106")]
public Color SelectedColor2
{
get { return mSelectedColor2; }
set { mSelectedColor2 = value; }
}
/// <summary>
/// Gets or sets the border color of the ImageListViewItem if the item is selected.
/// </summary>
[Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the item is selected.")]
[DefaultValue(typeof(Color), "128, 10, 36, 106")]
public Color SelectedBorderColor
{
get { return mSelectedBorderColor; }
set { mSelectedBorderColor = value; }
}
/// <summary>
/// Gets or sets the fore color of the ImageListViewItem if the item is selected.
/// </summary>
[Category("Appearance"), Description("Gets or sets the fore color of the ImageListViewItem if the item is selected.")]
[DefaultValue(typeof(Color), "ControlText")]
public Color SelectedForeColor
{
get { return mSelectedForeColor; }
set { mSelectedForeColor = value; }
}
/// <summary>
/// Gets or sets the background gradient color1 if the ImageListViewItem is disabled.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color1 if the ImageListViewItem is disabled.")]
[DefaultValue(typeof(Color), "0, 128, 128, 128")]
public Color DisabledColor1
{
get { return mDisabledColor1; }
set { mDisabledColor1 = value; }
}
/// <summary>
/// Gets or sets the background gradient color2 if the ImageListViewItem is disabled.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color2 if the ImageListViewItem is disabled.")]
[DefaultValue(typeof(Color), "32, 128, 128, 128")]
public Color DisabledColor2
{
get { return mDisabledColor2; }
set { mDisabledColor2 = value; }
}
/// <summary>
/// Gets or sets the border color of the ImageListViewItem if the item is disabled.
/// </summary>
[Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the item is disabled.")]
[DefaultValue(typeof(Color), "32, 128, 128, 128")]
public Color DisabledBorderColor
{
get { return mDisabledBorderColor; }
set { mDisabledBorderColor = value; }
}
/// <summary>
/// Gets or sets the fore color of the ImageListViewItem if the item is disabled.
/// </summary>
[Category("Appearance"), Description("Gets or sets the fore color of the ImageListViewItem if the item is disabled.")]
[DefaultValue(typeof(Color), "128, 128, 128")]
public Color DisabledForeColor
{
get { return mDisabledForeColor; }
set { mDisabledForeColor = value; }
}
/// <summary>
/// Gets or sets the background gradient color1 of the column header.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the cells background color1 of the column header.")]
[DefaultValue(typeof(Color), "32, 212, 208, 200")]
public Color ColumnHeaderBackColor1
{
get { return mColumnHeaderBackColor1; }
set { mColumnHeaderBackColor1 = value; }
}
/// <summary>
/// Gets or sets the background gradient color2 of the column header.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the cells background color2 of the column header.")]
[DefaultValue(typeof(Color), "196, 212, 208, 200")]
public Color ColumnHeaderBackColor2
{
get { return mColumnHeaderBackColor2; }
set { mColumnHeaderBackColor2 = value; }
}
/// <summary>
/// Gets or sets the background hover gradient color1 of the column header.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the background hover color1 of the column header.")]
[DefaultValue(typeof(Color), "16, 10, 36, 106")]
public Color ColumnHeaderHoverColor1
{
get { return mColumnHeaderHoverColor1; }
set { mColumnHeaderHoverColor1 = value; }
}
/// <summary>
/// Gets or sets the background hover gradient color2 of the column header.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the background hover color2 of the column header.")]
[DefaultValue(typeof(Color), "64, 10, 36, 106")]
public Color ColumnHeaderHoverColor2
{
get { return mColumnHeaderHoverColor2; }
set { mColumnHeaderHoverColor2 = value; }
}
/// <summary>
/// Gets or sets the cells foreground color of the column header text.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the cells foreground color of the column header text.")]
[DefaultValue(typeof(Color), "WindowText")]
public Color ColumnHeaderForeColor
{
get { return mColumnHeaderForeColor; }
set { mColumnHeaderForeColor = value; }
}
/// <summary>
/// Gets or sets the cells background color if column is selected in Details View.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the cells background color if column is selected in Details View.")]
[DefaultValue(typeof(Color), "16, 128, 128, 128")]
public Color ColumnSelectColor
{
get { return mColumnSelectColor; }
set { mColumnSelectColor = value; }
}
/// <summary>
/// Gets or sets the color of the separator in Details View.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the color of the separator in Details View.")]
[DefaultValue(typeof(Color), "32, 128, 128, 128")]
public Color ColumnSeparatorColor
{
get { return mColumnSeparatorColor; }
set { mColumnSeparatorColor = value; }
}
/// <summary>
/// Gets or sets the foreground color of the cell text in Details View.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the foreground color of the cell text in Details View.")]
[DefaultValue(typeof(Color), "ControlText")]
public Color CellForeColor
{
get { return mCellForeColor; }
set { mCellForeColor = value; }
}
/// <summary>
/// Gets or sets the foreground color of alternating cells text in Details View.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the foreground color of alternating cells text in Details View.")]
[DefaultValue(typeof(Color), "ControlText")]
public Color AlternateCellForeColor
{
get { return mAlternateCellForeColor; }
set { mAlternateCellForeColor = value; }
}
/// <summary>
/// Gets or sets the background color of the image pane.
/// </summary>
[Category("Appearance Pane View"), Description("Gets or sets the background color of the image pane.")]
[DefaultValue(typeof(Color), "16, 128, 128, 128")]
public Color PaneBackColor
{
get { return mPaneBackColor; }
set { mPaneBackColor = value; }
}
/// <summary>
/// Gets or sets the separator line color between image pane and thumbnail view.
/// </summary>
[Category("Appearance Pane View"), Description("Gets or sets the separator line color between image pane and thumbnail view.")]
[DefaultValue(typeof(Color), "128, 128, 128, 128")]
public Color PaneSeparatorColor
{
get { return mPaneSeparatorColor; }
set { mPaneSeparatorColor = value; }
}
/// <summary>
/// Gets or sets the color of labels in pane view.
/// </summary>
[Category("Appearance Pane View"), Description("Gets or sets the color of labels in pane view.")]
[DefaultValue(typeof(Color), "196, 0, 0, 0")]
public Color PaneLabelColor
{
get { return mPaneLabelColor; }
set { mPaneLabelColor = value; }
}
/// <summary>
/// Gets or sets the image inner border color for thumbnails and pane.
/// </summary>
[Category("Appearance Image"), Description("Gets or sets the image inner border color for thumbnails and pane.")]
[DefaultValue(typeof(Color), "128, 255, 255, 255")]
public Color ImageInnerBorderColor
{
get { return mImageInnerBorderColor; }
set { mImageInnerBorderColor = value; }
}
/// <summary>
/// Gets or sets the image outer border color for thumbnails and pane.
/// </summary>
[Category("Appearance Image"), Description("Gets or sets the image outer border color for thumbnails and pane.")]
[DefaultValue(typeof(Color), "128, 128, 128, 128")]
public Color ImageOuterBorderColor
{
get { return mImageOuterBorderColor; }
set { mImageOuterBorderColor = value; }
}
/// <summary>
/// Gets or sets the background color1 of the selection rectangle.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background color1 of the selection rectangle.")]
[DefaultValue(typeof(Color), "128, 10, 36, 106")]
public Color SelectionRectangleColor1
{
get { return mSelectionRectangleColor1; }
set { mSelectionRectangleColor1 = value; }
}
/// <summary>
/// Gets or sets the background color2 of the selection rectangle.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background color2 of the selection rectangle.")]
[DefaultValue(typeof(Color), "128, 10, 36, 106")]
public Color SelectionRectangleColor2
{
get { return mSelectionRectangleColor2; }
set { mSelectionRectangleColor2 = value; }
}
/// <summary>
/// Gets or sets the color of the selection rectangle border.
/// </summary>
[Category("Appearance"), Description("Gets or sets the color of the selection rectangle border.")]
[DefaultValue(typeof(Color), "Highlight")]
public Color SelectionRectangleBorderColor
{
get { return mSelectionRectangleBorderColor; }
set { mSelectionRectangleBorderColor = value; }
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the ImageListViewColor class.
/// </summary>
public ImageListViewColor()
{
// control
mControlBackColor = SystemColors.Window;
mDisabledBackColor = SystemColors.Control;
// item
mBackColor = SystemColors.Window;
mForeColor = SystemColors.ControlText;
mBorderColor = Color.FromArgb(64, SystemColors.GrayText);
mUnFocusedColor1 = Color.FromArgb(16, SystemColors.GrayText);
mUnFocusedColor2 = Color.FromArgb(64, SystemColors.GrayText);
mUnFocusedBorderColor = Color.FromArgb(128, SystemColors.GrayText);
mUnFocusedForeColor = SystemColors.ControlText;
mHoverColor1 = Color.FromArgb(8, SystemColors.Highlight);
mHoverColor2 = Color.FromArgb(64, SystemColors.Highlight);
mHoverBorderColor = Color.FromArgb(64, SystemColors.Highlight);
mSelectedColor1 = Color.FromArgb(16, SystemColors.Highlight);
mSelectedColor2 = Color.FromArgb(128, SystemColors.Highlight);
mSelectedBorderColor = Color.FromArgb(128, SystemColors.Highlight);
mSelectedForeColor = SystemColors.ControlText;
mDisabledColor1 = Color.FromArgb(0, SystemColors.GrayText);
mDisabledColor2 = Color.FromArgb(32, SystemColors.GrayText);
mDisabledBorderColor = Color.FromArgb(32, SystemColors.GrayText);
mDisabledForeColor = Color.FromArgb(128, 128, 128);
mInsertionCaretColor = SystemColors.Highlight;
// thumbnails
mImageInnerBorderColor = Color.FromArgb(128, Color.White);
mImageOuterBorderColor = Color.FromArgb(128, Color.Gray);
// details view
mColumnHeaderBackColor1 = Color.FromArgb(32, SystemColors.Control);
mColumnHeaderBackColor2 = Color.FromArgb(196, SystemColors.Control);
mColumnHeaderHoverColor1 = Color.FromArgb(16, SystemColors.Highlight);
mColumnHeaderHoverColor2 = Color.FromArgb(64, SystemColors.Highlight);
mColumnHeaderForeColor = SystemColors.WindowText;
mColumnSelectColor = Color.FromArgb(16, SystemColors.GrayText);
mColumnSeparatorColor = Color.FromArgb(32, SystemColors.GrayText);
mCellForeColor = SystemColors.ControlText;
mAlternateBackColor = SystemColors.Window;
mAlternateCellForeColor = SystemColors.ControlText;
// image pane
mPaneBackColor = Color.FromArgb(16, SystemColors.GrayText);
mPaneSeparatorColor = Color.FromArgb(128, SystemColors.GrayText);
mPaneLabelColor = Color.FromArgb(196, Color.Black);
// selection rectangle
mSelectionRectangleColor1 = Color.FromArgb(128, SystemColors.Highlight);
mSelectionRectangleColor2 = Color.FromArgb(128, SystemColors.Highlight);
mSelectionRectangleBorderColor = SystemColors.Highlight;
}
/// <summary>
/// Initializes a new instance of the ImageListViewColor class
/// from its string representation.
/// </summary>
/// <param name="definition">String representation of the object.</param>
public ImageListViewColor(string definition)
: this()
{
try
{
// First check if the color matches a predefined color setting
foreach (MemberInfo info in typeof(ImageListViewColor).GetMembers(BindingFlags.Static | BindingFlags.Public))
{
if (info.MemberType == MemberTypes.Property)
{
PropertyInfo propertyInfo = (PropertyInfo)info;
if (propertyInfo.PropertyType == typeof(ImageListViewColor))
{
// If the color setting is equal to a preset value
// return the preset
if (definition == string.Format("({0})", propertyInfo.Name) ||
definition == propertyInfo.Name)
{
ImageListViewColor presetValue = (ImageListViewColor)propertyInfo.GetValue(null, null);
CopyFrom(presetValue);
return;
}
}
}
}
// Convert color values
foreach (string line in definition.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
// Read the color setting
string[] pair = line.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
string name = pair[0].Trim();
Color color = Color.FromName(pair[1].Trim());
// Set the property value
PropertyInfo property = typeof(ImageListViewColor).GetProperty(name);
property.SetValue(this, color, null);
}
}
catch
{
throw new ArgumentException("Invalid string format", "definition");
}
}
#endregion
#region Instance Methods
/// <summary>
/// Copies color values from the given object.
/// </summary>
/// <param name="source">The source object.</param>
public void CopyFrom(ImageListViewColor source)
{
foreach (PropertyInfo info in typeof(ImageListViewColor).GetProperties())
{
// Walk through color properties
if (info.PropertyType == typeof(Color))
{
Color color = (Color)info.GetValue(source, null);
info.SetValue(this, color, null);
}
}
}
#endregion
#region Static Members
/// <summary>
/// Represents the default color theme.
/// </summary>
public static ImageListViewColor Default { get { return ImageListViewColor.GetDefaultTheme(); } }
/// <summary>
/// Represents the noir color theme.
/// </summary>
public static ImageListViewColor Noir { get { return ImageListViewColor.GetNoirTheme(); } }
/// <summary>
/// Represents the mandarin color theme.
/// </summary>
public static ImageListViewColor Mandarin { get { return ImageListViewColor.GetMandarinTheme(); } }
/// <summary>
/// Sets the color palette to default colors.
/// </summary>
private static ImageListViewColor GetDefaultTheme()
{
return new ImageListViewColor();
}
/// <summary>
/// Sets the color palette to mandarin colors.
/// </summary>
private static ImageListViewColor GetMandarinTheme()
{
ImageListViewColor c = new ImageListViewColor();
// control
c.ControlBackColor = Color.White;
c.DisabledBackColor = Color.FromArgb(220, 220, 220);
// item
c.BackColor = Color.White;
c.ForeColor = Color.FromArgb(60, 60, 60);
c.BorderColor = Color.FromArgb(187, 190, 183);
c.UnFocusedColor1 = Color.FromArgb(235, 235, 235);
c.UnFocusedColor2 = Color.FromArgb(217, 217, 217);
c.UnFocusedBorderColor = Color.FromArgb(168, 169, 161);
c.UnFocusedForeColor = Color.FromArgb(40, 40, 40);
c.HoverColor1 = Color.Transparent;
c.HoverColor2 = Color.Transparent;
c.HoverBorderColor = Color.Transparent;
c.SelectedColor1 = Color.FromArgb(244, 125, 77);
c.SelectedColor2 = Color.FromArgb(235, 110, 60);
c.SelectedBorderColor = Color.FromArgb(240, 119, 70);
c.SelectedForeColor = Color.White;
c.DisabledColor1 = Color.FromArgb(217, 217, 217);
c.DisabledColor2 = Color.FromArgb(197, 197, 197);
c.DisabledBorderColor = Color.FromArgb(128, 128, 128);
c.DisabledForeColor = Color.FromArgb(128, 128, 128);
c.InsertionCaretColor = Color.FromArgb(240, 119, 70);
// thumbnails & pane
c.ImageInnerBorderColor = Color.Transparent;
c.ImageOuterBorderColor = Color.White;
// details view
c.CellForeColor = Color.FromArgb(60, 60, 60);
c.ColumnHeaderBackColor1 = Color.FromArgb(247, 247, 247);
c.ColumnHeaderBackColor2 = Color.FromArgb(235, 235, 235);
c.ColumnHeaderHoverColor1 = Color.White;
c.ColumnHeaderHoverColor2 = Color.FromArgb(245, 245, 245);
c.ColumnHeaderForeColor = Color.FromArgb(60, 60, 60);
c.ColumnSelectColor = Color.FromArgb(34, 128, 128, 128);
c.ColumnSeparatorColor = Color.FromArgb(106, 128, 128, 128);
c.mAlternateBackColor = Color.FromArgb(234, 234, 234);
c.mAlternateCellForeColor = Color.FromArgb(40, 40, 40);
// image pane
c.PaneBackColor = Color.White;
c.PaneSeparatorColor = Color.FromArgb(216, 216, 216);
c.PaneLabelColor = Color.FromArgb(156, 156, 156);
// selection rectangle
c.SelectionRectangleColor1 = Color.FromArgb(64, 240, 116, 68);
c.SelectionRectangleColor2 = Color.FromArgb(64, 240, 116, 68);
c.SelectionRectangleBorderColor = Color.FromArgb(240, 119, 70);
return c;
}
/// <summary>
/// Sets the color palette to noir colors.
/// </summary>
private static ImageListViewColor GetNoirTheme()
{
ImageListViewColor c = new ImageListViewColor();
// control
c.ControlBackColor = Color.Black;
c.DisabledBackColor = Color.Black;
// item
c.BackColor = Color.FromArgb(0x31, 0x31, 0x31);
c.ForeColor = Color.LightGray;
c.BorderColor = Color.DarkGray;
c.UnFocusedColor1 = Color.FromArgb(16, SystemColors.GrayText);
c.UnFocusedColor2 = Color.FromArgb(64, SystemColors.GrayText);
c.UnFocusedBorderColor = Color.FromArgb(128, SystemColors.GrayText);
c.UnFocusedForeColor = Color.LightGray;
c.HoverColor1 = Color.FromArgb(64, Color.White);
c.HoverColor2 = Color.FromArgb(16, Color.White);
c.HoverBorderColor = Color.FromArgb(64, SystemColors.Highlight);
c.SelectedColor1 = Color.FromArgb(64, 96, 160);
c.SelectedColor2 = Color.FromArgb(64, 64, 96, 160);
c.SelectedBorderColor = Color.FromArgb(128, SystemColors.Highlight);
c.SelectedForeColor = Color.LightGray;
c.DisabledColor1 = Color.FromArgb(0, SystemColors.GrayText);
c.DisabledColor2 = Color.FromArgb(32, SystemColors.GrayText);
c.DisabledBorderColor = Color.FromArgb(96, SystemColors.GrayText);
c.DisabledForeColor = Color.LightGray;
c.InsertionCaretColor = Color.FromArgb(96, 144, 240);
// thumbnails & pane
c.ImageInnerBorderColor = Color.FromArgb(128, Color.White);
c.ImageOuterBorderColor = Color.FromArgb(128, Color.Gray);
// details view
c.CellForeColor = Color.WhiteSmoke;
c.ColumnHeaderBackColor1 = Color.FromArgb(32, 128, 128, 128);
c.ColumnHeaderBackColor2 = Color.FromArgb(196, 128, 128, 128);
c.ColumnHeaderHoverColor1 = Color.FromArgb(64, 96, 144, 240);
c.ColumnHeaderHoverColor2 = Color.FromArgb(196, 96, 144, 240);
c.ColumnHeaderForeColor = Color.White;
c.ColumnSelectColor = Color.FromArgb(96, 128, 128, 128);
c.ColumnSeparatorColor = Color.Gold;
c.AlternateBackColor = Color.FromArgb(0x31, 0x31, 0x31);
c.AlternateCellForeColor = Color.WhiteSmoke;
// image pane
c.PaneBackColor = Color.FromArgb(0x31, 0x31, 0x31);
c.PaneSeparatorColor = Color.Gold;
c.PaneLabelColor = SystemColors.GrayText;
// selection rectangke
c.SelectionRectangleColor1 = Color.FromArgb(160, 96, 144, 240);
c.SelectionRectangleColor2 = Color.FromArgb(32, 96, 144, 240);
c.SelectionRectangleBorderColor = Color.FromArgb(64, 96, 144, 240);
return c;
}
#endregion
#region System.Object Overrides
/// <summary>
/// Determines whether all color values of the specified
/// ImageListViewColor are equal to this instance.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>true if the two instances have the same color values;
/// otherwise false.</returns>
public override bool Equals(object obj)
{
if (obj == null)
throw new NullReferenceException();
ImageListViewColor other = obj as ImageListViewColor;
if (other == null) return false;
foreach (PropertyInfo info in typeof(ImageListViewColor).GetProperties())
{
// Walk through color properties
if (info.PropertyType == typeof(Color))
{
// Compare colors
Color color1 = (Color)info.GetValue(this, null);
Color color2 = (Color)info.GetValue(other, null);
if (color1 != color2) return false;
}
}
return true;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in
/// hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Returns a string that represents this instance.
/// </summary>
/// <returns>
/// A string that represents this instance.
/// </returns>
public override string ToString()
{
ImageListViewColor colors = this;
// First check if the color matches a predefined color setting
foreach (MemberInfo info in typeof(ImageListViewColor).GetMembers(BindingFlags.Static | BindingFlags.Public))
{
if (info.MemberType == MemberTypes.Property)
{
PropertyInfo propertyInfo = (PropertyInfo)info;
if (propertyInfo.PropertyType == typeof(ImageListViewColor))
{
ImageListViewColor presetValue = (ImageListViewColor)propertyInfo.GetValue(null, null);
// If the color setting is equal to a preset value
// return the name of the preset
if (colors.Equals(presetValue))
return string.Format("({0})", propertyInfo.Name);
}
}
}
// Serialize all colors which are different from the default setting
List<string> lines = new List<string>();
foreach (PropertyInfo info in typeof(ImageListViewColor).GetProperties())
{
// Walk through color properties
if (info.PropertyType == typeof(Color))
{
// Get property name
string name = info.Name;
// Get the current value
Color color = (Color)info.GetValue(colors, null);
// Find the default value atribute
Attribute[] attributes = (Attribute[])info.GetCustomAttributes(typeof(DefaultValueAttribute), false);
if (attributes.Length != 0)
{
// Get the default value
DefaultValueAttribute attribute = (DefaultValueAttribute)attributes[0];
Color defaultColor = (Color)attribute.Value;
// Serialize only if colors are different
if (color != defaultColor)
{
lines.Add(string.Format("{0} = {1}", name, color.Name));
}
}
}
}
return string.Join("; ", lines.ToArray());
}
#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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\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;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithLowerAndUpperDouble()
{
var test = new VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperDouble();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperDouble
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Double[] values = new Double[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetDouble();
}
Vector256<Double> value = Vector256.Create(values[0], values[1], values[2], values[3]);
Vector128<Double> lowerResult = value.GetLower();
Vector128<Double> upperResult = value.GetUpper();
ValidateGetResult(lowerResult, upperResult, values);
Vector256<Double> result = value.WithLower(upperResult);
result = result.WithUpper(lowerResult);
ValidateWithResult(result, values);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Double[] values = new Double[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetDouble();
}
Vector256<Double> value = Vector256.Create(values[0], values[1], values[2], values[3]);
object lowerResult = typeof(Vector256)
.GetMethod(nameof(Vector256.GetLower))
.MakeGenericMethod(typeof(Double))
.Invoke(null, new object[] { value });
object upperResult = typeof(Vector256)
.GetMethod(nameof(Vector256.GetUpper))
.MakeGenericMethod(typeof(Double))
.Invoke(null, new object[] { value });
ValidateGetResult((Vector128<Double>)(lowerResult), (Vector128<Double>)(upperResult), values);
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.WithLower))
.MakeGenericMethod(typeof(Double))
.Invoke(null, new object[] { value, upperResult });
result = typeof(Vector256)
.GetMethod(nameof(Vector256.WithUpper))
.MakeGenericMethod(typeof(Double))
.Invoke(null, new object[] { result, lowerResult });
ValidateWithResult((Vector256<Double>)(result), values);
}
private void ValidateGetResult(Vector128<Double> lowerResult, Vector128<Double> upperResult, Double[] values, [CallerMemberName] string method = "")
{
Double[] lowerElements = new Double[ElementCount / 2];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref lowerElements[0]), lowerResult);
Double[] upperElements = new Double[ElementCount / 2];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref upperElements[0]), upperResult);
ValidateGetResult(lowerElements, upperElements, values, method);
}
private void ValidateGetResult(Double[] lowerResult, Double[] upperResult, Double[] values, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount / 2; i++)
{
if (lowerResult[i] != values[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Double>.GetLower(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", lowerResult)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = true;
for (int i = ElementCount / 2; i < ElementCount; i++)
{
if (upperResult[i - (ElementCount / 2)] != values[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Double>.GetUpper(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", upperResult)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
private void ValidateWithResult(Vector256<Double> result, Double[] values, [CallerMemberName] string method = "")
{
Double[] resultElements = new Double[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, method);
}
private void ValidateWithResult(Double[] result, Double[] values, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount / 2; i++)
{
if (result[i] != values[i + (ElementCount / 2)])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Double.WithLower(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = true;
for (int i = ElementCount / 2; i < ElementCount; i++)
{
if (result[i] != values[i - (ElementCount / 2)])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Double.WithUpper(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. 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.Linq;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.DependencyModel;
using NuGet.Frameworks;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectModel;
namespace Microsoft.DotNet.Cli.Utils
{
internal class DepsJsonBuilder
{
private readonly VersionFolderPathResolver _versionFolderPathResolver;
public DepsJsonBuilder()
{
// This resolver is only used for building file names, so that base path is not required.
_versionFolderPathResolver = new VersionFolderPathResolver(path: null);
}
public DependencyContext Build(
SingleProjectInfo mainProjectInfo,
CompilationOptions compilationOptions,
LockFile lockFile,
NuGetFramework framework,
string runtime)
{
bool includeCompilationLibraries = compilationOptions != null;
LockFileTarget lockFileTarget = lockFile.GetTarget(framework, runtime);
IEnumerable<LockFileTargetLibrary> runtimeExports = lockFileTarget.GetRuntimeLibraries();
IEnumerable<LockFileTargetLibrary> compilationExports =
includeCompilationLibraries ?
lockFileTarget.GetCompileLibraries() :
Enumerable.Empty<LockFileTargetLibrary>();
var dependencyLookup = compilationExports
.Concat(runtimeExports)
.Distinct()
.Select(library => new Dependency(library.Name, library.Version.ToString()))
.ToDictionary(dependency => dependency.Name, StringComparer.OrdinalIgnoreCase);
var libraryLookup = lockFile.Libraries.ToDictionary(l => l.Name, StringComparer.OrdinalIgnoreCase);
var runtimeSignature = GenerateRuntimeSignature(runtimeExports);
IEnumerable<RuntimeLibrary> runtimeLibraries =
GetLibraries(runtimeExports, libraryLookup, dependencyLookup, runtime: true).Cast<RuntimeLibrary>();
IEnumerable<CompilationLibrary> compilationLibraries;
if (includeCompilationLibraries)
{
CompilationLibrary projectCompilationLibrary = GetProjectCompilationLibrary(
mainProjectInfo,
lockFile,
lockFileTarget,
dependencyLookup);
compilationLibraries = new[] { projectCompilationLibrary }
.Concat(
GetLibraries(compilationExports, libraryLookup, dependencyLookup, runtime: false)
.Cast<CompilationLibrary>());
}
else
{
compilationLibraries = Enumerable.Empty<CompilationLibrary>();
}
return new DependencyContext(
new TargetInfo(framework.DotNetFrameworkName, runtime, runtimeSignature, lockFileTarget.IsPortable()),
compilationOptions ?? CompilationOptions.Default,
compilationLibraries,
runtimeLibraries,
new RuntimeFallbacks[] { });
}
private static string GenerateRuntimeSignature(IEnumerable<LockFileTargetLibrary> runtimeExports)
{
var sha1 = SHA1.Create();
var builder = new StringBuilder();
var packages = runtimeExports
.Where(libraryExport => libraryExport.Type == "package");
var separator = "|";
foreach (var libraryExport in packages)
{
builder.Append(libraryExport.Name);
builder.Append(separator);
builder.Append(libraryExport.Version.ToString());
builder.Append(separator);
}
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString()));
builder.Clear();
foreach (var hashByte in hash)
{
builder.AppendFormat("{0:x2}", hashByte);
}
return builder.ToString();
}
private List<Dependency> GetProjectDependencies(
LockFile lockFile,
LockFileTarget lockFileTarget,
Dictionary<string, Dependency> dependencyLookup)
{
List<Dependency> dependencies = new List<Dependency>();
IEnumerable<ProjectFileDependencyGroup> projectFileDependencies = lockFile
.ProjectFileDependencyGroups
.Where(dg => dg.FrameworkName == string.Empty ||
dg.FrameworkName == lockFileTarget.TargetFramework.DotNetFrameworkName);
foreach (string projectFileDependency in projectFileDependencies.SelectMany(dg => dg.Dependencies))
{
int separatorIndex = projectFileDependency.IndexOf(' ');
string dependencyName = separatorIndex > 0 ?
projectFileDependency.Substring(0, separatorIndex) :
projectFileDependency;
Dependency dependency;
if (dependencyLookup.TryGetValue(dependencyName, out dependency))
{
dependencies.Add(dependency);
}
}
return dependencies;
}
private RuntimeLibrary GetProjectRuntimeLibrary(
SingleProjectInfo projectInfo,
LockFile lockFile,
LockFileTarget lockFileTarget,
Dictionary<string, Dependency> dependencyLookup)
{
RuntimeAssetGroup[] runtimeAssemblyGroups = new[] { new RuntimeAssetGroup(string.Empty, projectInfo.GetOutputName()) };
List<Dependency> dependencies = GetProjectDependencies(lockFile, lockFileTarget, dependencyLookup);
ResourceAssembly[] resourceAssemblies = projectInfo
.ResourceAssemblies
.Select(r => new ResourceAssembly(r.RelativePath, r.Culture))
.ToArray();
return new RuntimeLibrary(
type: "project",
name: projectInfo.Name,
version: projectInfo.Version,
hash: string.Empty,
runtimeAssemblyGroups: runtimeAssemblyGroups,
nativeLibraryGroups: new RuntimeAssetGroup[] { },
resourceAssemblies: resourceAssemblies,
dependencies: dependencies.ToArray(),
serviceable: false);
}
private CompilationLibrary GetProjectCompilationLibrary(
SingleProjectInfo projectInfo,
LockFile lockFile,
LockFileTarget lockFileTarget,
Dictionary<string, Dependency> dependencyLookup)
{
List<Dependency> dependencies = GetProjectDependencies(lockFile, lockFileTarget, dependencyLookup);
return new CompilationLibrary(
type: "project",
name: projectInfo.Name,
version: projectInfo.Version,
hash: string.Empty,
assemblies: new[] { projectInfo.GetOutputName() },
dependencies: dependencies.ToArray(),
serviceable: false);
}
private IEnumerable<Library> GetLibraries(
IEnumerable<LockFileTargetLibrary> exports,
IDictionary<string, LockFileLibrary> libraryLookup,
IDictionary<string, Dependency> dependencyLookup,
bool runtime)
{
return exports.Select(export => GetLibrary(export, libraryLookup, dependencyLookup, runtime));
}
private Library GetLibrary(
LockFileTargetLibrary export,
IDictionary<string, LockFileLibrary> libraryLookup,
IDictionary<string, Dependency> dependencyLookup,
bool runtime)
{
var type = export.Type;
// TEMPORARY: All packages are serviceable in RC2
// See https://github.com/dotnet/cli/issues/2569
var serviceable = export.Type == "package";
var libraryDependencies = new HashSet<Dependency>();
foreach (PackageDependency libraryDependency in export.Dependencies)
{
Dependency dependency;
if (dependencyLookup.TryGetValue(libraryDependency.Id, out dependency))
{
libraryDependencies.Add(dependency);
}
}
string hash = string.Empty;
string path = null;
string hashPath = null;
LockFileLibrary library;
if (libraryLookup.TryGetValue(export.Name, out library))
{
if (!string.IsNullOrEmpty(library.Sha512))
{
hash = "sha512-" + library.Sha512;
hashPath = _versionFolderPathResolver.GetHashFileName(export.Name, export.Version);
}
path = library.Path;
}
if (runtime)
{
return new RuntimeLibrary(
type.ToLowerInvariant(),
export.Name,
export.Version.ToString(),
hash,
CreateRuntimeAssemblyGroups(export),
CreateNativeLibraryGroups(export),
export.ResourceAssemblies.FilterPlaceHolderFiles().Select(CreateResourceAssembly),
libraryDependencies,
serviceable,
path,
hashPath);
}
else
{
IEnumerable<string> assemblies = export
.CompileTimeAssemblies
.FilterPlaceHolderFiles()
.Select(libraryAsset => libraryAsset.Path);
return new CompilationLibrary(
type.ToString().ToLowerInvariant(),
export.Name,
export.Version.ToString(),
hash,
assemblies,
libraryDependencies,
serviceable,
path,
hashPath);
}
}
private IReadOnlyList<RuntimeAssetGroup> CreateRuntimeAssemblyGroups(LockFileTargetLibrary export)
{
List<RuntimeAssetGroup> assemblyGroups = new List<RuntimeAssetGroup>();
assemblyGroups.Add(
new RuntimeAssetGroup(
string.Empty,
export.RuntimeAssemblies.FilterPlaceHolderFiles().Select(a => a.Path)));
foreach (var runtimeTargetsGroup in export.GetRuntimeTargetsGroups("runtime"))
{
assemblyGroups.Add(
new RuntimeAssetGroup(
runtimeTargetsGroup.Key,
runtimeTargetsGroup.Select(t => t.Path)));
}
return assemblyGroups;
}
private IReadOnlyList<RuntimeAssetGroup> CreateNativeLibraryGroups(LockFileTargetLibrary export)
{
List<RuntimeAssetGroup> nativeGroups = new List<RuntimeAssetGroup>();
nativeGroups.Add(
new RuntimeAssetGroup(
string.Empty,
export.NativeLibraries.FilterPlaceHolderFiles().Select(a => a.Path)));
foreach (var runtimeTargetsGroup in export.GetRuntimeTargetsGroups("native"))
{
nativeGroups.Add(
new RuntimeAssetGroup(
runtimeTargetsGroup.Key,
runtimeTargetsGroup.Select(t => t.Path)));
}
return nativeGroups;
}
private ResourceAssembly CreateResourceAssembly(LockFileItem resourceAssembly)
{
string locale;
if (!resourceAssembly.Properties.TryGetValue("locale", out locale))
{
locale = null;
}
return new ResourceAssembly(resourceAssembly.Path, locale);
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Threading;
using System.Web;
using ASC.Core;
using ASC.Core.Users;
using ASC.Files.Core;
using ASC.MessagingSystem;
using ASC.Web.Core.Files;
using ASC.Web.Files.Classes;
using ASC.Web.Files.Helpers;
using ASC.Web.Files.Resources;
using ASC.Web.Studio.Core;
using File = ASC.Files.Core.File;
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Web.Files.Utils
{
public static class FileUploader
{
public static File Exec(string folderId, string title, long contentLength, Stream data)
{
return Exec(folderId, title, contentLength, data, !FilesSettings.UpdateIfExist);
}
public static File Exec(string folderId, string title, long contentLength, Stream data, bool createNewIfExist, bool deleteConvertStatus = true)
{
if (contentLength <= 0)
throw new Exception(FilesCommonResource.ErrorMassage_EmptyFile);
var file = VerifyFileUpload(folderId, title, contentLength, !createNewIfExist);
using (var dao = Global.DaoFactory.GetFileDao())
{
file = dao.SaveFile(file, data);
}
using (var linkDao = Global.GetLinkDao())
{
linkDao.DeleteAllLink(file.ID);
}
FileMarker.MarkAsNew(file);
if (FileConverter.EnableAsUploaded && FileConverter.MustConvert(file))
FileConverter.ExecAsync(file, deleteConvertStatus);
return file;
}
public static File VerifyFileUpload(string folderId, string fileName, bool updateIfExists, string relativePath = null)
{
fileName = Global.ReplaceInvalidCharsAndTruncate(fileName);
if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(fileName)))
throw new NotSupportedException(FilesCommonResource.ErrorMassage_NotSupportedFormat);
folderId = GetFolderId(folderId, string.IsNullOrEmpty(relativePath) ? null : relativePath.Split('/').ToList());
using (var fileDao = Global.DaoFactory.GetFileDao())
{
var file = fileDao.GetFile(folderId, fileName);
if (updateIfExists && CanEdit(file))
{
file.Title = fileName;
file.ConvertedType = null;
file.Comment = FilesCommonResource.CommentUpload;
file.Version++;
file.VersionGroup++;
file.Encrypted = false;
file.ThumbnailStatus = Thumbnail.Waiting;
return file;
}
}
return new File { FolderID = folderId, Title = fileName };
}
public static File VerifyFileUpload(string folderId, string fileName, long fileSize, bool updateIfExists)
{
if (fileSize <= 0)
throw new Exception(FilesCommonResource.ErrorMassage_EmptyFile);
var maxUploadSize = GetMaxFileSize(folderId);
if (fileSize > maxUploadSize)
throw FileSizeComment.GetFileSizeException(maxUploadSize);
var file = VerifyFileUpload(folderId, fileName, updateIfExists);
file.ContentLength = fileSize;
return file;
}
private static bool CanEdit(File file)
{
return file != null
&& Global.GetFilesSecurity().CanEdit(file)
&& !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()
&& !EntryManager.FileLockedForMe(file.ID)
&& !FileTracker.IsEditing(file.ID)
&& file.RootFolderType != FolderType.TRASH
&& !file.Encrypted;
}
private static string GetFolderId(object folderId, IList<string> relativePath)
{
using (var folderDao = Global.DaoFactory.GetFolderDao())
{
var folder = folderDao.GetFolder(folderId);
if (folder == null)
throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound);
if (!Global.GetFilesSecurity().CanCreate(folder))
throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
if (relativePath != null && relativePath.Any())
{
var subFolderTitle = Global.ReplaceInvalidCharsAndTruncate(relativePath.FirstOrDefault());
if (!string.IsNullOrEmpty(subFolderTitle))
{
folder = folderDao.GetFolder(subFolderTitle, folder.ID);
if (folder == null)
{
folderId = folderDao.SaveFolder(new Folder { Title = subFolderTitle, ParentFolderID = folderId });
folder = folderDao.GetFolder(folderId);
FilesMessageService.Send(folder, HttpContext.Current.Request, MessageAction.FolderCreated, folder.Title);
}
folderId = folder.ID;
relativePath.RemoveAt(0);
folderId = GetFolderId(folderId, relativePath);
}
}
}
return folderId.ToString();
}
#region chunked upload
public static File VerifyChunkedUpload(string folderId, string fileName, long fileSize, bool updateIfExists, string relativePath = null)
{
var maxUploadSize = GetMaxFileSize(folderId, true);
if (fileSize > maxUploadSize)
throw FileSizeComment.GetFileSizeException(maxUploadSize);
var file = VerifyFileUpload(folderId, fileName, updateIfExists, relativePath);
file.ContentLength = fileSize;
return file;
}
public static ChunkedUploadSession InitiateUpload(string folderId, string fileId, string fileName, long contentLength, bool encrypted)
{
if (string.IsNullOrEmpty(folderId))
folderId = null;
if (string.IsNullOrEmpty(fileId))
fileId = null;
var file = new File
{
ID = fileId,
FolderID = folderId,
Title = fileName,
ContentLength = contentLength
};
using (var dao = Global.DaoFactory.GetFileDao())
{
var uploadSession = dao.CreateUploadSession(file, contentLength);
uploadSession.Expired = uploadSession.Created + ChunkedUploadSessionHolder.SlidingExpiration;
uploadSession.Location = FilesLinkUtility.GetUploadChunkLocationUrl(uploadSession.Id);
uploadSession.TenantId = CoreContext.TenantManager.GetCurrentTenant().TenantId;
uploadSession.UserId = SecurityContext.CurrentAccount.ID;
uploadSession.FolderId = folderId;
uploadSession.CultureName = Thread.CurrentThread.CurrentUICulture.Name;
uploadSession.Encrypted = encrypted;
ChunkedUploadSessionHolder.StoreSession(uploadSession);
return uploadSession;
}
}
public static ChunkedUploadSession UploadChunk(string uploadId, Stream stream, long chunkLength)
{
var uploadSession = ChunkedUploadSessionHolder.GetSession(uploadId);
uploadSession.Expired = DateTime.UtcNow + ChunkedUploadSessionHolder.SlidingExpiration;
if (chunkLength <= 0)
{
throw new Exception(FilesCommonResource.ErrorMassage_EmptyFile);
}
if (chunkLength > SetupInfo.ChunkUploadSize)
{
throw FileSizeComment.GetFileSizeException(SetupInfo.MaxUploadSize);
}
var maxUploadSize = GetMaxFileSize(uploadSession.FolderId, uploadSession.BytesTotal > 0);
if (uploadSession.BytesUploaded + chunkLength > maxUploadSize)
{
AbortUpload(uploadSession);
throw FileSizeComment.GetFileSizeException(maxUploadSize);
}
using (var dao = Global.DaoFactory.GetFileDao())
{
dao.UploadChunk(uploadSession, stream, chunkLength);
}
if (uploadSession.BytesUploaded == uploadSession.BytesTotal)
{
using (var linkDao = Global.GetLinkDao())
{
linkDao.DeleteAllLink(uploadSession.File.ID);
}
FileMarker.MarkAsNew(uploadSession.File);
ChunkedUploadSessionHolder.RemoveSession(uploadSession);
}
else
{
ChunkedUploadSessionHolder.StoreSession(uploadSession);
}
return uploadSession;
}
public static void AbortUpload(string uploadId)
{
AbortUpload(ChunkedUploadSessionHolder.GetSession(uploadId));
}
private static void AbortUpload(ChunkedUploadSession uploadSession)
{
using (var dao = Global.DaoFactory.GetFileDao())
{
dao.AbortUploadSession(uploadSession);
}
ChunkedUploadSessionHolder.RemoveSession(uploadSession);
}
private static long GetMaxFileSize(object folderId, bool chunkedUpload = false)
{
using (var folderDao = Global.DaoFactory.GetFolderDao())
{
return folderDao.GetMaxUploadSize(folderId, chunkedUpload);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace KillrVideo.MessageBus.Transport
{
/// <summary>
/// An async producer/consumer queue.
/// </summary>
internal class AsyncQueue<T>
{
private readonly Queue<T> _queue;
private readonly int _capacity;
private readonly AsyncQueueLock _lock;
protected bool IsFull => _queue.Count == _capacity;
protected bool HasItems => _queue.Count > 0;
public AsyncQueue(int capacity)
{
_queue = new Queue<T>(capacity);
_capacity = capacity;
_lock = new AsyncQueueLock(this);
}
public async Task Enqueue(T item, CancellationToken token = default(CancellationToken))
{
// Acquire the lock for enqueueing items before modifying the queue
using (var queueLock = await _lock.GetEnqueueLock(token).ConfigureAwait(false))
{
token.ThrowIfCancellationRequested();
_queue.Enqueue(item);
}
}
public async Task<T> Dequeue(CancellationToken token = default(CancellationToken))
{
// Acquire the lock for dequeueing items before modifying the queue
T item;
using (var queueLock = await _lock.GetDequeueLock(token).ConfigureAwait(false))
{
token.ThrowIfCancellationRequested();
item = _queue.Dequeue();
}
return item;
}
/// <summary>
/// A coordination helper class that provides coordination of locking around AsyncQueue operations. Favors
/// dequeueing over enqueueing when there are Tasks waiting.
/// </summary>
private class AsyncQueueLock
{
private readonly AsyncQueue<T> _queue;
private readonly Task<Releaser> _fastPathReleaser;
private readonly Queue<TaskCompletionSource<Releaser>> _waitingEnqueue;
private readonly Queue<TaskCompletionSource<Releaser>> _waitingDequeue;
private readonly object _queueLock;
private int _status;
public AsyncQueueLock(AsyncQueue<T> queue)
{
// Keep a reference to the queue so we can know if there are items in it
_queue = queue;
// Releaser for fast path
_fastPathReleaser = Task.FromResult(new Releaser(this));
// Queues for waiting operations
_waitingEnqueue = new Queue<TaskCompletionSource<Releaser>>();
_waitingDequeue = new Queue<TaskCompletionSource<Releaser>>();
// Object to lock on for synchronization
_queueLock = new object();
// Status of lock, 0 = nobody has lock, 1 = enqueue has lock, -1 = dequeue has lock
_status = 0;
}
public Task<Releaser> GetEnqueueLock(CancellationToken token)
{
lock (_queueLock)
{
// If no one has the lock and the queue has space
if (_status == 0 && _queue.IsFull == false)
{
// Let the enqueue in right away
_status = 1;
return _fastPathReleaser;
}
// Make the enqueue operation wait
TaskCompletionSource<Releaser> tcs = CreateTcsInLock(token);
_waitingEnqueue.Enqueue(tcs);
return tcs.Task;
}
}
public Task<Releaser> GetDequeueLock(CancellationToken token)
{
lock (_queueLock)
{
// If no one has the lock and the queue has items in it
if (_status == 0 && _queue.HasItems)
{
// Let the dequeue in right away
_status = -1;
return _fastPathReleaser;
}
// Make the dequeue operation wait
TaskCompletionSource<Releaser> tcs = CreateTcsInLock(token);
_waitingDequeue.Enqueue(tcs);
return tcs.Task;
}
}
/// <summary>
/// Create a new TaskCompletionSource. MUST be executed inside the queue lock.
/// </summary>
private TaskCompletionSource<Releaser> CreateTcsInLock(CancellationToken token)
{
// Run continuations async so that when setting the result/cancelled, that code doesn't hold onto the lock
var tcs = new TaskCompletionSource<Releaser>(TaskContinuationOptions.RunContinuationsAsynchronously);
// If this action runs syncronously (because the token is already cancelled), it should get the lock right away since this
// method is meant to run inside a locked section of code
var cancelRegistration = token.Register(() =>
{
lock (_queueLock)
tcs.TrySetCanceled(token);
}, useSynchronizationContext: false);
// Dispose of the event registration when completed
tcs.Task.ContinueWith(_ => cancelRegistration.Dispose(), CancellationToken.None);
return tcs;
}
private void ReleaseLock()
{
TaskCompletionSource<Releaser> toWake = null;
lock (_queueLock)
{
// Are there items in the queue and dequeue operations waiting?
if (_queue.HasItems && TryGetNextWaitingOpInLock(_waitingDequeue, out toWake))
{
// Prepare to wake up the dequeue operation and set the status accordingly
_status = -1;
}
// Otherwise, is there space in the queue and enqueue operations waiting?
else if (_queue.IsFull == false && TryGetNextWaitingOpInLock(_waitingEnqueue, out toWake))
{
// Prepare to wake up the enqueue operation and set the state accordingly
_status = 1;
}
else
{
// Nobody has the lock
_status = 0;
}
toWake?.SetResult(new Releaser(this));
}
}
/// <summary>
/// Tries to get the next waiting operation from the specified wait queue. MUST be executed while in the lock.
/// </summary>
private bool TryGetNextWaitingOpInLock(Queue<TaskCompletionSource<Releaser>> waitQueue, out TaskCompletionSource<Releaser> waitingOp)
{
waitingOp = null;
// Try to find a waiting op that isn't completed
while (waitQueue.Count > 0)
{
// Just throw out waiting ops that have already been completed (cancelled)
TaskCompletionSource<Releaser> tcs = waitQueue.Dequeue();
if (tcs.Task.IsCompleted)
continue;
waitingOp = tcs;
return true;
}
return false;
}
/// <summary>
/// Disposable struct so lock can be used with using( ... ) pattern to release the lock on Dispose().
/// </summary>
public struct Releaser : IDisposable
{
private readonly AsyncQueueLock _toRelease;
public Releaser(AsyncQueueLock toRelease)
{
_toRelease = toRelease;
}
public void Dispose()
{
_toRelease?.ReleaseLock();
}
}
}
}
}
| |
// 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 gcdv = Google.Cloud.DocumentAI.V1Beta3;
using sys = System;
namespace Google.Cloud.DocumentAI.V1Beta3
{
/// <summary>Resource name for the <c>ProcessorType</c> resource.</summary>
public sealed partial class ProcessorTypeName : gax::IResourceName, sys::IEquatable<ProcessorTypeName>
{
/// <summary>The possible contents of <see cref="ProcessorTypeName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/processorTypes/{processor_type}</c>
/// .
/// </summary>
ProjectLocationProcessorType = 1,
}
private static gax::PathTemplate s_projectLocationProcessorType = new gax::PathTemplate("projects/{project}/locations/{location}/processorTypes/{processor_type}");
/// <summary>Creates a <see cref="ProcessorTypeName"/> 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="ProcessorTypeName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ProcessorTypeName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ProcessorTypeName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ProcessorTypeName"/> with the pattern
/// <c>projects/{project}/locations/{location}/processorTypes/{processor_type}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorTypeId">The <c>ProcessorType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ProcessorTypeName"/> constructed from the provided ids.</returns>
public static ProcessorTypeName FromProjectLocationProcessorType(string projectId, string locationId, string processorTypeId) =>
new ProcessorTypeName(ResourceNameType.ProjectLocationProcessorType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), processorTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(processorTypeId, nameof(processorTypeId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProcessorTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/processorTypes/{processor_type}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorTypeId">The <c>ProcessorType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProcessorTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/processorTypes/{processor_type}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string processorTypeId) =>
FormatProjectLocationProcessorType(projectId, locationId, processorTypeId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProcessorTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/processorTypes/{processor_type}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorTypeId">The <c>ProcessorType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProcessorTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/processorTypes/{processor_type}</c>.
/// </returns>
public static string FormatProjectLocationProcessorType(string projectId, string locationId, string processorTypeId) =>
s_projectLocationProcessorType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(processorTypeId, nameof(processorTypeId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ProcessorTypeName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/processorTypes/{processor_type}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="processorTypeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ProcessorTypeName"/> if successful.</returns>
public static ProcessorTypeName Parse(string processorTypeName) => Parse(processorTypeName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ProcessorTypeName"/> 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>projects/{project}/locations/{location}/processorTypes/{processor_type}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="processorTypeName">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="ProcessorTypeName"/> if successful.</returns>
public static ProcessorTypeName Parse(string processorTypeName, bool allowUnparsed) =>
TryParse(processorTypeName, allowUnparsed, out ProcessorTypeName 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="ProcessorTypeName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/processorTypes/{processor_type}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="processorTypeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ProcessorTypeName"/>, 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 processorTypeName, out ProcessorTypeName result) =>
TryParse(processorTypeName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ProcessorTypeName"/> 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>projects/{project}/locations/{location}/processorTypes/{processor_type}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="processorTypeName">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="ProcessorTypeName"/>, 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 processorTypeName, bool allowUnparsed, out ProcessorTypeName result)
{
gax::GaxPreconditions.CheckNotNull(processorTypeName, nameof(processorTypeName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationProcessorType.TryParseName(processorTypeName, out resourceName))
{
result = FromProjectLocationProcessorType(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(processorTypeName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ProcessorTypeName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string processorTypeId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProcessorTypeId = processorTypeId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ProcessorTypeName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/processorTypes/{processor_type}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="processorTypeId">The <c>ProcessorType</c> ID. Must not be <c>null</c> or empty.</param>
public ProcessorTypeName(string projectId, string locationId, string processorTypeId) : this(ResourceNameType.ProjectLocationProcessorType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), processorTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(processorTypeId, nameof(processorTypeId)))
{
}
/// <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>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>ProcessorType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string ProcessorTypeId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { 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.ProjectLocationProcessorType: return s_projectLocationProcessorType.Expand(ProjectId, LocationId, ProcessorTypeId);
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 ProcessorTypeName);
/// <inheritdoc/>
public bool Equals(ProcessorTypeName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ProcessorTypeName a, ProcessorTypeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ProcessorTypeName a, ProcessorTypeName b) => !(a == b);
}
public partial class ProcessorType
{
/// <summary>
/// <see cref="gcdv::ProcessorTypeName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::ProcessorTypeName ProcessorTypeName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::ProcessorTypeName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using Microsoft.Build.Construction;
/* This file provides a basefunctionallity for IVsCfgProvider2.
Instead of using the IVsProjectCfgEventsHelper object we have our own little sink and call our own helper methods
similiar to the interface. But there is no real benefit in inheriting from the interface in the first place.
Using the helper object seems to be:
a) undocumented
b) not really wise in the managed world
*/
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false)]
[ComVisible(true)]
public class ConfigProvider : IVsCfgProvider2, IVsProjectCfgProvider, IVsExtensibleObject
{
#region fields
internal const string configString = " '$(Configuration)' == '{0}' ";
internal const string AnyCPUPlatform = "Any CPU";
internal const string x86Platform = "x86";
private ProjectNode project;
private EventSinkCollection cfgEventSinks = new EventSinkCollection();
private List<KeyValuePair<KeyValuePair<string, string>, string>> newCfgProps = new List<KeyValuePair<KeyValuePair<string, string>, string>>();
private Dictionary<string, ProjectConfig> configurationsList = new Dictionary<string, ProjectConfig>();
#endregion
#region Properties
/// <summary>
/// The associated project.
/// </summary>
protected ProjectNode ProjectMgr
{
get
{
return this.project;
}
}
/// <summary>
/// If the project system wants to add custom properties to the property group then
/// they provide us with this data.
/// Returns/sets the [(<propName, propCondition>) <propValue>] collection
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual List<KeyValuePair<KeyValuePair<string, string>, string>> NewConfigProperties
{
get
{
return newCfgProps;
}
set
{
newCfgProps = value;
}
}
#endregion
#region ctors
public ConfigProvider(ProjectNode manager)
{
this.project = manager;
}
#endregion
#region methods
/// <summary>
/// Creates new Project Configuartion objects based on the configuration name.
/// </summary>
/// <param name="configName">The name of the configuration</param>
/// <returns>An instance of a ProjectConfig object.</returns>
protected ProjectConfig GetProjectConfiguration(string configName)
{
// if we already created it, return the cached one
if(configurationsList.ContainsKey(configName))
{
return configurationsList[configName];
}
ProjectConfig requestedConfiguration = CreateProjectConfiguration(configName);
configurationsList.Add(configName, requestedConfiguration);
return requestedConfiguration;
}
protected virtual ProjectConfig CreateProjectConfiguration(string configName)
{
return new ProjectConfig(this.project, configName);
}
#endregion
#region IVsProjectCfgProvider methods
/// <summary>
/// Provides access to the IVsProjectCfg interface implemented on a project's configuration object.
/// </summary>
/// <param name="projectCfgCanonicalName">The canonical name of the configuration to access.</param>
/// <param name="projectCfg">The IVsProjectCfg interface of the configuration identified by szProjectCfgCanonicalName.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int OpenProjectCfg(string projectCfgCanonicalName, out IVsProjectCfg projectCfg)
{
if(projectCfgCanonicalName == null)
{
throw new ArgumentNullException("projectCfgCanonicalName");
}
projectCfg = null;
// Be robust in release
if(projectCfgCanonicalName == null)
{
return VSConstants.E_INVALIDARG;
}
Debug.Assert(this.project != null && this.project.BuildProject != null);
string[] configs = GetPropertiesConditionedOn(ProjectFileConstants.Configuration);
foreach(string config in configs)
{
if(String.Compare(config, projectCfgCanonicalName, StringComparison.OrdinalIgnoreCase) == 0)
{
projectCfg = this.GetProjectConfiguration(config);
if(projectCfg != null)
{
return VSConstants.S_OK;
}
else
{
return VSConstants.E_FAIL;
}
}
}
return VSConstants.E_INVALIDARG;
}
/// <summary>
/// Checks whether or not this configuration provider uses independent configurations.
/// </summary>
/// <param name="usesIndependentConfigurations">true if independent configurations are used, false if they are not used. By default returns true.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int get_UsesIndependentConfigurations(out int usesIndependentConfigurations)
{
usesIndependentConfigurations = 1;
return VSConstants.S_OK;
}
#endregion
#region IVsCfgProvider2 methods
/// <summary>
/// Copies an existing configuration name or creates a new one.
/// </summary>
/// <param name="name">The name of the new configuration.</param>
/// <param name="cloneName">the name of the configuration to copy, or a null reference, indicating that AddCfgsOfCfgName should create a new configuration.</param>
/// <param name="fPrivate">Flag indicating whether or not the new configuration is private. If fPrivate is set to true, the configuration is private. If set to false, the configuration is public. This flag can be ignored.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int AddCfgsOfCfgName(string name, string cloneName, int fPrivate)
{
// We need to QE/QS the project file
if(!this.ProjectMgr.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
// First create the condition that represent the configuration we want to clone
string condition = (cloneName == null ? String.Empty : String.Format(CultureInfo.InvariantCulture, configString, cloneName).Trim());
// Get all configs
List<ProjectPropertyGroupElement> configGroup = new List<ProjectPropertyGroupElement>(this.project.BuildProject.Xml.PropertyGroups);
ProjectPropertyGroupElement configToClone = null;
if(cloneName != null)
{
// Find the configuration to clone
foreach (ProjectPropertyGroupElement currentConfig in configGroup)
{
// Only care about conditional property groups
if(currentConfig.Condition == null || currentConfig.Condition.Length == 0)
continue;
// Skip if it isn't the group we want
if(String.Compare(currentConfig.Condition.Trim(), condition, StringComparison.OrdinalIgnoreCase) != 0)
continue;
configToClone = currentConfig;
}
}
ProjectPropertyGroupElement newConfig = null;
if(configToClone != null)
{
// Clone the configuration settings
newConfig = this.project.ClonePropertyGroup(configToClone);
//Will be added later with the new values to the path
foreach (ProjectPropertyElement property in newConfig.Properties)
{
if (property.Name.Equals("OutputPath", StringComparison.OrdinalIgnoreCase))
{
property.Parent.RemoveChild(property);
}
}
}
else
{
// no source to clone from, lets just create a new empty config
newConfig = this.project.BuildProject.Xml.AddPropertyGroup();
// Get the list of property name, condition value from the config provider
IList<KeyValuePair<KeyValuePair<string, string>, string>> propVals = this.NewConfigProperties;
foreach(KeyValuePair<KeyValuePair<string, string>, string> data in propVals)
{
KeyValuePair<string, string> propData = data.Key;
string value = data.Value;
ProjectPropertyElement newProperty = newConfig.AddProperty(propData.Key, value);
if(!String.IsNullOrEmpty(propData.Value))
newProperty.Condition = propData.Value;
}
}
//add the output path
string outputBasePath = this.ProjectMgr.OutputBaseRelativePath;
if(outputBasePath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
outputBasePath = Path.GetDirectoryName(outputBasePath);
newConfig.AddProperty("OutputPath", Path.Combine(outputBasePath, name) + Path.DirectorySeparatorChar.ToString());
// Set the condition that will define the new configuration
string newCondition = String.Format(CultureInfo.InvariantCulture, configString, name);
newConfig.Condition = newCondition;
NotifyOnCfgNameAdded(name);
return VSConstants.S_OK;
}
/// <summary>
/// Copies an existing platform name or creates a new one.
/// </summary>
/// <param name="platformName">The name of the new platform.</param>
/// <param name="clonePlatformName">The name of the platform to copy, or a null reference, indicating that AddCfgsOfPlatformName should create a new platform.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int AddCfgsOfPlatformName(string platformName, string clonePlatformName)
{
return VSConstants.E_NOTIMPL;
}
/// <summary>
/// Deletes a specified configuration name.
/// </summary>
/// <param name="name">The name of the configuration to be deleted.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int DeleteCfgsOfCfgName(string name)
{
// We need to QE/QS the project file
if(!this.ProjectMgr.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
if(name == null)
{
Debug.Fail(String.Format(CultureInfo.CurrentCulture, "Name of the configuration should not be null if you want to delete it from project: {0}", this.project.BuildProject.FullPath));
// The configuration " '$(Configuration)' == " does not exist, so technically the goal
// is achieved so return S_OK
return VSConstants.S_OK;
}
// Verify that this config exist
string[] configs = GetPropertiesConditionedOn(ProjectFileConstants.Configuration);
foreach(string config in configs)
{
if(String.Compare(config, name, StringComparison.OrdinalIgnoreCase) == 0)
{
// Create condition of config to remove
string condition = String.Format(CultureInfo.InvariantCulture, configString, config);
foreach (ProjectPropertyGroupElement element in this.project.BuildProject.Xml.PropertyGroups)
{
if(String.Equals(element.Condition, condition, StringComparison.OrdinalIgnoreCase))
{
element.Parent.RemoveChild(element);
}
}
NotifyOnCfgNameDeleted(name);
}
}
return VSConstants.S_OK;
}
/// <summary>
/// Deletes a specified platform name.
/// </summary>
/// <param name="platName">The platform name to delet.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int DeleteCfgsOfPlatformName(string platName)
{
return VSConstants.E_NOTIMPL;
}
/// <summary>
/// Returns the existing configurations stored in the project file.
/// </summary>
/// <param name="celt">Specifies the requested number of property names. If this number is unknown, celt can be zero.</param>
/// <param name="names">On input, an allocated array to hold the number of configuration property names specified by celt. This parameter can also be a null reference if the celt parameter is zero.
/// On output, names contains configuration property names.</param>
/// <param name="actual">The actual number of property names returned.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int GetCfgNames(uint celt, string[] names, uint[] actual)
{
// get's called twice, once for allocation, then for retrieval
int i = 0;
string[] configList = GetPropertiesConditionedOn(ProjectFileConstants.Configuration);
if(names != null)
{
foreach(string config in configList)
{
names[i++] = config;
if(i == celt)
break;
}
}
else
i = configList.Length;
if(actual != null)
{
actual[0] = (uint)i;
}
return VSConstants.S_OK;
}
/// <summary>
/// Returns the configuration associated with a specified configuration or platform name.
/// </summary>
/// <param name="name">The name of the configuration to be returned.</param>
/// <param name="platName">The name of the platform for the configuration to be returned.</param>
/// <param name="cfg">The implementation of the IVsCfg interface.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int GetCfgOfName(string name, string platName, out IVsCfg cfg)
{
cfg = null;
cfg = this.GetProjectConfiguration(name);
return VSConstants.S_OK;
}
/// <summary>
/// Returns a specified configuration property.
/// </summary>
/// <param name="propid">Specifies the property identifier for the property to return. For valid propid values, see __VSCFGPROPID.</param>
/// <param name="var">The value of the property.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int GetCfgProviderProperty(int propid, out object var)
{
var = false;
switch((__VSCFGPROPID)propid)
{
case __VSCFGPROPID.VSCFGPROPID_SupportsCfgAdd:
var = true;
break;
case __VSCFGPROPID.VSCFGPROPID_SupportsCfgDelete:
var = true;
break;
case __VSCFGPROPID.VSCFGPROPID_SupportsCfgRename:
var = true;
break;
case __VSCFGPROPID.VSCFGPROPID_SupportsPlatformAdd:
var = false;
break;
case __VSCFGPROPID.VSCFGPROPID_SupportsPlatformDelete:
var = false;
break;
}
return VSConstants.S_OK;
}
/// <summary>
/// Returns the per-configuration objects for this object.
/// </summary>
/// <param name="celt">Number of configuration objects to be returned or zero, indicating a request for an unknown number of objects.</param>
/// <param name="a">On input, pointer to an interface array or a null reference. On output, this parameter points to an array of IVsCfg interfaces belonging to the requested configuration objects.</param>
/// <param name="actual">The number of configuration objects actually returned or a null reference, if this information is not necessary.</param>
/// <param name="flags">Flags that specify settings for project configurations, or a null reference (Nothing in Visual Basic) if no additional flag settings are required. For valid prgrFlags values, see __VSCFGFLAGS.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int GetCfgs(uint celt, IVsCfg[] a, uint[] actual, uint[] flags)
{
if(flags != null)
flags[0] = 0;
int i = 0;
string[] configList = GetPropertiesConditionedOn(ProjectFileConstants.Configuration);
if(a != null)
{
foreach(string configName in configList)
{
a[i] = this.GetProjectConfiguration(configName);
i++;
if(i == celt)
break;
}
}
else
i = configList.Length;
if(actual != null)
actual[0] = (uint)i;
return VSConstants.S_OK;
}
/// <summary>
/// Returns one or more platform names.
/// </summary>
/// <param name="celt">Specifies the requested number of platform names. If this number is unknown, celt can be zero.</param>
/// <param name="names">On input, an allocated array to hold the number of platform names specified by celt. This parameter can also be a null reference if the celt parameter is zero. On output, names contains platform names.</param>
/// <param name="actual">The actual number of platform names returned.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int GetPlatformNames(uint celt, string[] names, uint[] actual)
{
string[] platforms = this.GetPlatformsFromProject();
return GetPlatforms(celt, names, actual, platforms);
}
/// <summary>
/// Returns the set of platforms that are installed on the user's machine.
/// </summary>
/// <param name="celt">Specifies the requested number of supported platform names. If this number is unknown, celt can be zero.</param>
/// <param name="names">On input, an allocated array to hold the number of names specified by celt. This parameter can also be a null reference (Nothing in Visual Basic)if the celt parameter is zero. On output, names contains the names of supported platforms</param>
/// <param name="actual">The actual number of platform names returned.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int GetSupportedPlatformNames(uint celt, string[] names, uint[] actual)
{
string[] platforms = this.GetSupportedPlatformsFromProject();
return GetPlatforms(celt, names, actual, platforms);
}
/// <summary>
/// Assigns a new name to a configuration.
/// </summary>
/// <param name="old">The old name of the target configuration.</param>
/// <param name="newname">The new name of the target configuration.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int RenameCfgsOfCfgName(string old, string newname)
{
// First create the condition that represent the configuration we want to rename
string condition = String.Format(CultureInfo.InvariantCulture, configString, old).Trim();
foreach (ProjectPropertyGroupElement config in this.project.BuildProject.Xml.PropertyGroups)
{
// Only care about conditional property groups
if(config.Condition == null || config.Condition.Length == 0)
continue;
// Skip if it isn't the group we want
if(String.Compare(config.Condition.Trim(), condition, StringComparison.OrdinalIgnoreCase) != 0)
continue;
// Change the name
config.Condition = String.Format(CultureInfo.InvariantCulture, configString, newname);
// Update the name in our config list
if(configurationsList.ContainsKey(old))
{
ProjectConfig configuration = configurationsList[old];
configurationsList.Remove(old);
configurationsList.Add(newname, configuration);
// notify the configuration of its new name
configuration.ConfigName = newname;
}
NotifyOnCfgNameRenamed(old, newname);
}
return VSConstants.S_OK;
}
/// <summary>
/// Cancels a registration for configuration event notification.
/// </summary>
/// <param name="cookie">The cookie used for registration.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int UnadviseCfgProviderEvents(uint cookie)
{
this.cfgEventSinks.RemoveAt(cookie);
return VSConstants.S_OK;
}
/// <summary>
/// Registers the caller for configuration event notification.
/// </summary>
/// <param name="sink">Reference to the IVsCfgProviderEvents interface to be called to provide notification of configuration events.</param>
/// <param name="cookie">Reference to a token representing the completed registration</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int AdviseCfgProviderEvents(IVsCfgProviderEvents sink, out uint cookie)
{
cookie = this.cfgEventSinks.Add(sink);
return VSConstants.S_OK;
}
#endregion
#region IVsExtensibleObject Members
/// <summary>
/// Proved access to an IDispatchable object being a list of configuration properties
/// </summary>
/// <param name="configurationName">Combined Name and Platform for the configuration requested</param>
/// <param name="configurationProperties">The IDispatchcable object</param>
/// <returns>S_OK if successful</returns>
public virtual int GetAutomationObject(string configurationName, out object configurationProperties)
{
//Init out param
configurationProperties = null;
string name, platform;
if(!ProjectConfig.TrySplitConfigurationCanonicalName(configurationName, out name, out platform))
{
return VSConstants.E_INVALIDARG;
}
// Get the configuration
IVsCfg cfg;
ErrorHandler.ThrowOnFailure(this.GetCfgOfName(name, platform, out cfg));
// Get the properties of the configuration
configurationProperties = ((ProjectConfig)cfg).ConfigurationProperties;
return VSConstants.S_OK;
}
#endregion
#region helper methods
/// <summary>
/// Called when a new configuration name was added.
/// </summary>
/// <param name="name">The name of configuration just added.</param>
private void NotifyOnCfgNameAdded(string name)
{
foreach(IVsCfgProviderEvents sink in this.cfgEventSinks)
{
ErrorHandler.ThrowOnFailure(sink.OnCfgNameAdded(name));
}
}
/// <summary>
/// Called when a config name was deleted.
/// </summary>
/// <param name="name">The name of the configuration.</param>
private void NotifyOnCfgNameDeleted(string name)
{
foreach(IVsCfgProviderEvents sink in this.cfgEventSinks)
{
ErrorHandler.ThrowOnFailure(sink.OnCfgNameDeleted(name));
}
}
/// <summary>
/// Called when a config name was renamed
/// </summary>
/// <param name="oldName">Old configuration name</param>
/// <param name="newName">New configuration name</param>
private void NotifyOnCfgNameRenamed(string oldName, string newName)
{
foreach(IVsCfgProviderEvents sink in this.cfgEventSinks)
{
ErrorHandler.ThrowOnFailure(sink.OnCfgNameRenamed(oldName, newName));
}
}
/// <summary>
/// Called when a platform name was added
/// </summary>
/// <param name="platformName">The name of the platform.</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private void NotifyOnPlatformNameAdded(string platformName)
{
foreach(IVsCfgProviderEvents sink in this.cfgEventSinks)
{
ErrorHandler.ThrowOnFailure(sink.OnPlatformNameAdded(platformName));
}
}
/// <summary>
/// Called when a platform name was deleted
/// </summary>
/// <param name="platformName">The name of the platform.</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private void NotifyOnPlatformNameDeleted(string platformName)
{
foreach(IVsCfgProviderEvents sink in this.cfgEventSinks)
{
ErrorHandler.ThrowOnFailure(sink.OnPlatformNameDeleted(platformName));
}
}
/// <summary>
/// Gets all the platforms defined in the project
/// </summary>
/// <returns>An array of platform names.</returns>
private string[] GetPlatformsFromProject()
{
string[] platforms = GetPropertiesConditionedOn(ProjectFileConstants.Platform);
if(platforms == null || platforms.Length == 0)
{
return new string[] { x86Platform, AnyCPUPlatform };
}
for(int i = 0; i < platforms.Length; i++)
{
platforms[i] = ConvertPlatformToVsProject(platforms[i]);
}
return platforms;
}
/// <summary>
/// Return the supported platform names.
/// </summary>
/// <returns>An array of supported platform names.</returns>
private string[] GetSupportedPlatformsFromProject()
{
string platforms = this.ProjectMgr.BuildProject.GetPropertyValue(ProjectFileConstants.AvailablePlatforms);
if(platforms == null)
{
return new string[] { };
}
if(platforms.Contains(","))
{
return platforms.Split(',');
}
return new string[] { platforms };
}
/// <summary>
/// Helper function to convert AnyCPU to Any CPU.
/// </summary>
/// <param name="oldName">The oldname.</param>
/// <returns>The new name.</returns>
private static string ConvertPlatformToVsProject(string oldPlatformName)
{
if(String.Compare(oldPlatformName, ProjectFileValues.AnyCPU, StringComparison.OrdinalIgnoreCase) == 0)
{
return AnyCPUPlatform;
}
return oldPlatformName;
}
/// <summary>
/// Common method for handling platform names.
/// </summary>
/// <param name="celt">Specifies the requested number of platform names. If this number is unknown, celt can be zero.</param>
/// <param name="names">On input, an allocated array to hold the number of platform names specified by celt. This parameter can also be null if the celt parameter is zero. On output, names contains platform names</param>
/// <param name="actual">A count of the actual number of platform names returned.</param>
/// <param name="platforms">An array of available platform names</param>
/// <returns>A count of the actual number of platform names returned.</returns>
/// <devremark>The platforms array is never null. It is assured by the callers.</devremark>
private static int GetPlatforms(uint celt, string[] names, uint[] actual, string[] platforms)
{
Debug.Assert(platforms != null, "The plaforms array should never be null");
if(names == null)
{
if(actual == null || actual.Length == 0)
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "actual");
}
actual[0] = (uint)platforms.Length;
return VSConstants.S_OK;
}
//Degenarate case
if(celt == 0)
{
if(actual != null && actual.Length != 0)
{
actual[0] = (uint)platforms.Length;
}
return VSConstants.S_OK;
}
uint returned = 0;
for(int i = 0; i < platforms.Length && names.Length > returned; i++)
{
names[returned] = platforms[i];
returned++;
}
if(actual != null && actual.Length != 0)
{
actual[0] = returned;
}
if(celt > returned)
{
return VSConstants.S_FALSE;
}
return VSConstants.S_OK;
}
#endregion
/// <summary>
/// Get all the configurations in the project.
/// </summary>
private string[] GetPropertiesConditionedOn(string constant)
{
List<string> configurations = null;
this.project.BuildProject.ReevaluateIfNecessary();
this.project.BuildProject.ConditionedProperties.TryGetValue(constant, out configurations);
return (configurations == null) ? new string[] { } : configurations.ToArray();
}
}
}
| |
// 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 ExtractVector128Byte1()
{
var test = new ImmUnaryOpTest__ExtractVector128Byte1();
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 ImmUnaryOpTest__ExtractVector128Byte1
{
private struct TestStruct
{
public Vector256<Byte> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ExtractVector128Byte1 testClass)
{
var result = Avx.ExtractVector128(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data = new Byte[Op1ElementCount];
private static Vector256<Byte> _clsVar;
private Vector256<Byte> _fld;
private SimpleUnaryOpTest__DataTable<Byte, Byte> _dataTable;
static ImmUnaryOpTest__ExtractVector128Byte1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
}
public ImmUnaryOpTest__ExtractVector128Byte1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Byte, Byte>(_data, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.ExtractVector128(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.ExtractVector128(
Avx.LoadVector256((Byte*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.ExtractVector128(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.ExtractVector128(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Byte>>(_dataTable.inArrayPtr);
var result = Avx.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Byte*)(_dataTable.inArrayPtr));
var result = Avx.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArrayPtr));
var result = Avx.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ExtractVector128Byte1();
var result = Avx.ExtractVector128(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.ExtractVector128(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.ExtractVector128(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _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<Byte> firstOp, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray = new Byte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray = new Byte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Byte[] firstOp, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != firstOp[16])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != firstOp[i+16])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.ExtractVector128)}<Byte>(Vector256<Byte><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using bv.common;
using bv.common.db;
using bv.common.db.Core;
using bv.common.Diagnostics;
using EIDSS.Tests.Core;
using NUnit.Framework;
using System.Threading;
using GlobalSettings = bv.common.GlobalSettings;
namespace EIDSS.Tests.Database
{
[TestFixture]
public class LookupCacheTest
{
[SetUp]
public void Init()
{
GlobalSettings.Init("test", "test", "test");
ScriptLoader.RunScript(PathToTestFolder.Get("Database") + "Data\\DropTestTables.sql");
ScriptLoader.RunScript(PathToTestFolder.Get("Database") + "Data\\CreateTestTables.sql");
}
[TearDown]
public void Deinit()
{
LookupCacheListener.Stop();
ScriptLoader.RunScript(PathToTestFolder.Get("Database") + "Data\\DropTestTables.sql");
}
private const int TimeOut = 100;
[Test]
public void RandomLookupCacheTest()
{
Random rnd = new Random();
DummyLookupCacheHelper.Init();
//LookupCache.UseSingleConnection = true;
DateTime time = DateTime.Now;
while (DateTime.Now.Subtract(time).TotalSeconds < TimeOut)
{
Thread.Sleep(rnd.Next(100, 5000));
int randomTableNum = Convert.ToInt32(rnd.Next(0, (int)DummyLookupTables.HumanDiagnoses));
Dbg.Debug("--------------------");
Dbg.Debug("Get lookup table {0}", ((DummyLookupTables)randomTableNum).ToString());
DataView dv = LookupCache.Get((DummyLookupTables)randomTableNum);
Assert.IsNotNull(dv, "lookup cache didn\'t return table {0}", ((DummyLookupTables)randomTableNum).ToString());
Dbg.Debug("{0} records is returned ", dv.Count);
//Assert.AreNotEqual(0, dv.Count, "lookup cache {0} has no data", CType(randomTableNum, LookupTables).ToString)
Dbg.Debug("--------------------");
LookupCache.Reload();
}
}
[Test]
public void TestLookupCache()
{
Dbg.Debug("************************************************************");
DebugTimer.Start("start lookup cache filling with multiple connections. Attempt 1");
DummyLookupCacheHelper.Init();
//LookupCache.UseSingleConnection = false;
while (!LookupCache.Filled)
{
Thread.Sleep(1000);
Dbg.Debug("waiting for async lookup table filling");
}
DebugTimer.Stop();
Dbg.Debug("************************************************************");
Dbg.Debug("************************************************************");
DebugTimer.Start("start lookup cache filling with multiple connections. Attempt 2");
LookupCache.Init(true, true);
//LookupCache.UseSingleConnection = false;
while (!LookupCache.Filled)
{
Thread.Sleep(1000);
Dbg.Debug("waiting for async lookup table filling");
}
DebugTimer.Stop();
Dbg.Debug("************************************************************");
Dbg.Debug("************************************************************");
DebugTimer.Start("start lookup cache filling with single connection. Attempt 1");
LookupCache.Init(true, true);
//LookupCache.UseSingleConnection = true;
while (!LookupCache.Filled)
{
Thread.Sleep(1000);
Dbg.Debug("waiting for async lookup table filling");
}
DebugTimer.Stop();
Dbg.Debug("************************************************************");
Dbg.Debug("************************************************************");
DebugTimer.Start("start lookup cache filling with single connection. Attempt 2");
LookupCache.Init(true, true);
//LookupCache.UseSingleConnection = true;
while (!LookupCache.Filled)
{
Thread.Sleep(1000);
Dbg.Debug("waiting for async lookup table filling");
}
DebugTimer.Stop();
Dbg.Debug("************************************************************");
Dbg.Debug("***********RowFilter performance**************");
DataView settlementView = LookupCache.Get(DummyLookupTables.Settlement);
Dbg.Debug("Settlement table contains {0} records", settlementView.Count);
string rowFilter = string.Format("idfsSettlement=\'{0}\'", settlementView.Table.Rows[0]["idfsSettlement"]);
DebugTimer.Start("Filtering setllements: " + rowFilter);
settlementView.RowFilter = rowFilter;
Dbg.Debug("{0} rows are selected", settlementView.Count);
DebugTimer.Stop();
rowFilter = string.Format("idfsSettlement=\'{0}\'", settlementView.Table.Rows[settlementView.Table.Rows.Count - 1]["idfsSettlement"]);
DebugTimer.Start("Filtering setllements: " + rowFilter);
settlementView.RowFilter = rowFilter;
Dbg.Debug("{0} rows are selected", settlementView.Count);
DebugTimer.Stop();
rowFilter = string.Format("idfsRayon=\'{0}\'", settlementView.Table.Rows[settlementView.Table.Rows.Count - 1]["idfsRayon"]);
DebugTimer.Start("Filtering setllements: " + rowFilter);
settlementView.RowFilter = rowFilter;
Dbg.Debug("{0} rows are selected", settlementView.Count);
DebugTimer.Stop();
rowFilter = string.Format("idfsRayon=\'{0}\'", settlementView.Table.Rows[0]["idfsRayon"]);
DebugTimer.Start("Filtering setllements: " + rowFilter);
settlementView.RowFilter = rowFilter;
Dbg.Debug("{0} rows are selected", settlementView.Count);
DebugTimer.Stop();
}
[Test]
public void ChangeNotification()
{
BaseDbService.NewIntID(null);
DummyLookupCacheHelper.Init();
while (!LookupCache.Filled)
{
Thread.Sleep(1000);
Dbg.Debug("waiting for async lookup table filling");
}
DataView dv = LookupCache.Get(DummyLookupTables.Organization);
if (dv.Count > 0)
{
object oldName = dv[0]["Name"];
IDbCommand cmd = BaseDbService.CreateSPCommand("spOrganization_Post", ConnectionManager.DefaultInstance.Connection, null);
StoredProcParamsCache.CreateParameters(cmd, null);
BaseDbService.SetParam(cmd, "@idfOffice", dv[0]["idfInstitution"], ParameterDirection.Input);
BaseDbService.SetParam(cmd, "@EnglishName", "Test111111", ParameterDirection.Input);
BaseDbService.SetParam(cmd, "@Name", "Test111111", ParameterDirection.Input);
BaseDbService.SetParam(cmd, "@EnglishAbbreviation", dv[0]["Abbreviation"], ParameterDirection.Input);
BaseDbService.SetParam(cmd, "@Abbreviation", dv[0]["Abbreviation"], ParameterDirection.Input);
//BaseDbService.SetParam(cmd, "@LANGID", GlobalSettings.CurrentLanguage, ParameterDirection.Input);
lock (cmd.Connection)
{
if (cmd.Connection.State == ConnectionState.Closed)
cmd.Connection.Open();
IDbTransaction transaction = cmd.Connection.BeginTransaction();
BaseDbService.ExecCommand(cmd, cmd.Connection, transaction, false);
LookupCache.NotifyChange("tlbOffice", transaction, null);
transaction.Commit();
}
Thread.Sleep(2000);
Assert.AreEqual("Test111111", dv[0]["Name"].ToString(), "organization lookup was not refreshed");
lock (cmd.Connection)
{
if (cmd.Connection.State == ConnectionState.Closed)
cmd.Connection.Open();
IDbTransaction transaction = cmd.Connection.BeginTransaction();
BaseDbService.SetParam(cmd, "@Name", oldName, ParameterDirection.Input);
BaseDbService.SetParam(cmd, "@EnglishName", oldName, ParameterDirection.Input);
BaseDbService.ExecCommand(cmd, cmd.Connection, transaction, false);
LookupCache.NotifyChange("tlbOffice", transaction, null);
transaction.Commit();
}
Thread.Sleep(2000);
Assert.AreEqual(oldName, dv[0]["Name"].ToString(), "organization lookup was refreshed unexpectelly");
}
}
[Test]
public void WebAccessMode()
{
LookupCache.WebClientMode = true;
DummyLookupCacheHelper.Init();
//LookupCache.UseSingleConnection = true;
DataView rayonView = LookupCache.Get(DummyLookupTables.Rayon);
Dictionary<string,object> args = new Dictionary<string, object>();
Dbg.Debug("************************************************************");
DebugTimer.Start("get full settlements list");
DataView settlementView = LookupCache.Get(DummyLookupTables.Settlement);
DebugTimer.Stop();
int total = settlementView.Count;
Dbg.Debug("got {0} settlements", total);
Assert.Greater(total, 0);
settlementView.RowFilter = string.Format("idfsRayon={0}", rayonView[0]["idfsRayon"]);
int rayon0Total = settlementView.Count;
settlementView.RowFilter = string.Format("idfsRayon={0}", rayonView[1]["idfsRayon"]);
int rayon1Total = settlementView.Count;
settlementView.RowFilter = string.Format("idfsRayon={0}", rayonView[2]["idfsRayon"]);
int rayon2Total = settlementView.Count;
args["@RayonID"] = rayonView[0]["idfsRayon"];
Dbg.Debug("************************************************************");
DebugTimer.Start("get settlements for rayon 1");
settlementView = LookupCache.Get(DummyLookupTables.Settlement, 0, args);
DebugTimer.Stop();
int rayonTotal = settlementView.Count;
Dbg.Debug("got {0} settlements", rayonTotal);
Assert.Greater(total, rayonTotal);
Assert.AreEqual(rayon0Total, rayonTotal);
args["@RayonID"] = rayonView[1]["idfsRayon"];
Dbg.Debug("************************************************************");
DebugTimer.Start("get settlements for rayon 2");
settlementView = LookupCache.Get(DummyLookupTables.Settlement, 0, args);
rayonTotal = settlementView.Count;
Dbg.Debug("got {0} settlements", rayonTotal);
Assert.Greater(total, rayonTotal);
Assert.AreEqual(rayon1Total, rayonTotal);
args["@RayonID"] = rayonView[2]["idfsRayon"];
Dbg.Debug("************************************************************");
DebugTimer.Start("get settlements for rayon 3");
settlementView = LookupCache.Get(DummyLookupTables.Settlement, 0, args);
DebugTimer.Stop();
rayonTotal = settlementView.Count;
Dbg.Debug("got {0} settlements", rayonTotal);
Assert.Greater(total, rayonTotal);
Assert.AreEqual(rayon2Total, rayonTotal);
Dbg.Debug("************************************************************");
DebugTimer.Start("get settlements for rayon 3");
settlementView = LookupCache.Get(DummyLookupTables.Settlement, 0, null);
DebugTimer.Stop();
rayonTotal = settlementView.Count;
Dbg.Debug("got {0} settlements", rayonTotal);
Assert.Greater(total, rayonTotal);
Assert.AreEqual(rayon2Total, rayonTotal);
args.Clear();
Dbg.Debug("************************************************************");
DebugTimer.Start("get all settlements");
settlementView = LookupCache.Get(DummyLookupTables.Settlement, 0, args);
DebugTimer.Stop();
rayonTotal = settlementView.Count;
Dbg.Debug("got {0} settlements", rayonTotal);
Assert.AreEqual(total, rayonTotal);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
internal sealed class WebSocketHttpListenerDuplexStream : Stream, WebSocketBase.IWebSocketStream
{
private static readonly EventHandler<HttpListenerAsyncEventArgs> s_OnReadCompleted =
new EventHandler<HttpListenerAsyncEventArgs>(OnReadCompleted);
private static readonly EventHandler<HttpListenerAsyncEventArgs> s_OnWriteCompleted =
new EventHandler<HttpListenerAsyncEventArgs>(OnWriteCompleted);
private static readonly Func<Exception, bool> s_CanHandleException = new Func<Exception, bool>(CanHandleException);
private static readonly Action<object> s_OnCancel = new Action<object>(OnCancel);
private readonly HttpRequestStream _inputStream;
private readonly HttpResponseStream _outputStream;
private HttpListenerContext _context;
private bool _inOpaqueMode;
private WebSocketBase _webSocket;
private HttpListenerAsyncEventArgs _writeEventArgs;
private HttpListenerAsyncEventArgs _readEventArgs;
private TaskCompletionSource<object> _writeTaskCompletionSource;
private TaskCompletionSource<int> _readTaskCompletionSource;
private int _cleanedUp;
#if DEBUG
private class OutstandingOperations
{
internal int _reads;
internal int _writes;
}
private readonly OutstandingOperations _outstandingOperations = new OutstandingOperations();
#endif //DEBUG
public WebSocketHttpListenerDuplexStream(HttpRequestStream inputStream,
HttpResponseStream outputStream,
HttpListenerContext context)
{
Debug.Assert(inputStream != null, "'inputStream' MUST NOT be NULL.");
Debug.Assert(outputStream != null, "'outputStream' MUST NOT be NULL.");
Debug.Assert(context != null, "'context' MUST NOT be NULL.");
Debug.Assert(inputStream.CanRead, "'inputStream' MUST support read operations.");
Debug.Assert(outputStream.CanWrite, "'outputStream' MUST support write operations.");
_inputStream = inputStream;
_outputStream = outputStream;
_context = context;
if (NetEventSource.IsEnabled)
{
NetEventSource.Associate(inputStream, this);
NetEventSource.Associate(outputStream, this);
}
}
public override bool CanRead
{
get
{
return _inputStream.CanRead;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanTimeout
{
get
{
return _inputStream.CanTimeout && _outputStream.CanTimeout;
}
}
public override bool CanWrite
{
get
{
return _outputStream.CanWrite;
}
}
public override long Length
{
get
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override long Position
{
get
{
throw new NotSupportedException(SR.net_noseek);
}
set
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return _inputStream.Read(buffer, offset, count);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
WebSocketValidate.ValidateBuffer(buffer, offset, count);
return ReadAsyncCore(buffer, offset, count, cancellationToken);
}
private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this, HttpWebSocket.GetTraceMsgForParameters(offset, count, cancellationToken));
}
CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
int bytesRead = 0;
try
{
if (cancellationToken.CanBeCanceled)
{
cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
}
if (!_inOpaqueMode)
{
bytesRead = await _inputStream.ReadAsync(buffer, offset, count, cancellationToken).SuppressContextFlow<int>();
}
else
{
#if DEBUG
// When using fast path only one outstanding read is permitted. By switching into opaque mode
// via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
// caller takes responsibility for enforcing this constraint.
Debug.Assert(Interlocked.Increment(ref _outstandingOperations._reads) == 1,
"Only one outstanding read allowed at any given time.");
#endif
_readTaskCompletionSource = new TaskCompletionSource<int>();
_readEventArgs.SetBuffer(buffer, offset, count);
if (!ReadAsyncFast(_readEventArgs))
{
if (_readEventArgs.Exception != null)
{
throw _readEventArgs.Exception;
}
bytesRead = _readEventArgs.BytesTransferred;
}
else
{
bytesRead = await _readTaskCompletionSource.Task.SuppressContextFlow<int>();
}
}
}
catch (Exception error)
{
if (s_CanHandleException(error))
{
cancellationToken.ThrowIfCancellationRequested();
}
throw;
}
finally
{
cancellationTokenRegistration.Dispose();
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this, bytesRead);
}
}
return bytesRead;
}
// return value indicates sync vs async completion
// false: sync completion
// true: async completion
private unsafe bool ReadAsyncFast(HttpListenerAsyncEventArgs eventArgs)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
}
eventArgs.StartOperationCommon(this, _inputStream.InternalHttpContext.RequestQueueBoundHandle);
eventArgs.StartOperationReceive();
uint statusCode = 0;
bool completedAsynchronously = false;
try
{
Debug.Assert(eventArgs.Buffer != null, "'BufferList' is not supported for read operations.");
if (eventArgs.Count == 0 || _inputStream.Closed)
{
eventArgs.FinishOperationSuccess(0, true);
return false;
}
uint dataRead = 0;
int offset = eventArgs.Offset;
int remainingCount = eventArgs.Count;
if (_inputStream.BufferedDataChunksAvailable)
{
dataRead = _inputStream.GetChunks(eventArgs.Buffer, eventArgs.Offset, eventArgs.Count);
if (_inputStream.BufferedDataChunksAvailable && dataRead == eventArgs.Count)
{
eventArgs.FinishOperationSuccess(eventArgs.Count, true);
return false;
}
}
Debug.Assert(!_inputStream.BufferedDataChunksAvailable, "'m_InputStream.BufferedDataChunksAvailable' MUST BE 'FALSE' at this point.");
Debug.Assert(dataRead <= eventArgs.Count, "'dataRead' MUST NOT be bigger than 'eventArgs.Count'.");
if (dataRead != 0)
{
offset += (int)dataRead;
remainingCount -= (int)dataRead;
//the http.sys team recommends that we limit the size to 128kb
if (remainingCount > HttpRequestStream.MaxReadSize)
{
remainingCount = HttpRequestStream.MaxReadSize;
}
eventArgs.SetBuffer(eventArgs.Buffer, offset, remainingCount);
}
else if (remainingCount > HttpRequestStream.MaxReadSize)
{
remainingCount = HttpRequestStream.MaxReadSize;
eventArgs.SetBuffer(eventArgs.Buffer, offset, remainingCount);
}
uint flags = 0;
uint bytesReturned = 0;
statusCode =
Interop.HttpApi.HttpReceiveRequestEntityBody(
_inputStream.InternalHttpContext.RequestQueueHandle,
_inputStream.InternalHttpContext.RequestId,
flags,
(byte*)_webSocket.InternalBuffer.ToIntPtr(eventArgs.Offset),
(uint)eventArgs.Count,
out bytesReturned,
eventArgs.NativeOverlapped);
if (statusCode != Interop.HttpApi.ERROR_SUCCESS &&
statusCode != Interop.HttpApi.ERROR_IO_PENDING &&
statusCode != Interop.HttpApi.ERROR_HANDLE_EOF)
{
throw new HttpListenerException((int)statusCode);
}
else if (statusCode == Interop.HttpApi.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
// IO operation completed synchronously. No IO completion port callback is used because
// it was disabled in SwitchToOpaqueMode()
eventArgs.FinishOperationSuccess((int)bytesReturned, true);
completedAsynchronously = false;
}
else
{
completedAsynchronously = true;
}
}
catch (Exception e)
{
_readEventArgs.FinishOperationFailure(e, true);
_outputStream.SetClosedFlag();
_outputStream.InternalHttpContext.Abort();
throw;
}
finally
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this, completedAsynchronously);
}
}
return completedAsynchronously;
}
public override int ReadByte()
{
return _inputStream.ReadByte();
}
public bool SupportsMultipleWrite
{
get
{
return true;
}
}
public override IAsyncResult BeginRead(byte[] buffer,
int offset,
int count,
AsyncCallback callback,
object state)
{
return _inputStream.BeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
return _inputStream.EndRead(asyncResult);
}
public Task MultipleWriteAsync(IList<ArraySegment<byte>> sendBuffers, CancellationToken cancellationToken)
{
Debug.Assert(_inOpaqueMode, "The stream MUST be in opaque mode at this point.");
Debug.Assert(sendBuffers != null, "'sendBuffers' MUST NOT be NULL.");
Debug.Assert(sendBuffers.Count == 1 || sendBuffers.Count == 2,
"'sendBuffers.Count' MUST be either '1' or '2'.");
if (sendBuffers.Count == 1)
{
ArraySegment<byte> buffer = sendBuffers[0];
return WriteAsync(buffer.Array, buffer.Offset, buffer.Count, cancellationToken);
}
return MultipleWriteAsyncCore(sendBuffers, cancellationToken);
}
private async Task MultipleWriteAsyncCore(IList<ArraySegment<byte>> sendBuffers, CancellationToken cancellationToken)
{
Debug.Assert(sendBuffers != null, "'sendBuffers' MUST NOT be NULL.");
Debug.Assert(sendBuffers.Count == 2, "'sendBuffers.Count' MUST be '2' at this point.");
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
}
CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
try
{
if (cancellationToken.CanBeCanceled)
{
cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
}
#if DEBUG
// When using fast path only one outstanding read is permitted. By switching into opaque mode
// via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
// caller takes responsibility for enforcing this constraint.
Debug.Assert(Interlocked.Increment(ref _outstandingOperations._writes) == 1,
"Only one outstanding write allowed at any given time.");
#endif
_writeTaskCompletionSource = new TaskCompletionSource<object>();
_writeEventArgs.SetBuffer(null, 0, 0);
_writeEventArgs.BufferList = sendBuffers;
if (WriteAsyncFast(_writeEventArgs))
{
await _writeTaskCompletionSource.Task.SuppressContextFlow();
}
}
catch (Exception error)
{
if (s_CanHandleException(error))
{
cancellationToken.ThrowIfCancellationRequested();
}
throw;
}
finally
{
cancellationTokenRegistration.Dispose();
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this);
}
}
}
public override void Write(byte[] buffer, int offset, int count)
{
_outputStream.Write(buffer, offset, count);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
WebSocketValidate.ValidateBuffer(buffer, offset, count);
return WriteAsyncCore(buffer, offset, count, cancellationToken);
}
private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this, HttpWebSocket.GetTraceMsgForParameters(offset, count, cancellationToken));
}
CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
try
{
if (cancellationToken.CanBeCanceled)
{
cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
}
if (!_inOpaqueMode)
{
await _outputStream.WriteAsync(buffer, offset, count, cancellationToken).SuppressContextFlow();
}
else
{
#if DEBUG
// When using fast path only one outstanding read is permitted. By switching into opaque mode
// via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
// caller takes responsibility for enforcing this constraint.
Debug.Assert(Interlocked.Increment(ref _outstandingOperations._writes) == 1,
"Only one outstanding write allowed at any given time.");
#endif
_writeTaskCompletionSource = new TaskCompletionSource<object>();
_writeEventArgs.BufferList = null;
_writeEventArgs.SetBuffer(buffer, offset, count);
if (WriteAsyncFast(_writeEventArgs))
{
await _writeTaskCompletionSource.Task.SuppressContextFlow();
}
}
}
catch (Exception error)
{
if (s_CanHandleException(error))
{
cancellationToken.ThrowIfCancellationRequested();
}
throw;
}
finally
{
cancellationTokenRegistration.Dispose();
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this);
}
}
}
// return value indicates sync vs async completion
// false: sync completion
// true: async completion
private unsafe bool WriteAsyncFast(HttpListenerAsyncEventArgs eventArgs)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
}
Interop.HttpApi.HTTP_FLAGS flags = Interop.HttpApi.HTTP_FLAGS.NONE;
eventArgs.StartOperationCommon(this, _outputStream.InternalHttpContext.RequestQueueBoundHandle);
eventArgs.StartOperationSend();
uint statusCode;
bool completedAsynchronously = false;
try
{
if (_outputStream.Closed ||
(eventArgs.Buffer != null && eventArgs.Count == 0))
{
eventArgs.FinishOperationSuccess(eventArgs.Count, true);
return false;
}
if (eventArgs.ShouldCloseOutput)
{
flags |= Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT;
}
else
{
flags |= Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA;
// When using HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA HTTP.SYS will copy the payload to
// kernel memory (Non-Paged Pool). Http.Sys will buffer up to
// Math.Min(16 MB, current TCP window size)
flags |= Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA;
}
uint bytesSent;
statusCode =
Interop.HttpApi.HttpSendResponseEntityBody(
_outputStream.InternalHttpContext.RequestQueueHandle,
_outputStream.InternalHttpContext.RequestId,
(uint)flags,
eventArgs.EntityChunkCount,
(Interop.HttpApi.HTTP_DATA_CHUNK*)eventArgs.EntityChunks,
&bytesSent,
SafeLocalAllocHandle.Zero,
0,
eventArgs.NativeOverlapped,
null);
if (statusCode != Interop.HttpApi.ERROR_SUCCESS &&
statusCode != Interop.HttpApi.ERROR_IO_PENDING)
{
throw new HttpListenerException((int)statusCode);
}
else if (statusCode == Interop.HttpApi.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
// IO operation completed synchronously - callback won't be called to signal completion.
eventArgs.FinishOperationSuccess((int)bytesSent, true);
completedAsynchronously = false;
}
else
{
completedAsynchronously = true;
}
}
catch (Exception e)
{
_writeEventArgs.FinishOperationFailure(e, true);
_outputStream.SetClosedFlag();
_outputStream.InternalHttpContext.Abort();
throw;
}
finally
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this, completedAsynchronously);
}
}
return completedAsynchronously;
}
public override void WriteByte(byte value)
{
_outputStream.WriteByte(value);
}
public override IAsyncResult BeginWrite(byte[] buffer,
int offset,
int count,
AsyncCallback callback,
object state)
{
return _outputStream.BeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
_outputStream.EndWrite(asyncResult);
}
public override void Flush()
{
_outputStream.Flush();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return _outputStream.FlushAsync(cancellationToken);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.net_noseek);
}
public override void SetLength(long value)
{
throw new NotSupportedException(SR.net_noseek);
}
public async Task CloseNetworkConnectionAsync(CancellationToken cancellationToken)
{
// need to yield here to make sure that we don't get any exception synchronously
await Task.Yield();
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
}
CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration();
try
{
if (cancellationToken.CanBeCanceled)
{
cancellationTokenRegistration = cancellationToken.Register(s_OnCancel, this, false);
}
#if DEBUG
// When using fast path only one outstanding read is permitted. By switching into opaque mode
// via IWebSocketStream.SwitchToOpaqueMode (see more detailed comments in interface definition)
// caller takes responsibility for enforcing this constraint.
Debug.Assert(Interlocked.Increment(ref _outstandingOperations._writes) == 1,
"Only one outstanding write allowed at any given time.");
#endif
_writeTaskCompletionSource = new TaskCompletionSource<object>();
_writeEventArgs.SetShouldCloseOutput();
if (WriteAsyncFast(_writeEventArgs))
{
await _writeTaskCompletionSource.Task.SuppressContextFlow();
}
}
catch (Exception error)
{
if (!s_CanHandleException(error))
{
throw;
}
// throw OperationCancelledException when canceled by the caller
// otherwise swallow the exception
cancellationToken.ThrowIfCancellationRequested();
}
finally
{
cancellationTokenRegistration.Dispose();
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this);
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing && Interlocked.Exchange(ref _cleanedUp, 1) == 0)
{
if (_readTaskCompletionSource != null)
{
_readTaskCompletionSource.TrySetCanceled();
}
if (_writeTaskCompletionSource != null)
{
_writeTaskCompletionSource.TrySetCanceled();
}
if (_readEventArgs != null)
{
_readEventArgs.Dispose();
}
if (_writeEventArgs != null)
{
_writeEventArgs.Dispose();
}
try
{
_inputStream.Close();
}
finally
{
_outputStream.Close();
}
}
}
public void Abort()
{
OnCancel(this);
}
private static bool CanHandleException(Exception error)
{
return error is HttpListenerException ||
error is ObjectDisposedException ||
error is IOException;
}
private static void OnCancel(object state)
{
Debug.Assert(state != null, "'state' MUST NOT be NULL.");
WebSocketHttpListenerDuplexStream thisPtr = state as WebSocketHttpListenerDuplexStream;
Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL.");
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(state);
}
try
{
thisPtr._outputStream.SetClosedFlag();
thisPtr._context.Abort();
}
catch { }
TaskCompletionSource<int> readTaskCompletionSourceSnapshot = thisPtr._readTaskCompletionSource;
if (readTaskCompletionSourceSnapshot != null)
{
readTaskCompletionSourceSnapshot.TrySetCanceled();
}
TaskCompletionSource<object> writeTaskCompletionSourceSnapshot = thisPtr._writeTaskCompletionSource;
if (writeTaskCompletionSourceSnapshot != null)
{
writeTaskCompletionSourceSnapshot.TrySetCanceled();
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(state);
}
}
public void SwitchToOpaqueMode(WebSocketBase webSocket)
{
Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL.");
Debug.Assert(_outputStream != null, "'m_OutputStream' MUST NOT be NULL.");
Debug.Assert(_outputStream.InternalHttpContext != null,
"'m_OutputStream.InternalHttpContext' MUST NOT be NULL.");
Debug.Assert(_outputStream.InternalHttpContext.Response != null,
"'m_OutputStream.InternalHttpContext.Response' MUST NOT be NULL.");
Debug.Assert(_outputStream.InternalHttpContext.Response.SentHeaders,
"Headers MUST have been sent at this point.");
Debug.Assert(!_inOpaqueMode, "SwitchToOpaqueMode MUST NOT be called multiple times.");
if (_inOpaqueMode)
{
throw new InvalidOperationException();
}
_webSocket = webSocket;
_inOpaqueMode = true;
_readEventArgs = new HttpListenerAsyncEventArgs(webSocket, this);
_readEventArgs.Completed += s_OnReadCompleted;
_writeEventArgs = new HttpListenerAsyncEventArgs(webSocket, this);
_writeEventArgs.Completed += s_OnWriteCompleted;
if (NetEventSource.IsEnabled)
{
NetEventSource.Associate(this, webSocket);
}
}
private static void OnWriteCompleted(object sender, HttpListenerAsyncEventArgs eventArgs)
{
Debug.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL.");
WebSocketHttpListenerDuplexStream thisPtr = eventArgs.CurrentStream;
Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL.");
#if DEBUG
Debug.Assert(Interlocked.Decrement(ref thisPtr._outstandingOperations._writes) >= 0,
"'thisPtr.m_OutstandingOperations.m_Writes' MUST NOT be negative.");
#endif
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(thisPtr);
}
if (eventArgs.Exception != null)
{
thisPtr._writeTaskCompletionSource.TrySetException(eventArgs.Exception);
}
else
{
thisPtr._writeTaskCompletionSource.TrySetResult(null);
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(thisPtr);
}
}
private static void OnReadCompleted(object sender, HttpListenerAsyncEventArgs eventArgs)
{
Debug.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL.");
WebSocketHttpListenerDuplexStream thisPtr = eventArgs.CurrentStream;
Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL.");
#if DEBUG
Debug.Assert(Interlocked.Decrement(ref thisPtr._outstandingOperations._reads) >= 0,
"'thisPtr.m_OutstandingOperations.m_Reads' MUST NOT be negative.");
#endif
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(thisPtr);
}
if (eventArgs.Exception != null)
{
thisPtr._readTaskCompletionSource.TrySetException(eventArgs.Exception);
}
else
{
thisPtr._readTaskCompletionSource.TrySetResult(eventArgs.BytesTransferred);
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(thisPtr);
}
}
internal class HttpListenerAsyncEventArgs : EventArgs, IDisposable
{
private const int Free = 0;
private const int InProgress = 1;
private const int Disposed = 2;
private int _operating;
private bool _disposeCalled;
private unsafe NativeOverlapped* _ptrNativeOverlapped;
private ThreadPoolBoundHandle _boundHandle;
private event EventHandler<HttpListenerAsyncEventArgs> m_Completed;
private byte[] _buffer;
private IList<ArraySegment<byte>> _bufferList;
private int _count;
private int _offset;
private int _bytesTransferred;
private HttpListenerAsyncOperation _completedOperation;
private Interop.HttpApi.HTTP_DATA_CHUNK[] _dataChunks;
private GCHandle _dataChunksGCHandle;
private ushort _dataChunkCount;
private Exception _exception;
private bool _shouldCloseOutput;
private readonly WebSocketBase _webSocket;
private readonly WebSocketHttpListenerDuplexStream _currentStream;
public HttpListenerAsyncEventArgs(WebSocketBase webSocket, WebSocketHttpListenerDuplexStream stream)
: base()
{
_webSocket = webSocket;
_currentStream = stream;
}
public int BytesTransferred
{
get { return _bytesTransferred; }
}
public byte[] Buffer
{
get { return _buffer; }
}
// BufferList property.
// Mutually exclusive with Buffer.
// Setting this property with an existing non-null Buffer will cause an assert.
public IList<ArraySegment<byte>> BufferList
{
get { return _bufferList; }
set
{
Debug.Assert(!_shouldCloseOutput, "'m_ShouldCloseOutput' MUST be 'false' at this point.");
Debug.Assert(value == null || _buffer == null,
"Either 'm_Buffer' or 'm_BufferList' MUST be NULL.");
Debug.Assert(_operating == Free,
"This property can only be modified if no IO operation is outstanding.");
Debug.Assert(value == null || value.Count == 2,
"This list can only be 'NULL' or MUST have exactly '2' items.");
_bufferList = value;
}
}
public bool ShouldCloseOutput
{
get { return _shouldCloseOutput; }
}
public int Offset
{
get { return _offset; }
}
public int Count
{
get { return _count; }
}
public Exception Exception
{
get { return _exception; }
}
public ushort EntityChunkCount
{
get
{
if (_dataChunks == null)
{
return 0;
}
return _dataChunkCount;
}
}
internal unsafe NativeOverlapped* NativeOverlapped
{
get { return _ptrNativeOverlapped; }
}
public IntPtr EntityChunks
{
get
{
if (_dataChunks == null)
{
return IntPtr.Zero;
}
return Marshal.UnsafeAddrOfPinnedArrayElement(_dataChunks, 0);
}
}
public WebSocketHttpListenerDuplexStream CurrentStream
{
get { return _currentStream; }
}
public event EventHandler<HttpListenerAsyncEventArgs> Completed
{
add
{
m_Completed += value;
}
remove
{
m_Completed -= value;
}
}
protected virtual void OnCompleted(HttpListenerAsyncEventArgs e)
{
m_Completed?.Invoke(e._currentStream, e);
}
public void SetShouldCloseOutput()
{
_bufferList = null;
_buffer = null;
_shouldCloseOutput = true;
}
public void Dispose()
{
// Remember that Dispose was called.
_disposeCalled = true;
// Check if this object is in-use for an async socket operation.
if (Interlocked.CompareExchange(ref _operating, Disposed, Free) != Free)
{
// Either already disposed or will be disposed when current operation completes.
return;
}
// Don't bother finalizing later.
GC.SuppressFinalize(this);
}
private unsafe void InitializeOverlapped(ThreadPoolBoundHandle boundHandle)
{
_boundHandle = boundHandle;
_ptrNativeOverlapped = boundHandle.AllocateNativeOverlapped(CompletionPortCallback, null, null);
}
// Method to clean up any existing Overlapped object and related state variables.
private unsafe void FreeOverlapped(bool checkForShutdown)
{
if (!checkForShutdown || !Environment.HasShutdownStarted)
{
// Free the overlapped object
if (_ptrNativeOverlapped != null)
{
_boundHandle.FreeNativeOverlapped(_ptrNativeOverlapped);
_ptrNativeOverlapped = null;
}
if (_dataChunksGCHandle.IsAllocated)
{
_dataChunksGCHandle.Free();
_dataChunks = null;
}
}
}
// Method called to prepare for a native async http.sys call.
// This method performs the tasks common to all http.sys operations.
internal void StartOperationCommon(WebSocketHttpListenerDuplexStream currentStream, ThreadPoolBoundHandle boundHandle)
{
// Change status to "in-use".
if (Interlocked.CompareExchange(ref _operating, InProgress, Free) != Free)
{
// If it was already "in-use" check if Dispose was called.
if (_disposeCalled)
{
// Dispose was called - throw ObjectDisposed.
throw new ObjectDisposedException(GetType().FullName);
}
Debug.Assert(false, "Only one outstanding async operation is allowed per HttpListenerAsyncEventArgs instance.");
// Only one at a time.
throw new InvalidOperationException();
}
// HttpSendResponseEntityBody can return ERROR_INVALID_PARAMETER if the InternalHigh field of the overlapped
// is not IntPtr.Zero, so we have to reset this field because we are reusing the Overlapped.
// When using the IAsyncResult based approach of HttpListenerResponseStream the Overlapped is reinitialized
// for each operation by the CLR when returned from the OverlappedDataCache.
InitializeOverlapped(boundHandle);
_exception = null;
_bytesTransferred = 0;
}
internal void StartOperationReceive()
{
// Remember the operation type.
_completedOperation = HttpListenerAsyncOperation.Receive;
}
internal void StartOperationSend()
{
UpdateDataChunk();
// Remember the operation type.
_completedOperation = HttpListenerAsyncOperation.Send;
}
public void SetBuffer(byte[] buffer, int offset, int count)
{
Debug.Assert(!_shouldCloseOutput, "'m_ShouldCloseOutput' MUST be 'false' at this point.");
Debug.Assert(buffer == null || _bufferList == null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL.");
_buffer = buffer;
_offset = offset;
_count = count;
}
private unsafe void UpdateDataChunk()
{
if (_dataChunks == null)
{
_dataChunks = new Interop.HttpApi.HTTP_DATA_CHUNK[2];
_dataChunksGCHandle = GCHandle.Alloc(_dataChunks, GCHandleType.Pinned);
_dataChunks[0] = new Interop.HttpApi.HTTP_DATA_CHUNK();
_dataChunks[0].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
_dataChunks[1] = new Interop.HttpApi.HTTP_DATA_CHUNK();
_dataChunks[1].DataChunkType = Interop.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
}
Debug.Assert(_buffer == null || _bufferList == null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL.");
Debug.Assert(_shouldCloseOutput || _buffer != null || _bufferList != null, "Either 'm_Buffer' or 'm_BufferList' MUST NOT be NULL.");
// The underlying byte[] m_Buffer or each m_BufferList[].Array are pinned already
if (_buffer != null)
{
UpdateDataChunk(0, _buffer, _offset, _count);
UpdateDataChunk(1, null, 0, 0);
_dataChunkCount = 1;
}
else if (_bufferList != null)
{
Debug.Assert(_bufferList != null && _bufferList.Count == 2,
"'m_BufferList' MUST NOT be NULL and have exactly '2' items at this point.");
UpdateDataChunk(0, _bufferList[0].Array, _bufferList[0].Offset, _bufferList[0].Count);
UpdateDataChunk(1, _bufferList[1].Array, _bufferList[1].Offset, _bufferList[1].Count);
_dataChunkCount = 2;
}
else
{
Debug.Assert(_shouldCloseOutput, "'m_ShouldCloseOutput' MUST be 'true' at this point.");
_dataChunks = null;
}
}
private unsafe void UpdateDataChunk(int index, byte[] buffer, int offset, int count)
{
if (buffer == null)
{
_dataChunks[index].pBuffer = null;
_dataChunks[index].BufferLength = 0;
return;
}
if (_webSocket.InternalBuffer.IsInternalBuffer(buffer, offset, count))
{
_dataChunks[index].pBuffer = (byte*)(_webSocket.InternalBuffer.ToIntPtr(offset));
}
else
{
_dataChunks[index].pBuffer =
(byte*)_webSocket.InternalBuffer.ConvertPinnedSendPayloadToNative(buffer, offset, count);
}
_dataChunks[index].BufferLength = (uint)count;
}
// Method to mark this object as no longer "in-use".
// Will also execute a Dispose deferred because I/O was in progress.
internal void Complete()
{
FreeOverlapped(false);
// Mark as not in-use
Interlocked.Exchange(ref _operating, Free);
// Check for deferred Dispose().
// The deferred Dispose is not guaranteed if Dispose is called while an operation is in progress.
// The m_DisposeCalled variable is not managed in a thread-safe manner on purpose for performance.
if (_disposeCalled)
{
Dispose();
}
}
// Method to update internal state after sync or async completion.
private void SetResults(Exception exception, int bytesTransferred)
{
_exception = exception;
_bytesTransferred = bytesTransferred;
}
internal void FinishOperationFailure(Exception exception, bool syncCompletion)
{
SetResults(exception, 0);
if (NetEventSource.IsEnabled)
{
string methodName = _completedOperation == HttpListenerAsyncOperation.Receive ? nameof(ReadAsyncFast) : nameof(WriteAsyncFast);
NetEventSource.Error(_currentStream, $"{methodName} {exception.ToString()}");
}
Complete();
OnCompleted(this);
}
internal void FinishOperationSuccess(int bytesTransferred, bool syncCompletion)
{
SetResults(null, bytesTransferred);
if (NetEventSource.IsEnabled)
{
if (_buffer != null && NetEventSource.IsEnabled)
{
string methodName = _completedOperation == HttpListenerAsyncOperation.Receive ? nameof(ReadAsyncFast) : nameof(WriteAsyncFast);
NetEventSource.DumpBuffer(_currentStream, _buffer, _offset, bytesTransferred, methodName);
}
else if (_bufferList != null)
{
Debug.Assert(_completedOperation == HttpListenerAsyncOperation.Send,
"'BufferList' is only supported for send operations.");
foreach (ArraySegment<byte> buffer in BufferList)
{
NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, buffer.Count, nameof(WriteAsyncFast));
}
}
}
if (_shouldCloseOutput)
{
_currentStream._outputStream.SetClosedFlag();
}
// Complete the operation and raise completion event.
Complete();
OnCompleted(this);
}
private unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
if (errorCode == Interop.HttpApi.ERROR_SUCCESS ||
errorCode == Interop.HttpApi.ERROR_HANDLE_EOF)
{
FinishOperationSuccess((int)numBytes, false);
}
else
{
FinishOperationFailure(new HttpListenerException((int)errorCode), false);
}
}
public enum HttpListenerAsyncOperation
{
None,
Receive,
Send
}
}
}
}
| |
/*******************************************************************************
* Copyright 2017 ROBOTIS CO., LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/* Author: Ryu Woon Jung (Leon) */
using System;
using System.Runtime.InteropServices;
namespace dynamixel_sdk
{
class dynamixel
{
const string dll_path = "../../../../../../../../c/build/win32/output/dxl_x86_c.dll";
#region PortHandler
[DllImport(dll_path)]
public static extern int portHandler (string port_name);
[DllImport(dll_path)]
public static extern bool openPort (int port_num);
[DllImport(dll_path)]
public static extern void closePort (int port_num);
[DllImport(dll_path)]
public static extern void clearPort (int port_num);
[DllImport(dll_path)]
public static extern void setPortName (int port_num, string port_name);
[DllImport(dll_path)]
public static extern string getPortName (int port_num);
[DllImport(dll_path)]
public static extern bool setBaudRate (int port_num, int baudrate);
[DllImport(dll_path)]
public static extern int getBaudRate (int port_num);
[DllImport(dll_path)]
public static extern int readPort (int port_num, byte[] packet, int length);
[DllImport(dll_path)]
public static extern int writePort (int port_num, byte[] packet, int length);
[DllImport(dll_path)]
public static extern void setPacketTimeout (int port_num, UInt16 packet_length);
[DllImport(dll_path)]
public static extern void setPacketTimeoutMSec(int port_num, double msec);
[DllImport(dll_path)]
public static extern bool isPacketTimeout (int port_num);
#endregion
#region PacketHandler
[DllImport(dll_path)]
public static extern void packetHandler ();
[DllImport(dll_path)]
public static extern IntPtr getTxRxResult (int protocol_version, int result);
[DllImport(dll_path)]
public static extern IntPtr getRxPacketError (int protocol_version, byte error);
[DllImport(dll_path)]
public static extern int getLastTxRxResult (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern byte getLastRxPacketError(int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void setDataWrite (int port_num, int protocol_version, UInt16 data_length, UInt16 data_pos, UInt32 data);
[DllImport(dll_path)]
public static extern UInt32 getDataRead (int port_num, int protocol_version, UInt16 data_length, UInt16 data_pos);
[DllImport(dll_path)]
public static extern void txPacket (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void rxPacket (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void txRxPacket (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern void ping (int port_num, int protocol_version, byte id);
[DllImport(dll_path)]
public static extern UInt16 pingGetModelNum (int port_num, int protocol_version, byte id);
[DllImport(dll_path)]
public static extern void broadcastPing (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern bool getBroadcastPingResult(int port_num, int protocol_version, int id);
[DllImport(dll_path)]
public static extern void reboot (int port_num, int protocol_version, byte id);
[DllImport(dll_path)]
public static extern void factoryReset (int port_num, int protocol_version, byte id, byte option);
[DllImport(dll_path)]
public static extern void readTx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void readRx (int port_num, int protocol_version, UInt16 length);
[DllImport(dll_path)]
public static extern void readTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void read1ByteTx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern byte read1ByteRx (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern byte read1ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern void read2ByteTx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern UInt16 read2ByteRx (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern UInt16 read2ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern void read4ByteTx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern UInt32 read4ByteRx (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern UInt32 read4ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address);
[DllImport(dll_path)]
public static extern void writeTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void writeTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void write1ByteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, byte data);
[DllImport(dll_path)]
public static extern void write1ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address, byte data);
[DllImport(dll_path)]
public static extern void write2ByteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt16 data);
[DllImport(dll_path)]
public static extern void write2ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 data);
[DllImport(dll_path)]
public static extern void write4ByteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt32 data);
[DllImport(dll_path)]
public static extern void write4ByteTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt32 data);
[DllImport(dll_path)]
public static extern void regWriteTxOnly (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void regWriteTxRx (int port_num, int protocol_version, byte id, UInt16 address, UInt16 length);
[DllImport(dll_path)]
public static extern void syncReadTx (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length, UInt16 param_length);
// syncReadRx -> GroupSyncRead
// syncReadTxRx -> GroupSyncRead
[DllImport(dll_path)]
public static extern void syncWriteTxOnly (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length, UInt16 param_length);
[DllImport(dll_path)]
public static extern void bulkReadTx (int port_num, int protocol_version, UInt16 param_length);
// bulkReadRx -> GroupBulkRead
// bulkReadTxRx -> GroupBulkRead
[DllImport(dll_path)]
public static extern void bulkWriteTxOnly (int port_num, int protocol_version, UInt16 param_length);
#endregion
#region GroupBulkRead
[DllImport(dll_path)]
public static extern int groupBulkRead (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern bool groupBulkReadAddParam (int group_num, byte id, UInt16 start_address, UInt16 data_length);
[DllImport(dll_path)]
public static extern void groupBulkReadRemoveParam(int group_num, byte id);
[DllImport(dll_path)]
public static extern void groupBulkReadClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkReadTxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkReadRxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkReadTxRxPacket (int group_num);
[DllImport(dll_path)]
public static extern bool groupBulkReadIsAvailable(int group_num, byte id, UInt16 address, UInt16 data_length);
[DllImport(dll_path)]
public static extern UInt32 groupBulkReadGetData (int group_num, byte id, UInt16 address, UInt16 data_length);
#endregion
#region GroupBulkWrite
[DllImport(dll_path)]
public static extern int groupBulkWrite (int port_num, int protocol_version);
[DllImport(dll_path)]
public static extern bool groupBulkWriteAddParam (int group_num, byte id, UInt16 start_address, UInt16 data_length, UInt32 data, UInt16 input_length);
[DllImport(dll_path)]
public static extern void groupBulkWriteRemoveParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern bool groupBulkWriteChangeParam (int group_num, byte id, UInt16 start_address, UInt16 data_length, UInt32 data, UInt16 input_length, UInt16 data_pos);
[DllImport(dll_path)]
public static extern void groupBulkWriteClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupBulkWriteTxPacket (int group_num);
#endregion
#region GroupSyncRead
[DllImport(dll_path)]
public static extern int groupSyncRead (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length);
[DllImport(dll_path)]
public static extern bool groupSyncReadAddParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern void groupSyncReadRemoveParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern void groupSyncReadClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncReadTxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncReadRxPacket (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncReadTxRxPacket (int group_num);
[DllImport(dll_path)]
public static extern bool groupSyncReadIsAvailable (int group_num, byte id, UInt16 address, UInt16 data_length);
[DllImport(dll_path)]
public static extern UInt32 groupSyncReadGetData (int group_num, byte id, UInt16 address, UInt16 data_length);
#endregion
#region GroupSyncWrite
[DllImport(dll_path)]
public static extern int groupSyncWrite (int port_num, int protocol_version, UInt16 start_address, UInt16 data_length);
[DllImport(dll_path)]
public static extern bool groupSyncWriteAddParam (int group_num, byte id, UInt32 data, UInt16 data_length);
[DllImport(dll_path)]
public static extern void groupSyncWriteRemoveParam (int group_num, byte id);
[DllImport(dll_path)]
public static extern bool groupSyncWriteChangeParam (int group_num, byte id, UInt32 data, UInt16 data_length, UInt16 data_pos);
[DllImport(dll_path)]
public static extern void groupSyncWriteClearParam (int group_num);
[DllImport(dll_path)]
public static extern void groupSyncWriteTxPacket (int group_num);
#endregion
}
}
| |
using Lucene.Net.Support;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Search
{
/*
* 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.
*/
/// <summary>
/// Represents hits returned by
/// <see cref="IndexSearcher.Search(Query,Filter,int)"/> and
/// <see cref="IndexSearcher.Search(Query,int)"/>.
/// </summary>
public class TopDocs
{
/// <summary>
/// The total number of hits for the query. </summary>
public int TotalHits { get; set; }
/// <summary>
/// The top hits for the query. </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public ScoreDoc[] ScoreDocs { get; set; }
/// <summary>
/// Stores the maximum score value encountered, needed for normalizing. </summary>
private float maxScore;
/// <summary>
/// Returns the maximum score value encountered. Note that in case
/// scores are not tracked, this returns <see cref="float.NaN"/>.
/// </summary>
public virtual float MaxScore
{
get => maxScore;
set => this.maxScore = value;
}
/// <summary>
/// Constructs a <see cref="TopDocs"/> with a default <c>maxScore=System.Single.NaN</c>. </summary>
internal TopDocs(int totalHits, ScoreDoc[] scoreDocs)
: this(totalHits, scoreDocs, float.NaN)
{
}
public TopDocs(int totalHits, ScoreDoc[] scoreDocs, float maxScore)
{
this.TotalHits = totalHits;
this.ScoreDocs = scoreDocs;
this.maxScore = maxScore;
}
// Refers to one hit:
private class ShardRef
{
// Which shard (index into shardHits[]):
internal int ShardIndex { get; private set; }
// Which hit within the shard:
internal int HitIndex { get; set; }
public ShardRef(int shardIndex)
{
this.ShardIndex = shardIndex;
}
public override string ToString()
{
return "ShardRef(shardIndex=" + ShardIndex + " hitIndex=" + HitIndex + ")";
}
}
// Specialized MergeSortQueue that just merges by
// relevance score, descending:
private class ScoreMergeSortQueue : Util.PriorityQueue<ShardRef>
{
internal readonly ScoreDoc[][] shardHits;
public ScoreMergeSortQueue(TopDocs[] shardHits)
: base(shardHits.Length)
{
this.shardHits = new ScoreDoc[shardHits.Length][];
for (int shardIDX = 0; shardIDX < shardHits.Length; shardIDX++)
{
this.shardHits[shardIDX] = shardHits[shardIDX].ScoreDocs;
}
}
// Returns true if first is < second
protected internal override bool LessThan(ShardRef first, ShardRef second)
{
Debug.Assert(first != second);
float firstScore = shardHits[first.ShardIndex][first.HitIndex].Score;
float secondScore = shardHits[second.ShardIndex][second.HitIndex].Score;
if (firstScore < secondScore)
{
return false;
}
else if (firstScore > secondScore)
{
return true;
}
else
{
// Tie break: earlier shard wins
if (first.ShardIndex < second.ShardIndex)
{
return true;
}
else if (first.ShardIndex > second.ShardIndex)
{
return false;
}
else
{
// Tie break in same shard: resolve however the
// shard had resolved it:
Debug.Assert(first.HitIndex != second.HitIndex);
return first.HitIndex < second.HitIndex;
}
}
}
}
private class MergeSortQueue : Util.PriorityQueue<ShardRef>
{
// These are really FieldDoc instances:
internal readonly ScoreDoc[][] shardHits;
internal readonly FieldComparer[] comparers;
internal readonly int[] reverseMul;
public MergeSortQueue(Sort sort, TopDocs[] shardHits)
: base(shardHits.Length)
{
this.shardHits = new ScoreDoc[shardHits.Length][];
for (int shardIDX = 0; shardIDX < shardHits.Length; shardIDX++)
{
ScoreDoc[] shard = shardHits[shardIDX].ScoreDocs;
//System.out.println(" init shardIdx=" + shardIDX + " hits=" + shard);
if (shard != null)
{
this.shardHits[shardIDX] = shard;
// Fail gracefully if API is misused:
for (int hitIDX = 0; hitIDX < shard.Length; hitIDX++)
{
ScoreDoc sd = shard[hitIDX];
if (!(sd is FieldDoc))
{
throw new ArgumentException("shard " + shardIDX + " was not sorted by the provided Sort (expected FieldDoc but got ScoreDoc)");
}
FieldDoc fd = (FieldDoc)sd;
if (fd.Fields == null)
{
throw new ArgumentException("shard " + shardIDX + " did not set sort field values (FieldDoc.fields is null); you must pass fillFields=true to IndexSearcher.search on each shard");
}
}
}
}
SortField[] sortFields = sort.GetSort();
comparers = new FieldComparer[sortFields.Length];
reverseMul = new int[sortFields.Length];
for (int compIDX = 0; compIDX < sortFields.Length; compIDX++)
{
SortField sortField = sortFields[compIDX];
comparers[compIDX] = sortField.GetComparer(1, compIDX);
reverseMul[compIDX] = sortField.IsReverse ? -1 : 1;
}
}
// Returns true if first is < second
protected internal override bool LessThan(ShardRef first, ShardRef second)
{
Debug.Assert(first != second);
FieldDoc firstFD = (FieldDoc)shardHits[first.ShardIndex][first.HitIndex];
FieldDoc secondFD = (FieldDoc)shardHits[second.ShardIndex][second.HitIndex];
//System.out.println(" lessThan:\n first=" + first + " doc=" + firstFD.doc + " score=" + firstFD.score + "\n second=" + second + " doc=" + secondFD.doc + " score=" + secondFD.score);
for (int compIDX = 0; compIDX < comparers.Length; compIDX++)
{
FieldComparer comp = comparers[compIDX];
//System.out.println(" cmp idx=" + compIDX + " cmp1=" + firstFD.fields[compIDX] + " cmp2=" + secondFD.fields[compIDX] + " reverse=" + reverseMul[compIDX]);
int cmp = reverseMul[compIDX] * comp.CompareValues(firstFD.Fields[compIDX], secondFD.Fields[compIDX]);
if (cmp != 0)
{
//System.out.println(" return " + (cmp < 0));
return cmp < 0;
}
}
// Tie break: earlier shard wins
if (first.ShardIndex < second.ShardIndex)
{
//System.out.println(" return tb true");
return true;
}
else if (first.ShardIndex > second.ShardIndex)
{
//System.out.println(" return tb false");
return false;
}
else
{
// Tie break in same shard: resolve however the
// shard had resolved it:
//System.out.println(" return tb " + (first.hitIndex < second.hitIndex));
Debug.Assert(first.HitIndex != second.HitIndex);
return first.HitIndex < second.HitIndex;
}
}
}
/// <summary>
/// Returns a new <see cref="TopDocs"/>, containing <paramref name="topN"/> results across
/// the provided <see cref="TopDocs"/>, sorting by the specified
/// <see cref="Sort"/>. Each of the <see cref="TopDocs"/> must have been sorted by
/// the same <see cref="Sort"/>, and sort field values must have been
/// filled (ie, <c>fillFields=true</c> must be
/// passed to
/// <see cref="TopFieldCollector.Create(Sort, int, bool, bool, bool, bool)"/>.
///
/// <para/>Pass <paramref name="sort"/>=null to merge sort by score descending.
/// <para/>
/// @lucene.experimental
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public static TopDocs Merge(Sort sort, int topN, TopDocs[] shardHits)
{
return Merge(sort, 0, topN, shardHits);
}
/// <summary>
/// Same as <see cref="Merge(Sort, int, TopDocs[])"/> but also slices the result at the same time based
/// on the provided start and size. The return <c>TopDocs</c> will always have a scoreDocs with length of
/// at most <see cref="Util.PriorityQueue{T}.Count"/>.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public static TopDocs Merge(Sort sort, int start, int size, TopDocs[] shardHits)
{
Util.PriorityQueue<ShardRef> queue;
if (sort == null)
{
queue = new ScoreMergeSortQueue(shardHits);
}
else
{
queue = new MergeSortQueue(sort, shardHits);
}
int totalHitCount = 0;
int availHitCount = 0;
float maxScore = float.MinValue;
for (int shardIDX = 0; shardIDX < shardHits.Length; shardIDX++)
{
TopDocs shard = shardHits[shardIDX];
// totalHits can be non-zero even if no hits were
// collected, when searchAfter was used:
totalHitCount += shard.TotalHits;
if (shard.ScoreDocs != null && shard.ScoreDocs.Length > 0)
{
availHitCount += shard.ScoreDocs.Length;
queue.Add(new ShardRef(shardIDX));
maxScore = Math.Max(maxScore, shard.MaxScore);
//System.out.println(" maxScore now " + maxScore + " vs " + shard.getMaxScore());
}
}
if (availHitCount == 0)
{
maxScore = float.NaN;
}
ScoreDoc[] hits;
if (availHitCount <= start)
{
hits = EMPTY_SCOREDOCS;
}
else
{
hits = new ScoreDoc[Math.Min(size, availHitCount - start)];
int requestedResultWindow = start + size;
int numIterOnHits = Math.Min(availHitCount, requestedResultWindow);
int hitUpto = 0;
while (hitUpto < numIterOnHits)
{
Debug.Assert(queue.Count > 0);
ShardRef @ref = queue.Pop();
ScoreDoc hit = shardHits[@ref.ShardIndex].ScoreDocs[@ref.HitIndex++];
hit.ShardIndex = @ref.ShardIndex;
if (hitUpto >= start)
{
hits[hitUpto - start] = hit;
}
//System.out.println(" hitUpto=" + hitUpto);
//System.out.println(" doc=" + hits[hitUpto].doc + " score=" + hits[hitUpto].score);
hitUpto++;
if (@ref.HitIndex < shardHits[@ref.ShardIndex].ScoreDocs.Length)
{
// Not done with this these TopDocs yet:
queue.Add(@ref);
}
}
}
if (sort == null)
{
return new TopDocs(totalHitCount, hits, maxScore);
}
else
{
return new TopFieldDocs(totalHitCount, hits, sort.GetSort(), maxScore);
}
}
// LUCENENET specific - optimized empty array creation
private static readonly ScoreDoc[] EMPTY_SCOREDOCS =
#if FEATURE_ARRAYEMPTY
Array.Empty<ScoreDoc>();
#else
new ScoreDoc[0];
#endif
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices; // for DllImport, MarshalAs, etc
namespace Networking
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button groupbtn;
protected static Int64 LOCALGROUP_MEMBERS_INFO_1_SIZE;
protected static Int64 LOCALGROUP_INFO_1_SIZE;
private System.Windows.Forms.TreeView grouptv;
private string[] commentArray;
private System.Windows.Forms.Label label1;
private TextBox descriptionlb;
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
unsafe
{
LOCALGROUP_INFO_1_SIZE = sizeof(Win32API.LOCALGROUP_INFO_1);
LOCALGROUP_MEMBERS_INFO_1_SIZE = sizeof(Win32API.LOCALGROUP_MEMBERS_INFO_1);
}
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.groupbtn = new System.Windows.Forms.Button();
this.grouptv = new System.Windows.Forms.TreeView();
this.label1 = new System.Windows.Forms.Label();
this.descriptionlb = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// groupbtn
//
this.groupbtn.Location = new System.Drawing.Point(24, 16);
this.groupbtn.Name = "groupbtn";
this.groupbtn.Size = new System.Drawing.Size(160, 23);
this.groupbtn.TabIndex = 0;
this.groupbtn.Text = "Groups and Members";
this.groupbtn.Click += new System.EventHandler(this.groupbtn_Click);
//
// grouptv
//
this.grouptv.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.grouptv.Location = new System.Drawing.Point(24, 48);
this.grouptv.Name = "grouptv";
this.grouptv.Size = new System.Drawing.Size(246, 216);
this.grouptv.TabIndex = 2;
this.grouptv.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.grouptv_AfterSelect);
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label1.Location = new System.Drawing.Point(276, 48);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 176);
this.label1.TabIndex = 4;
this.label1.Text = "Select each node to see description and members in local computer.";
this.label1.Visible = false;
//
// descriptionlb
//
this.descriptionlb.AcceptsReturn = true;
this.descriptionlb.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.descriptionlb.Location = new System.Drawing.Point(24, 280);
this.descriptionlb.Multiline = true;
this.descriptionlb.Name = "descriptionlb";
this.descriptionlb.Size = new System.Drawing.Size(356, 74);
this.descriptionlb.TabIndex = 5;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(392, 366);
this.Controls.Add(this.descriptionlb);
this.Controls.Add(this.label1);
this.Controls.Add(this.grouptv);
this.Controls.Add(this.groupbtn);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void groupbtn_Click(object sender, System.EventArgs e)
{
//defining values for getting group names
uint level = 1, prefmaxlen = 0xFFFFFFFF, entriesread = 0, totalentries = 0;
//Values that will receive information.
IntPtr GroupInfoPtr,UserInfoPtr;
GroupInfoPtr = IntPtr.Zero;
UserInfoPtr = IntPtr.Zero;
Win32API.NetLocalGroupEnum(
IntPtr.Zero, //Server name.it must be null
level,//level can be 0 or 1 for groups.For more information see LOCALGROUP_INFO_0 and LOCALGROUP_INFO_1
ref GroupInfoPtr,//Value that will be receive information
prefmaxlen,//maximum length
ref entriesread,//value that receives the count of elements actually enumerated.
ref totalentries,//value that receives the approximate total number of entries that could have been enumerated from the current resume position.
IntPtr.Zero);
//this string array will hold comments of each group
commentArray = new string[totalentries];
grouptv.Nodes.Clear();
label1.Visible = true;
//getting group names and add them to tree view
for(int i = 0; i<totalentries; i++)
{
//converting unmanaged code to managed codes with using Marshal class
Int64 newOffset = GroupInfoPtr.ToInt64() + LOCALGROUP_INFO_1_SIZE * i;
Win32API.LOCALGROUP_INFO_1 groupInfo = (Win32API.LOCALGROUP_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset), typeof(Win32API.LOCALGROUP_INFO_1));
string currentGroupName = Marshal.PtrToStringAuto(groupInfo.lpszGroupName);
//storing group comment in an string array to show it in a label later
commentArray[i] = Marshal.PtrToStringAuto(groupInfo.lpszComment);
//add group name to tree
grouptv.Nodes.Add(currentGroupName);
//defining value for getting name of members in each group
uint prefmaxlen1 = 0xFFFFFFFF, entriesread1 = 0, totalentries1 = 0;
//paramaeters for NetLocalGroupGetMembers is like NetLocalGroupEnum.
Win32API.NetLocalGroupGetMembers(IntPtr.Zero,groupInfo.lpszGroupName,1, ref UserInfoPtr,prefmaxlen1,ref entriesread1,ref totalentries1, IntPtr.Zero);
//getting members name
for(int j = 0; j<totalentries1; j++)
{
//converting unmanaged code to managed codes with using Marshal class
Int64 newOffset1 = UserInfoPtr.ToInt64() + LOCALGROUP_MEMBERS_INFO_1_SIZE * j;
Win32API.LOCALGROUP_MEMBERS_INFO_1 memberInfo = (Win32API.LOCALGROUP_MEMBERS_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset1), typeof(Win32API.LOCALGROUP_MEMBERS_INFO_1));
String stringSid;
Win32API.ConvertSidToStringSid(memberInfo.lgrmi1_sid, out stringSid);
var currentUserName = Marshal.PtrToStringAuto(memberInfo.lgrmi1_name);
var sid = stringSid;
var sidUsage = memberInfo.lgrmi1_sidusage;
//adding member name to tree view
var userNode = new TreeNode(currentUserName)
{
Tag = new {Sid = sid, SidUsage = sidUsage},
};
grouptv.Nodes[i].Nodes.Add(userNode);
}
//free memory
Win32API.NetApiBufferFree(UserInfoPtr);
}
//free memory
Win32API.NetApiBufferFree(GroupInfoPtr);
}
private void grouptv_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
TreeView tr = (TreeView)sender;
dynamic tag = tr.SelectedNode.Tag;
string path = tr.SelectedNode.FullPath;
if(path.IndexOf("\\")==-1)
descriptionlb.Text = commentArray[tr.SelectedNode.Index];
else
{
//path = path.Substring(path.IndexOf("\\")+1);
descriptionlb.Text = String.Format("{1}{0}{2}{0}{3}", Environment.NewLine, path, tag.Sid, tag.SidUsage);
}
}
}
}
| |
// 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.Xml.Serialization;
using System.Diagnostics;
using System.Drawing;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using FlickrCache;
using FlickrNet;
using MonoTouchUtils;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.ObjCRuntime;
/// <summary>
/// Author: Saxon D'Aubin
/// </summary>
namespace FlickrCache
{
public delegate void PhotoAdded(PhotosetPhoto photo);
public delegate void NoticeMessage(string message);
public delegate void ImagesChanged(int totalCount, int recentlyArrivedCount, int recentlyDownloadedCount);
public class PhotosetCache
{
private const uint CarrierDownloadLimitInBytes = 1048576
#if DEBUG
/ 4; // limit to 1/4 mb
#else
/ 2; // limit to 1/2 mb
#endif
private readonly string photosetUserDefaultsKeyName;
/// <summary>
/// Set of known photo ids, used to notice when new images have arrived.
/// </summary>
///
private readonly HashSet<string> photoIds = new HashSet<string>();
private readonly FlickrNet.Flickr flickr;
private readonly string photosetId;
private readonly FlickrCache.Photoset photoset;
private DateTime? lastPhotoFetchTimestamp;
public event PhotoAdded Added;
public event NoticeMessage Messages;
public event ImagesChanged ImagesChanged;
public PhotosetCache(string apiKey, string sharedSecret, string photosetId)
{
this.photosetId = photosetId;
photosetUserDefaultsKeyName = "Photoset_" + photosetId;
flickr = new FlickrNet.Flickr (apiKey, sharedSecret);
// load the photo metadata that was saved in user defaults
try {
FlickrCache.Photoset savedPhotos = UserDefaultsUtils.LoadObject<FlickrCache.Photoset>(photosetUserDefaultsKeyName);
if (savedPhotos == null) {
photoset = new FlickrCache.Photoset();
photoset.Photo = new PhotosetPhoto[0];
} else {
photoset = savedPhotos;
Debug.WriteLine("Successfully loaded photoset data");
foreach (PhotosetPhoto p in photoset.Photo) {
photoIds.Add(p.Id);
}
}
} catch (Exception ex) {
Debug.WriteLine("An error occurred deserializing data: {0}", ex);
Debug.WriteLine(ex);
photoset = new FlickrCache.Photoset();
photoset.Photo = new PhotosetPhoto[0];
}
// hook up a listener so that we'll notice when connectivity changes
Debug.WriteLine("Attach reachability listener");
Reachability.ReachabilityChanged += ReachabilityChanged;
}
public void Close() {
Reachability.ReachabilityChanged -= ReachabilityChanged;
}
private bool PhotosAvailable {
get {
return photoset.Photo.Length == 0 || photoset.Photo.Length != Photos.Length;
}
}
/// <summary>
/// The network connection status has changed. Update if we have a connection.
/// </summary>
private void ReachabilityChanged(object sender, EventArgs args) {
NetworkStatus status = Reachability.RemoteHostStatus();
Debug.WriteLine("Reachability changed: {0}", status);
if (NetworkStatus.ReachableViaWiFiNetwork == status ||
(NetworkStatus.ReachableViaCarrierDataNetwork == status &&
PhotosAvailable)) {
System.Threading.ThreadPool.QueueUserWorkItem(delegate {
if (photoset.Photo.Length == 0) {
Fetch (status);
} else {
FetchImages(status);
}
});
}
}
public bool Stale {
get {
#if DEBUG
TimeSpan staleSpan = TimeSpan.FromMinutes(5);
#else
TimeSpan staleSpan = TimeSpan.FromHours(6);
#endif
// photos are stale if we've never fetched or it's been more than 6 hours
return lastPhotoFetchTimestamp == null ? true :
(DateTime.UtcNow - lastPhotoFetchTimestamp) > staleSpan;
}
}
public PhotosetPhoto[] Photos {
get {
// if we have a wifi connection, return all the photos assuming they'll be downloaded
if (NetworkStatus.ReachableViaWiFiNetwork == Reachability.RemoteHostStatus()) {
return photoset.Photo;
}
else
{
// otherwise, filter the set of photos to the ones that have been cached to storage
List<PhotosetPhoto> photoList = new List<PhotosetPhoto>(photoset.Photo.Length);
foreach (PhotosetPhoto p in photoset.Photo) {
if (null != FileCacher.LoadUrl(p.Url, false)) {
photoList.Add(p);
}
}
return photoList.ToArray();
}
}
}
private FlickrNet.Photoset GetPhotosetInfo() {
bool networkIndicator = UIApplication.SharedApplication.NetworkActivityIndicatorVisible;
try {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
Debug.WriteLine("Fetching photoset info");
return flickr.PhotosetsGetInfo(photosetId);
} finally {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = networkIndicator;
}
}
private PhotosetPhotoCollection GetPhotosetPhotoCollection() {
bool networkIndicator = UIApplication.SharedApplication.NetworkActivityIndicatorVisible;
try {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
Debug.WriteLine("Fetching photoset photo list");
return flickr.PhotosetsGetPhotos(photosetId, PhotoSearchExtras.AllUrls | PhotoSearchExtras.Tags);
} finally {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = networkIndicator;
}
}
/// <summary>
/// Fetch photo information from Flickr and persist it to local storage if there are new photos.
/// </summary>
public void Fetch(NetworkStatus status) {
lastPhotoFetchTimestamp = DateTime.UtcNow;
Debug.WriteLine("Http request on thread {0}:{1}",
System.Threading.Thread.CurrentThread.ManagedThreadId, System.Threading.Thread.CurrentThread.Name);
var info = GetPhotosetInfo();
if (photoset.LastUpdatedSpecified) {
if (info.DateUpdated == photoset.LastUpdated &&
photoset.Photo != null && info.NumberOfPhotos == photoset.Photo.Length) {
Debug.WriteLine("Up to date : {0}", info.DateUpdated);
return;
}
}
photoset.LastUpdated = info.DateUpdated;
photoset.LastUpdatedSpecified = true;
photoset.Title = info.Title;
if (Messages != null) {
Messages("Updating the cartoon list");
}
var photos = GetPhotosetPhotoCollection();
List<PhotosetPhoto> newPhotos = new List<PhotosetPhoto>();
List<PhotosetPhoto> allPhotos = new List<PhotosetPhoto>();
lock (this.photoset) {
photoset.Photo = new PhotosetPhoto[photos.Count];
foreach (Photo p in photos) {
var thePhoto = CreatePhotosetPhoto(p);
allPhotos.Add(thePhoto);
if (!photoIds.Contains(p.PhotoId)) {
newPhotos.Add(thePhoto);
photoIds.Add(p.PhotoId);
}
}
photoset.Photo = allPhotos.ToArray();
}
Save();
int dlCount = FetchImages(status);
if (null != ImagesChanged) {
ImagesChanged(photoset.Photo.Length, newPhotos.Count, dlCount);
}
}
/// <summary>
/// A convenience constructor to create our PhotosetPhoto object from a FlickrNet photo.
/// </summary>
public static PhotosetPhoto CreatePhotosetPhoto(Photo p) {
var photo = new FlickrCache.PhotosetPhoto();
photo.Title = p.Title;
photo.Id = p.PhotoId;
photo.Url = GetUrl(p);
photo.Tags = new List<string>(p.Tags).ToArray();
return photo;
}
private static bool LargerThanBounds(float width, float height, SizeF bounds) {
return width > bounds.Width || height > bounds.Height;
}
/// <summary>
/// Returns the URL by picking the smallest image that is larger than the device screen bounds.
/// </summary>
private static string GetUrl(Photo photo) {
var bounds = UIScreen.MainScreen.Bounds.Size;
if (photo.SmallWidth.HasValue && LargerThanBounds(photo.SmallWidth.Value, photo.SmallHeight.Value, bounds)) {
return photo.SmallUrl;
}
if (photo.MediumWidth.HasValue && LargerThanBounds(photo.MediumWidth.Value, photo.MediumHeight.Value, bounds)) {
return photo.MediumUrl;
}
if (photo.Medium640Width.HasValue && LargerThanBounds(photo.Medium640Width.Value, photo.Medium640Height.Value, bounds)) {
return photo.Medium640Url;
}
return photo.LargeUrl;
}
/// <summary>
/// Fetch images that have not already been cached.
/// </summary>
/// <returns>
/// The count of the number of downloaded images.
/// </returns>
/// <param name='status'>
/// The current network status.
/// </param>
private int FetchImages(NetworkStatus status) {
if (NetworkStatus.NotReachable == status) return 0;
List<PhotosetPhoto> downloadedPhotos = new List<PhotosetPhoto>();
// limit cell downloads
uint byteLimit = NetworkStatus.ReachableViaCarrierDataNetwork == status ? CarrierDownloadLimitInBytes : UInt32.MaxValue;
uint byteCount = 0;
// warm the image file cache
lock (this.photoset) {
foreach (var p in this.photoset.Photo) {
// if the photo is not cached, load it
if (FileCacher.LoadUrl(p.Url, false) == null) {
var data = FileCacher.LoadUrl(p.Url, true);
byteCount += data.Length;
downloadedPhotos.Add(p);
if (null != Added) {
Added(p);
}
if (byteCount > byteLimit) {
break;
}
}
}
}
return downloadedPhotos.Count;
}
/// <summary>
/// Save all of the photo information to user defaults.
/// </summary>
public void Save() {
UserDefaultsUtils.SaveObject(photosetUserDefaultsKeyName, photoset);
Debug.WriteLine("Successfully saved photoset data");
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Launches a specified number of instances of an AMI for which you have permissions.
/// </summary>
/// <remarks>
/// If Amazon EC2 cannot launch the minimum number AMIs you request, no
/// instances will be launched. If there is insufficient capacity to
/// launch the maximum number of AMIs you request, Amazon EC2 launches the minimum
/// number specified for each AMI and allocate the remaining available
/// instances using round robin.
///
/// In the following example, Libby generates a request to
/// launch two images (database and web_server):
///
/// Libby runs the RunInstances operation to launch database instances
/// (min. 10, max. 15) and web_server instances (min. 30, max. 40).
///
/// Because there are currently 30 instances available and Libby needs a
/// minimum of 40, no instances are launched.
///
/// Libby adjusts the number of instances she needs and runs the
/// RunInstances operation to launch database
/// instances (min. 5, max. 10) and web_server
/// instances (min. 20, max. 40).
///
/// Amazon EC2 launches the minimum number of instances for each
/// AMI (5 database, 20 web_server).
///
/// The remaining 5 instances are allocated using round robin.
///
/// Libby adjusts the number of instances she needs and runs the RunInstances
/// operation again to launch database instances (min. 5, max. 10) and
/// web_server instances (min. 20, max. 40).
///
/// Note - every instance is launched in a security group
/// (created using the CreateSecurityGroup operation.)
///
/// You can provide an optional key pair ID for each image in the launch request
/// (created using the CreateKeyPair operation). All instances that
/// are created from images that use this key pair will have access to
/// the associated public key at boot. You can use this key to provide
/// secure access to an instance of an image on a per-instance basis.
/// Amazon EC2 public images use this feature to provide secure access
/// without passwords.
///
/// Important - launching public images without a key pair ID will leave them
/// inaccessible.
///
/// The public key material is made available to the instance at boot
/// time by placing it in the openssh_id.pub file on a logical device that is exposed
/// to the instance as /dev/sda2 (the instance store). The format of this
/// file is suitable for use as an entry within ~/.ssh/authorized_keys
/// (the OpenSSH format). This can be done at boot (e.g., as part of rc.local) allowing
/// for secure access without passwords.
///
/// Optional user data can be provided in the launch request. All instances that
/// collectively comprise the launch request have access to this data.
/// For more information, go the Amazon Elastic Compute Cloud Developer
/// Guide.
///
/// Note - if any of the AMIs have a product code attached for
/// which the user has not subscribed, the RunInstances call will fail.
///
/// Important - we strongly recommend using the 2.6.18 Xen stock
/// kernel with High-CPU and High-Memory instances. Although the
/// default Amazon EC2 kernels will work, the new kernels provide
/// greater stability and performance for these instance types. For more
/// information about kernels, go the Amazon Elastic Compute Cloud Developer Guide
/// </remarks>
[XmlRootAttribute(IsNullable = false)]
public class RunInstancesRequest : EC2Request
{
private string imageIdField;
private Decimal? minCountField;
private Decimal? maxCountField;
private string keyNameField;
private List<string> securityGroupField;
private List<string> securityGroupIdField;
private string userDataField;
private string instanceTypeField;
private Placement placementField;
private string kernelIdField;
private string ramdiskIdField;
private List<BlockDeviceMapping> blockDeviceMappingField;
private MonitoringSpecification monitoringField;
private string subnetIdField;
private bool? disableApiTerminationField;
private string instanceInitiatedShutdownBehaviorField;
private InstanceLicenseSpecification licenseField;
private string privateIpAddressField;
private string clientTokenField;
private List<InstanceNetworkInterfaceSpecification> networkInterfaceSetField;
private bool? ebsOptimizedField;
private IAMInstanceProfile instanceProfileField;
/// <summary>
/// Unique ID of a machine image.
/// </summary>
[XmlElementAttribute(ElementName = "ImageId")]
public string ImageId
{
get { return this.imageIdField; }
set { this.imageIdField = value; }
}
/// <summary>
/// Sets the unique ID of a machine image.
/// </summary>
/// <param name="imageId">Unique ID of a machine image,</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithImageId(string imageId)
{
this.imageIdField = imageId;
return this;
}
/// <summary>
/// Checks if ImageId property is set
/// </summary>
/// <returns>true if ImageId property is set</returns>
public bool IsSetImageId()
{
return this.imageIdField != null;
}
/// <summary>
/// Minimum number of instances to launch.
/// If the value is more than Amazon EC2 can launch,
/// no instances are launched at all.
///
/// Constraints: Between 1 and the maximum number
/// allowed for your account (default: 20).
/// </summary>
[XmlElementAttribute(ElementName = "MinCount")]
public Decimal MinCount
{
get { return this.minCountField.GetValueOrDefault(); }
set { this.minCountField = value; }
}
/// <summary>
/// Sets the minimum number of instances to launch.
/// </summary>
/// <param name="minCount">Minimum number of instances to launch. If the
/// value is more than Amazon
/// EC2 can launch, no instances are launched at all.
///
/// Constraints: Between 1 and the maximum number
/// allowed for your account (default: 20).</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithMinCount(Decimal minCount)
{
this.minCountField = minCount;
return this;
}
/// <summary>
/// Checks if MinCount property is set
/// </summary>
/// <returns>true if MinCount property is set</returns>
public bool IsSetMinCount()
{
return this.minCountField.HasValue;
}
/// <summary>
/// Maximum number of instances to launch.
/// If the value is more than Amazon EC2 can launch, the largest possible
/// number above minCount will be launched instead.
///
/// Constraints:
/// Between 1 and the maximum number allowed for your account
/// (default: 20).
/// </summary>
[XmlElementAttribute(ElementName = "MaxCount")]
public Decimal MaxCount
{
get { return this.maxCountField.GetValueOrDefault(); }
set { this.maxCountField = value; }
}
/// <summary>
/// Sets the maximum number of instances to launch.
/// </summary>
/// <param name="maxCount">Maximum number of instances to launch. If the
/// value is more than Amazon
/// EC2 can launch, the largest possible
/// number above minCount will be launched instead.
///
/// Constraints:
/// Between 1 and the maximum number allowed for your account
/// (default: 20).</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithMaxCount(Decimal maxCount)
{
this.maxCountField = maxCount;
return this;
}
/// <summary>
/// Checks if MaxCount property is set
/// </summary>
/// <returns>true if MaxCount property is set</returns>
public bool IsSetMaxCount()
{
return this.maxCountField.HasValue;
}
/// <summary>
/// The name of the key pair to use.
/// </summary>
[XmlElementAttribute(ElementName = "KeyName")]
public string KeyName
{
get { return this.keyNameField; }
set { this.keyNameField = value; }
}
/// <summary>
/// Sets the name of the key pair to use.
/// </summary>
/// <param name="keyName">The name of the key pair.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithKeyName(string keyName)
{
this.keyNameField = keyName;
return this;
}
/// <summary>
/// Checks if KeyName property is set
/// </summary>
/// <returns>true if KeyName property is set</returns>
public bool IsSetKeyName()
{
return this.keyNameField != null;
}
/// <summary>
/// Names of the security groups.
/// </summary>
[XmlElementAttribute(ElementName = "SecurityGroup")]
public List<string> SecurityGroup
{
get
{
if (this.securityGroupField == null)
{
this.securityGroupField = new List<string>();
}
return this.securityGroupField;
}
set { this.securityGroupField = value; }
}
/// <summary>
/// Sets the names of the security groups.
/// </summary>
/// <param name="list">Names of the security group.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithSecurityGroup(params string[] list)
{
foreach (string item in list)
{
SecurityGroup.Add(item);
}
return this;
}
/// <summary>
/// Checks if SecurityGroup property is set
/// </summary>
/// <returns>true if SecurityGroup property is set</returns>
public bool IsSetSecurityGroup()
{
return (SecurityGroup.Count > 0);
}
/// <summary>
/// IDs of the security groups.
/// </summary>
[XmlElementAttribute(ElementName = "SecurityGroupId")]
public List<string> SecurityGroupId
{
get
{
if (this.securityGroupIdField == null)
{
this.securityGroupIdField = new List<string>();
}
return this.securityGroupIdField;
}
set { this.securityGroupIdField = value; }
}
/// <summary>
/// Sets the IDs of the security groups.
/// </summary>
/// <param name="list">IDs of the security group.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithSecurityGroupId(params string[] list)
{
foreach (string item in list)
{
SecurityGroupId.Add(item);
}
return this;
}
/// <summary>
/// Checks if SecurityGroupId property is set
/// </summary>
/// <returns>true if SecurityGroupId property is set</returns>
public bool IsSetSecurityGroupId()
{
return (SecurityGroupId.Count > 0);
}
/// <summary>
/// MIME, Base64-encoded user data.
/// </summary>
[XmlElementAttribute(ElementName = "UserData")]
public string UserData
{
get { return this.userDataField; }
set { this.userDataField = value; }
}
/// <summary>
/// Sets the MIME, Base64-encoded user data.
/// </summary>
/// <param name="userData">MIME, Base64-encoded user data.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithUserData(string userData)
{
this.userDataField = userData;
return this;
}
/// <summary>
/// Checks if UserData property is set
/// </summary>
/// <returns>true if UserData property is set</returns>
public bool IsSetUserData()
{
return this.userDataField != null;
}
/// <summary>
/// The instance type.
///
/// Valid Values:
/// m1.small | m1.medium | m1.large | m1.xlarge | c1.medium |
/// c1.xlarge | m2.2xlarge | m2.4xlarge
///
/// Default: m1.small
/// </summary>
[XmlElementAttribute(ElementName = "InstanceType")]
public string InstanceType
{
get { return this.instanceTypeField; }
set { this.instanceTypeField = value; }
}
/// <summary>
/// Sets the instance type.
/// </summary>
/// <param name="instanceType">Specifies the instance type.
///
/// Valid Values:
/// m1.small | m1.medium | m1.large | m1.xlarge | c1.medium |
/// c1.xlarge | m2.2xlarge | m2.4xlarge
///
/// Default: m1.small</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithInstanceType(string instanceType)
{
this.instanceTypeField = instanceType;
return this;
}
/// <summary>
/// Checks if InstanceType property is set
/// </summary>
/// <returns>true if InstanceType property is set</returns>
public bool IsSetInstanceType()
{
return this.instanceTypeField != null;
}
/// <summary>
/// The placement constraints.
/// </summary>
[XmlElementAttribute(ElementName = "Placement")]
public Placement Placement
{
get { return this.placementField; }
set { this.placementField = value; }
}
/// <summary>
/// Sets the placement constraints.
/// </summary>
/// <param name="placement">Specifies the placement constraints.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithPlacement(Placement placement)
{
this.placementField = placement;
return this;
}
/// <summary>
/// Checks if Placement property is set
/// </summary>
/// <returns>true if Placement property is set</returns>
public bool IsSetPlacement()
{
return this.placementField != null;
}
/// <summary>
/// The ID of the kernel with which to launch the instance.
/// </summary>
[XmlElementAttribute(ElementName = "KernelId")]
public string KernelId
{
get { return this.kernelIdField; }
set { this.kernelIdField = value; }
}
/// <summary>
/// Sets the ID of the kernel with which to launch the instance.
/// </summary>
/// <param name="kernelId">The ID of the kernel with which to launch the
/// instance.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithKernelId(string kernelId)
{
this.kernelIdField = kernelId;
return this;
}
/// <summary>
/// Checks if KernelId property is set
/// </summary>
/// <returns>true if KernelId property is set</returns>
public bool IsSetKernelId()
{
return this.kernelIdField != null;
}
/// <summary>
/// The ID of the RAM disk with which to launch the instance.
/// Some kernels require additional drivers at launch.
/// Check the kernel requirements for information on whether you need
/// to specify a RAM disk. To find kernel requirements, go to the
/// Resource Center and search for the kernel ID.
/// </summary>
[XmlElementAttribute(ElementName = "RamdiskId")]
public string RamdiskId
{
get { return this.ramdiskIdField; }
set { this.ramdiskIdField = value; }
}
/// <summary>
/// Sets the ID of the RAM disk with which to launch the instance.
/// </summary>
/// <param name="ramdiskId">The ID of the RAM disk with which to launch
/// the instance. Some kernels
/// require additional drivers at launch.
/// Check the kernel requirements for
/// information on whether you need
/// to specify a RAM disk. To find kernel
/// requirements, go to the
/// Resource Center and search for the
/// kernel ID.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithRamdiskId(string ramdiskId)
{
this.ramdiskIdField = ramdiskId;
return this;
}
/// <summary>
/// Checks if RamdiskId property is set
/// </summary>
/// <returns>true if RamdiskId property is set</returns>
public bool IsSetRamdiskId()
{
return this.ramdiskIdField != null;
}
/// <summary>
/// Block device mapping.
/// </summary>
[XmlElementAttribute(ElementName = "BlockDeviceMapping")]
public List<BlockDeviceMapping> BlockDeviceMapping
{
get
{
if (this.blockDeviceMappingField == null)
{
this.blockDeviceMappingField = new List<BlockDeviceMapping>();
}
return this.blockDeviceMappingField;
}
set { this.blockDeviceMappingField = value; }
}
/// <summary>
/// Sets the block device mapping.
/// </summary>
/// <param name="list">Block device mapping.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithBlockDeviceMapping(params BlockDeviceMapping[] list)
{
foreach (BlockDeviceMapping item in list)
{
BlockDeviceMapping.Add(item);
}
return this;
}
/// <summary>
/// Checks if BlockDeviceMapping property is set
/// </summary>
/// <returns>true if BlockDeviceMapping property is set</returns>
public bool IsSetBlockDeviceMapping()
{
return (BlockDeviceMapping.Count > 0);
}
/// <summary>
/// Monitoring for the instance.
/// </summary>
[XmlElementAttribute(ElementName = "Monitoring")]
public MonitoringSpecification Monitoring
{
get { return this.monitoringField; }
set { this.monitoringField = value; }
}
/// <summary>
/// Sets the monitoring for the instance.
/// </summary>
/// <param name="monitoring">Enables monitoring for the instance.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithMonitoring(MonitoringSpecification monitoring)
{
this.monitoringField = monitoring;
return this;
}
/// <summary>
/// Checks if Monitoring property is set
/// </summary>
/// <returns>true if Monitoring property is set</returns>
public bool IsSetMonitoring()
{
return this.monitoringField != null;
}
/// <summary>
/// The subnet ID within which to launch the instance(s) for Amazon
/// Virtual Private Cloud.
/// </summary>
[XmlElementAttribute(ElementName = "SubnetId")]
public string SubnetId
{
get { return this.subnetIdField; }
set { this.subnetIdField = value; }
}
/// <summary>
/// Sets the subnet ID within which to launch the instance(s) for Amazon
/// Virtual Private Cloud.
/// </summary>
/// <param name="subnetId">Specifies the subnet ID within which to launch
/// the instance(s) for
/// Amazon Virtual Private Cloud.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithSubnetId(string subnetId)
{
this.subnetIdField = subnetId;
return this;
}
/// <summary>
/// Checks if SubnetId property is set
/// </summary>
/// <returns>true if SubnetId property is set</returns>
public bool IsSetSubnetId()
{
return this.subnetIdField != null;
}
/// <summary>
/// Whether the instance can be terminated using the APIs.
/// You must modify this attribute before you can terminate any "locked"
/// instances from the APIs.
/// </summary>
[XmlElementAttribute(ElementName = "DisableApiTermination")]
public bool DisableApiTermination
{
get { return this.disableApiTerminationField.GetValueOrDefault(); }
set { this.disableApiTerminationField = value; }
}
/// <summary>
/// Sets whether the instance can be terminated using the APIs.
/// </summary>
/// <param name="disableApiTermination">Specifies whether the instance can be
/// terminated using the APIs. You must modify this attribute before
/// you can terminate any "locked" instances from the APIs.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithDisableApiTermination(bool disableApiTermination)
{
this.disableApiTerminationField = disableApiTermination;
return this;
}
/// <summary>
/// Checks if DisableApiTermination property is set
/// </summary>
/// <returns>true if DisableApiTermination property is set</returns>
public bool IsSetDisableApiTermination()
{
return this.disableApiTerminationField.HasValue;
}
/// <summary>
/// Whether the instance's Amazon EBS volumes are stopped or terminated
/// when the instance is shut down.
/// </summary>
[XmlElementAttribute(ElementName = "InstanceInitiatedShutdownBehavior")]
public string InstanceInitiatedShutdownBehavior
{
get { return this.instanceInitiatedShutdownBehaviorField; }
set { this.instanceInitiatedShutdownBehaviorField = value; }
}
/// <summary>
/// Sets whether the instance's Amazon EBS volumes are stopped or terminated
/// when the instance is shut down.
/// </summary>
/// <param name="instanceInitiatedShutdownBehavior">Specifies whether the instance's Amazon EBS
/// volumes are stopped or terminated when the instance is shut
/// down.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithInstanceInitiatedShutdownBehavior(string instanceInitiatedShutdownBehavior)
{
this.instanceInitiatedShutdownBehaviorField = instanceInitiatedShutdownBehavior;
return this;
}
/// <summary>
/// Checks if InstanceInitiatedShutdownBehavior property is set
/// </summary>
/// <returns>true if InstanceInitiatedShutdownBehavior property is set</returns>
public bool IsSetInstanceInitiatedShutdownBehavior()
{
return this.instanceInitiatedShutdownBehaviorField != null;
}
/// <summary>
/// Active licenses in use and attached to an Amazon EC2 instance.
/// </summary>
[XmlElementAttribute(ElementName = "License")]
public InstanceLicenseSpecification License
{
get { return this.licenseField; }
set { this.licenseField = value; }
}
/// <summary>
/// Sets the active licenses in use and attached to an Amazon EC2 instance.
/// </summary>
/// <param name="license">Specifies active licenses in use and attached
/// to an Amazon EC2 instance.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithLicense(InstanceLicenseSpecification license)
{
this.licenseField = license;
return this;
}
/// <summary>
/// Checks if License property is set
/// </summary>
/// <returns>true if License property is set</returns>
public bool IsSetLicense()
{
return this.licenseField != null;
}
/// <summary>
/// Private IP address for this instance.
/// <remarks>
/// If you're using Amazon Virtual Private Cloud, you can optionally use this
/// parameter to assign the instance a specific available IP address from the
/// subnet.
/// </remarks>
/// </summary>
[XmlElementAttribute(ElementName = "PrivateIpAddress")]
public string PrivateIpAddress
{
get { return this.privateIpAddressField; }
set { this.privateIpAddressField = value; }
}
/// <summary>
/// Sets the private IP address for this instance.
/// </summary>
/// <param name="privateIpAddress">If you're using Amazon Virtual Private Cloud,
/// you can optionally use this
/// parameter to assign the instance a
/// specific available IP address from the
/// subnet.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithPrivateIpAddress(string privateIpAddress)
{
this.privateIpAddressField = privateIpAddress;
return this;
}
/// <summary>
/// Checks if PrivateIpAddress property is set
/// </summary>
/// <returns>true if PrivateIpAddress property is set</returns>
public bool IsSetPrivateIpAddress()
{
return this.privateIpAddressField != null;
}
/// <summary>
/// Unique, case-sensitive identifier you provide to ensure idempotency of the request.
/// </summary>
[XmlElementAttribute(ElementName = "ClientToken")]
public string ClientToken
{
get { return this.clientTokenField; }
set { this.clientTokenField = value; }
}
/// <summary>
/// Sets the unique, case-sensitive identifier to ensure idempotency of the request.
/// </summary>
/// <param name="clientToken">ClientToken property</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithClientToken(string clientToken)
{
this.clientTokenField = clientToken;
return this;
}
/// <summary>
/// Checks if ClientToken property is set
/// </summary>
/// <returns>true if ClientToken property is set</returns>
public bool IsSetClientToken()
{
return this.clientTokenField != null;
}
/// <summary>
/// A set of one or more existing network interfaces to attach to the instance.
/// </summary>
[XmlElementAttribute(ElementName = "NetworkInterfaceSet")]
public List<InstanceNetworkInterfaceSpecification> NetworkInterfaceSet
{
get
{
if (this.networkInterfaceSetField == null)
{
this.networkInterfaceSetField = new List<InstanceNetworkInterfaceSpecification>();
}
return this.networkInterfaceSetField;
}
set { this.networkInterfaceSetField = value; }
}
/// <summary>
/// Sets one or more existing network interfaces to attach to the instance.
/// </summary>
/// <param name="list">A set of one or more existing network interfaces to attach to the instance.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithNetworkInterfaceSet(params InstanceNetworkInterfaceSpecification[] list)
{
foreach (InstanceNetworkInterfaceSpecification item in list)
{
this.NetworkInterfaceSet.Add(item);
}
return this;
}
/// <summary>
/// Checks if the NetworkInterfaceSet property is set
/// </summary>
/// <returns>true if the NetworkInterfaceSet property is set</returns>
public bool IsSetNetworkInterfaceSet()
{
return (this.NetworkInterfaceSet.Count > 0);
}
/// <summary>
/// Whether to use the EBS IOPS optimized option.
/// </summary>
[XmlElementAttribute(ElementName = "EbsOptimized")]
public bool EbsOptimized
{
get { return this.ebsOptimizedField.GetValueOrDefault(); }
set { this.ebsOptimizedField = value; }
}
/// <summary>
/// Sets whether to use the EBS IOPS optimized option.
/// </summary>
/// <param name="ebsOptimized">Specifies whether to use the EBS
/// IOPS optimized option.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithEbsOptimized(bool ebsOptimized)
{
this.ebsOptimizedField = ebsOptimized;
return this;
}
/// <summary>
/// Checks if EbsOptimized property is set
/// </summary>
/// <returns>true if EbsOptimized property is set</returns>
public bool IsSetEbsOptimized()
{
return this.ebsOptimizedField.HasValue;
}
/// <summary>
/// An Identity and Access Management Instance Profile to associate with the instance.
/// </summary>
[XmlElementAttribute(ElementName = "InstanceProfile")]
public IAMInstanceProfile InstanceProfile
{
get { return this.instanceProfileField; }
set { this.instanceProfileField = value; }
}
/// <summary>
/// Sets an Identity and Access Management Instance Profile to associate with the instance.
/// </summary>
/// <param name="instanceProfile">
/// An Identity and Access Management Instance Profile to associate with the instance.
/// </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public RunInstancesRequest WithInstanceProfile(IAMInstanceProfile instanceProfile)
{
this.instanceProfileField = instanceProfile;
return this;
}
/// <summary>
/// Checks if the InstanceProfile property is set
/// </summary>
/// <returns>true if the InstanceProfile property is set</returns>
public bool IsSetInstanceProfile()
{
return this.instanceProfileField != null;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// DR task
/// First published in XenServer 6.0.
/// </summary>
public partial class DR_task : XenObject<DR_task>
{
#region Constructors
public DR_task()
{
}
public DR_task(string uuid,
List<XenRef<SR>> introduced_SRs)
{
this.uuid = uuid;
this.introduced_SRs = introduced_SRs;
}
/// <summary>
/// Creates a new DR_task from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public DR_task(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new DR_task from a Proxy_DR_task.
/// </summary>
/// <param name="proxy"></param>
public DR_task(Proxy_DR_task proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given DR_task.
/// </summary>
public override void UpdateFrom(DR_task record)
{
uuid = record.uuid;
introduced_SRs = record.introduced_SRs;
}
internal void UpdateFrom(Proxy_DR_task proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
introduced_SRs = proxy.introduced_SRs == null ? null : XenRef<SR>.Create(proxy.introduced_SRs);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this DR_task
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("introduced_SRs"))
introduced_SRs = Marshalling.ParseSetRef<SR>(table, "introduced_SRs");
}
public Proxy_DR_task ToProxy()
{
Proxy_DR_task result_ = new Proxy_DR_task();
result_.uuid = uuid ?? "";
result_.introduced_SRs = introduced_SRs == null ? new string[] {} : Helper.RefListToStringArray(introduced_SRs);
return result_;
}
public bool DeepEquals(DR_task other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._introduced_SRs, other._introduced_SRs);
}
public override string SaveChanges(Session session, string opaqueRef, DR_task server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given DR_task.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_dr_task">The opaque_ref of the given dr_task</param>
public static DR_task get_record(Session session, string _dr_task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_record(session.opaque_ref, _dr_task);
else
return new DR_task(session.XmlRpcProxy.dr_task_get_record(session.opaque_ref, _dr_task ?? "").parse());
}
/// <summary>
/// Get a reference to the DR_task instance with the specified UUID.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<DR_task> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<DR_task>.Create(session.XmlRpcProxy.dr_task_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given DR_task.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_dr_task">The opaque_ref of the given dr_task</param>
public static string get_uuid(Session session, string _dr_task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_uuid(session.opaque_ref, _dr_task);
else
return session.XmlRpcProxy.dr_task_get_uuid(session.opaque_ref, _dr_task ?? "").parse();
}
/// <summary>
/// Get the introduced_SRs field of the given DR_task.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_dr_task">The opaque_ref of the given dr_task</param>
public static List<XenRef<SR>> get_introduced_SRs(Session session, string _dr_task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_introduced_srs(session.opaque_ref, _dr_task);
else
return XenRef<SR>.Create(session.XmlRpcProxy.dr_task_get_introduced_srs(session.opaque_ref, _dr_task ?? "").parse());
}
/// <summary>
/// Create a disaster recovery task which will query the supplied list of devices
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_type">The SR driver type of the SRs to introduce</param>
/// <param name="_device_config">The device configuration of the SRs to introduce</param>
/// <param name="_whitelist">The devices to use for disaster recovery</param>
public static XenRef<DR_task> create(Session session, string _type, Dictionary<string, string> _device_config, string[] _whitelist)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_create(session.opaque_ref, _type, _device_config, _whitelist);
else
return XenRef<DR_task>.Create(session.XmlRpcProxy.dr_task_create(session.opaque_ref, _type ?? "", Maps.convert_to_proxy_string_string(_device_config), _whitelist).parse());
}
/// <summary>
/// Create a disaster recovery task which will query the supplied list of devices
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_type">The SR driver type of the SRs to introduce</param>
/// <param name="_device_config">The device configuration of the SRs to introduce</param>
/// <param name="_whitelist">The devices to use for disaster recovery</param>
public static XenRef<Task> async_create(Session session, string _type, Dictionary<string, string> _device_config, string[] _whitelist)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_dr_task_create(session.opaque_ref, _type, _device_config, _whitelist);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_dr_task_create(session.opaque_ref, _type ?? "", Maps.convert_to_proxy_string_string(_device_config), _whitelist).parse());
}
/// <summary>
/// Destroy the disaster recovery task, detaching and forgetting any SRs introduced which are no longer required
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_dr_task">The opaque_ref of the given dr_task</param>
public static void destroy(Session session, string _dr_task)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.dr_task_destroy(session.opaque_ref, _dr_task);
else
session.XmlRpcProxy.dr_task_destroy(session.opaque_ref, _dr_task ?? "").parse();
}
/// <summary>
/// Destroy the disaster recovery task, detaching and forgetting any SRs introduced which are no longer required
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_dr_task">The opaque_ref of the given dr_task</param>
public static XenRef<Task> async_destroy(Session session, string _dr_task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_dr_task_destroy(session.opaque_ref, _dr_task);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_dr_task_destroy(session.opaque_ref, _dr_task ?? "").parse());
}
/// <summary>
/// Return a list of all the DR_tasks known to the system.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<DR_task>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_all(session.opaque_ref);
else
return XenRef<DR_task>.Create(session.XmlRpcProxy.dr_task_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the DR_task Records at once, in a single XML RPC call
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<DR_task>, DR_task> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_all_records(session.opaque_ref);
else
return XenRef<DR_task>.Create<Proxy_DR_task>(session.XmlRpcProxy.dr_task_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// All SRs introduced by this appliance
/// </summary>
[JsonConverter(typeof(XenRefListConverter<SR>))]
public virtual List<XenRef<SR>> introduced_SRs
{
get { return _introduced_SRs; }
set
{
if (!Helper.AreEqual(value, _introduced_SRs))
{
_introduced_SRs = value;
NotifyPropertyChanged("introduced_SRs");
}
}
}
private List<XenRef<SR>> _introduced_SRs = new List<XenRef<SR>>() {};
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using SphinxDemo.Areas.HelpPage.ModelDescriptions;
using SphinxDemo.Areas.HelpPage.Models;
namespace SphinxDemo.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using iSukces.Code.Ammy;
using Xunit;
using Xunit.Abstractions;
namespace iSukces.Code.Tests.Ammy
{
public class CodeEmbedderTests
{
private readonly ITestOutputHelper _testOutputHelper;
public CodeEmbedderTests(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
public static IEnumerable<object[]> DataFor_T01_Should_find_marker()
{
var result = new List<object[]>();
void Add(string d)
{
result.Add(new object[] {d});
}
void AddSerie(string d)
{
Add(d);
var befores = new[] {"\r\n", "\n", "line1\nline2\r\n"};
var afters = new[] {"\r\n", "\n", "\r\nline1\nline2\r\n"};
foreach (var before in befores)
foreach (var after in afters)
Add(before + d + after);
}
IEnumerable<string> Texts()
{
yield return "Bla";
yield return " Bla";
yield return " Bla \t";
}
foreach (var text in Texts())
{
var core = CodeEmbeder.Limiter1 + text + CodeEmbeder.Limiter2;
AddSerie("// " + core);
AddSerie("// " + core);
AddSerie("// \t " + core);
AddSerie("// \t " + core + " other");
}
return result;
}
[Theory]
[MemberData(nameof(DataFor_T01_Should_find_marker))]
public void T01_Should_find_marker(string text)
{
var a = CodeEmbeder.Limiter.Match(text);
Assert.True(a.Success);
Assert.Equal("Bla", a.Groups[1].Value.TrimEnd('=').Trim());
}
[Fact]
public void T02_Should_embed_into_empty()
{
var result = CodeEmbeder.Embed(null, null);
Assert.Equal(string.Empty, result);
}
[Fact]
public void T03_Should_embed_into_empty()
{
// #############################
var exp1 = @"// -----===== autocode begin =====-----
Some code 1
Some code 2
// -----===== autocode end =====-----
";
var result = CodeEmbeder.Embed(null, "Some code 1\r\nSome code 2");
WriteExpected("exp1", result);
Assert.Equal(exp1, result);
// #############################
var exp2 = @"// -----===== autocode begin =====-----
Some code 3
Some code 4
// -----===== autocode end =====-----
";
result = CodeEmbeder.Embed(result, "Some code 3\r\nSome code 4");
WriteExpected("exp2", result);
Assert.Equal(exp2, result);
// #############################
var exp3 = string.Empty;
result = CodeEmbeder.Embed(result, null);
WriteExpected("exp3", result);
Assert.Equal(exp3, result);
}
[Fact]
public void T04_Should_embed_at_beginning()
{
const string sourceText = @"Line 1
Line2
Line3
";
// #############################
var exp1 = @"// -----===== autocode begin =====-----
Some code 1
Some code 2
// -----===== autocode end =====-----
Line 1
Line2
Line3
";
var result = CodeEmbeder.Embed(sourceText, "Some code 1\r\nSome code 2");
WriteExpected("exp1", result);
Assert.Equal(exp1, result);
// #############################
var exp2 = @"// -----===== autocode begin =====-----
Some code 3
Some code 4
// -----===== autocode end =====-----
Line 1
Line2
Line3
";
result = CodeEmbeder.Embed(result, "Some code 3\r\nSome code 4");
WriteExpected("exp2", result);
Assert.Equal(exp2, result);
// #############################
var exp3 = @"Line 1
Line2
Line3
";
result = CodeEmbeder.Embed(result, null);
WriteExpected("exp3", result);
Assert.Equal(exp3, result);
}
void WriteExpected(string name, string code)
{
_testOutputHelper.WriteLine("var " + name + " = " + code.CsVerbatimEncode() + ";");
}
[Fact]
public void T05_Should_embed_in_the_middle()
{
const string sourceText = @"Line 1
Line2
Line3
// -----========= autocode begin =====----- other text
// -----===== autocode END =========-------- other text
Line 4
";
var result = CodeEmbeder.Embed(sourceText, "Some code 1\r\nSome code 2");
var exp1 = @"Line 1
Line2
Line3
// -----===== autocode begin =====-----
Some code 1
Some code 2
// -----===== autocode end =====-----
Line 4
";
WriteExpected("exp1", result);
Assert.Equal(exp1, result);
result = CodeEmbeder.Embed(result, "Some code 3\r\nSome code 4");
var exp2 = @"Line 1
Line2
Line3
// -----===== autocode begin =====-----
Some code 3
Some code 4
// -----===== autocode end =====-----
Line 4
";
WriteExpected("exp2", result);
Assert.Equal(exp2, result);
result = CodeEmbeder.Embed(result, null);
var exp3 = @"Line 1
Line2
Line3
// -----===== autocode begin =====-----
// -----===== autocode end =====-----
Line 4
";
WriteExpected("exp3", result);
Assert.Equal(exp3, result);
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using System.Text;
using GTANetworkServer;
using GTANetworkShared;
using System.Threading;
public class DDGamemode : Script
{
public DDGamemode()
{
AvailableRaces = new List<Race>();
Opponents = new List<Opponent>();
Objects = new List<NetHandle>();
LoadRaces();
API.consoleOutput("Destruction Derby gamemode started! Loaded " + AvailableRaces.Count + " races.");
StartVote();
API.onUpdate += onUpdate;
API.onPlayerDisconnected += onDisconnect;
API.onChatCommand += onChatCommand;
API.onPlayerFinishedDownload += onPlayerConnect;
API.onPlayerRespawn += onPlayerRespawn;
}
public bool IsRaceOngoing { get; set; }
public List<Opponent> Opponents { get; set; }
public Race CurrentRace { get; set; }
public List<Race> AvailableRaces { get; set; }
public List<Vector3> CurrentRaceCheckpoints { get; set; }
public Dictionary<long, int> RememberedBlips { get; set; }
public DateTime RaceStart { get; set; }
public List<NetHandle> Objects { get; set; }
public List<Thread> ActiveThreads { get; set; }
public int RaceStartCountdown { get; set; }
public DateTime RaceTimer { get; set; }
// Voting
public int TimeLeft { get; set; }
public int VoteEnd { get; set; }
public DateTime LastSecond { get; set; }
public DateTime VoteStart { get; set; }
public List<Client> Voters { get; set; }
public Dictionary<int, int> Votes { get; set; }
public Dictionary<int, Race> AvailableChoices { get; set; }
public bool IsVoteActive()
{
return DateTime.Now.Subtract(VoteStart).TotalSeconds < 60;
}
public void onPlayerRespawn(Client player)
{
if (IsRaceStarting)
{
SetUpPlayerForRace(player, CurrentRace, false, 0);
}
else if (IsRaceOngoing)
{
API.setPlayerToSpectator(player);
Opponent curOp = Opponents.FirstOrDefault(op => op.Client == player);
if (curOp == null) return;
curOp.IsAlive = false;
}
}
public void onUpdate(object sender, EventArgs e)
{
if (DateTime.Now.Subtract(LastSecond).TotalMilliseconds > 1000)
{
LastSecond = DateTime.Now;
if (TimeLeft > 0)
{
TimeLeft--;
if (TimeLeft == 0)
{
if (!IsVoteActive())
StartVote();
}
else if (TimeLeft == 30)
{
API.sendChatMessageToAll("Vote for next map will start in 30 seconds!");
}
else if (TimeLeft == 59)
{
API.sendChatMessageToAll("Vote for next map will start in 60 seconds!");
}
}
if (RaceStartCountdown > 0)
{
RaceStartCountdown--;
if (RaceStartCountdown == 3)
{
API.triggerClientEventForAll("startRaceCountdown");
}
else if (RaceStartCountdown == 0)
{
IsRaceOngoing = true;
lock (Opponents)
foreach (var opponent in Opponents)
{
API.setEntityPositionFrozen(opponent.Client, opponent.Vehicle, false);
opponent.HasStarted = true;
}
RaceTimer = DateTime.Now;
}
}
if (VoteEnd > 0)
{
VoteEnd--;
if (VoteEnd == 0)
{
EndRace();
var raceWon = AvailableChoices[Votes.OrderByDescending(pair => pair.Value).ToList()[0].Key];
API.sendChatMessageToAll("Race ~b~" + raceWon.name + "~w~ has won the vote!");
API.sleep(1000);
StartRace(raceWon);
}
}
}
if (!IsRaceOngoing) return;
lock (Opponents)
{
var count = 0;
foreach(var playa in Opponents)
{
if (playa.Client.Position.Z <= 0 || playa.Client.Position.Z <= CurrentRace.Checkpoints[0].Z)
{
API.setPlayerHealth(playa.Client, -1);
playa.IsAlive = false;
}
if (playa.IsAlive) count++;
}
if (count <= 1)
{
StartVote();
var winner = Opponents.FirstOrDefault(op => op.IsAlive);
if (winner != null)
{
API.sendChatMessageToAll("The winner is ~b~" + winner.Client.name + "~w~!");
}
else API.sendChatMessageToAll("There are no winners!");
IsRaceOngoing = false;
}
}
}
public void onDisconnect(Client player, string reason)
{
Opponent curOp = Opponents.FirstOrDefault(op => op.Client == player);
if (curOp == null) return;
API.deleteEntity(curOp.Vehicle);
lock (Opponents) Opponents.Remove(curOp);
}
public void onChatCommand(Client sender, string message)
{
if (message == "/votemap" && !IsVoteActive() && (!IsRaceStarting || DateTime.UtcNow.Subtract(RaceStart).TotalSeconds > 60))
{
StartVote();
return;
}
else if (message.StartsWith("/vote"))
{
if (DateTime.Now.Subtract(VoteStart).TotalSeconds > 60)
{
API.sendChatMessageToPlayer(sender, "No current vote is in progress.");
return;
}
var args = message.Split();
if (args.Length <= 1)
{
API.sendChatMessageToPlayer(sender, "USAGE", "/vote [id]");
return;
}
if (Voters.Contains(sender))
{
API.sendChatMessageToPlayer(sender, "ERROR", "You have already voted!");
return;
}
int choice;
if (!int.TryParse(args[1], out choice) || choice <= 0 || choice > AvailableChoices.Count)
{
API.sendChatMessageToPlayer(sender, "USAGE", "/vote [id]");
return;
}
Votes[choice]++;
API.sendChatMessageToPlayer(sender, "You have voted for " + AvailableChoices[choice].name);
Voters.Add(sender);
return;
}
}
public void onPlayerConnect(Client player)
{
if (IsRaceStarting)
{
SetUpPlayerForRace(player, CurrentRace, true, 0);
}
else if (IsRaceOngoing)
{
API.setPlayerToSpectator(player);
}
if (DateTime.Now.Subtract(VoteStart).TotalSeconds < 60)
{
object[] argumentList = new object[11];
argumentList[0] = AvailableChoices.Count;
for (var i = 0; i < AvailableChoices.Count; i++)
{
argumentList[i+1] = AvailableChoices.ElementAt(i).Value.name;
}
API.triggerClientEvent(player, "race_startVotemap", argumentList);
}
}
private int LoadRaces()
{
int counter = 0;
if (!Directory.Exists("dd-races")) return 0;
foreach (string path in Directory.GetFiles("dd-races", "*.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(Race));
StreamReader file = new StreamReader(path);
var raceout = (Race)serializer.Deserialize(file);
file.Close();
AvailableRaces.Add(raceout);
counter++;
}
return counter;
}
private void StartRace(Race race)
{
race = new Race(race);
CurrentRace = race;
Opponents.ForEach(op =>
{
op.HasFinished = false;
op.CheckpointsPassed = 0;
if (!op.Vehicle.IsNull)
{
API.deleteEntity(op.Vehicle);
}
});
foreach (var ent in Objects)
{
API.deleteEntity(ent);
}
Objects.Clear();
foreach (var prop in race.DecorativeProps)
{
Objects.Add(API.createObject(prop.Hash, prop.Position, prop.Rotation));
}
var clients = API.getAllPlayers();
for (int i = 0; i < clients.Count; i++)
{
SetUpPlayerForRace(clients[i], CurrentRace, true, i);
}
CurrentRaceCheckpoints = race.Checkpoints.ToList();
RaceStart = DateTime.UtcNow;
API.consoleOutput("RACE: Starting race " + race.name);
RaceStartCountdown = 13;
}
private void EndRace()
{
IsRaceStarting = false;
IsRaceOngoing = false;
CurrentRace = null;
foreach (var opponent in Opponents)
{
opponent.IsAlive = false;
}
API.triggerClientEventForAll("resetRace");
}
private Random randGen = new Random();
private void SetUpPlayerForRace(Client client, Race race, bool freeze, int spawnpoint)
{
if (race == null) return;
var selectedModel = unchecked((int)((uint)race.AvailableVehicles[randGen.Next(race.AvailableVehicles.Length)]));
var position = race.SpawnPoints[spawnpoint % race.SpawnPoints.Length].Position;
var heading = race.SpawnPoints[spawnpoint % race.SpawnPoints.Length].Heading;
API.setEntityPosition(client.handle, position);
var playerVehicle = API.createVehicle(selectedModel, position, new Vector3(0, 0, heading), 0, 0);
Thread.Sleep(500);
API.setPlayerIntoVehicle(client, playerVehicle, -1);
if (freeze)
API.setEntityPositionFrozen(client, playerVehicle, true);
Opponent inOp = Opponents.FirstOrDefault(op => op.Client == client);
lock (Opponents)
{
if (inOp != null)
{
inOp.Vehicle = playerVehicle;
inOp.IsAlive = true;
}
else
{
Opponents.Add(new Opponent(client) { Vehicle = playerVehicle, IsAlive = true });
}
}
}
public void StartVote()
{
var pickedRaces = new List<Race>();
var racePool = new List<Race>(AvailableRaces);
var rand = new Random();
for (int i = 0; i < Math.Min(9, AvailableRaces.Count); i++)
{
var pick = rand.Next(racePool.Count);
pickedRaces.Add(racePool[pick]);
racePool.RemoveAt(pick);
}
Votes = new Dictionary<int, int>();
Voters = new List<Client>();
AvailableChoices = new Dictionary<int, Race>();
var counter = 1;
foreach (var race in pickedRaces)
{
Votes.Add(counter, 0);
AvailableChoices.Add(counter, race);
counter++;
}
object[] argumentList = new object[11];
argumentList[0] = AvailableChoices.Count;
for (var i = 0; i < AvailableChoices.Count; i++)
{
argumentList[i+1] = AvailableChoices.ElementAt(i).Value.name;
}
API.triggerClientEventForAll("race_startVotemap", argumentList);
VoteStart = DateTime.Now;
VoteEnd = 60;
}
}
public static class RangeExtension
{
public static bool IsInRangeOf(this Vector3 center, Vector3 dest, float radius)
{
return center.Subtract(dest).Length() < radius;
}
public static Vector3 Subtract(this Vector3 left, Vector3 right)
{
if (left == null || right == null)
{
return new Vector3(100, 100, 100);
}
return new Vector3()
{
X = left.X - right.X,
Y = left.Y - right.Y,
Z = left.Z - right.Z,
};
}
public static float Length(this Vector3 vect)
{
return (float)Math.Sqrt((vect.X * vect.X) + (vect.Y * vect.Y) + (vect.Z * vect.Z));
}
public static Vector3 Normalize(this Vector3 vect)
{
float length = vect.Length();
if (length == 0) return vect;
float num = 1 / length;
return new Vector3()
{
X = vect.X * num,
Y = vect.Y * num,
Z = vect.Z * num,
};
}
}
public class Race
{
public Vector3[] Checkpoints;
public SpawnPoint[] SpawnPoints;
public VehicleHash[] AvailableVehicles;
public bool LapsAvailable = true;
public Vector3 Trigger;
public SavedProp[] DecorativeProps;
public string Name;
public string Description;
public Race() { }
public Race(Race copyFrom)
{
Checkpoints = copyFrom.Checkpoints;
SpawnPoints = copyFrom.SpawnPoints;
AvailableVehicles = copyFrom.AvailableVehicles;
LapsAvailable = copyFrom.LapsAvailable;
Trigger = copyFrom.Trigger;
DecorativeProps = copyFrom.DecorativeProps;
Name = copyFrom.name;
Description = copyFrom.Description;
}
}
public class SpawnPoint
{
public Vector3 Position { get; set; }
public float Heading { get; set; }
}
public class SavedProp
{
public Vector3 Position { get; set; }
public Vector3 Rotation { get; set; }
public int Hash { get; set; }
public bool Dynamic { get; set; }
}
public class Opponent
{
public Opponent(Client c)
{
Client = c;
}
public bool IsAlive { get; set; }
public Client Client { get; set; }
public NetHandle Vehicle { get; set; }
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Client
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Configuration;
using NUnit.Framework;
/// <summary>
/// Tests client connection: port ranges, version checks, etc.
/// </summary>
public class ClientConnectionTest
{
/// <summary>
/// Fixture tear down.
/// </summary>
[TearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Tests that missing server yields connection refused error.
/// </summary>
[Test]
public void TestNoServerConnectionRefused()
{
var ex = Assert.Throws<AggregateException>(() => StartClient());
var socketEx = ex.InnerExceptions.OfType<SocketException>().First();
Assert.AreEqual(SocketError.ConnectionRefused, socketEx.SocketErrorCode);
}
/// <summary>
/// Tests that multiple clients can connect to one server.
/// </summary>
[Test]
public void TestMultipleClients()
{
using (Ignition.Start(TestUtils.GetTestConfiguration()))
{
var client1 = StartClient();
var client2 = StartClient();
var client3 = StartClient();
client1.Dispose();
client2.Dispose();
client3.Dispose();
}
}
/// <summary>
/// Tests custom connector and client configuration.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestCustomConfig()
{
var servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
ClientConnectorConfiguration = new ClientConnectorConfiguration
{
Host = "localhost",
Port = 2000,
PortRange = 1,
SocketSendBufferSize = 100,
SocketReceiveBufferSize = 50
}
};
var clientCfg = new IgniteClientConfiguration
{
Host = "localhost",
Port = 2000
};
using (Ignition.Start(servCfg))
using (var client = Ignition.StartClient(clientCfg))
{
Assert.AreNotEqual(clientCfg, client.GetConfiguration());
Assert.AreNotEqual(client.GetConfiguration(), client.GetConfiguration());
Assert.AreEqual(clientCfg.ToXml(), client.GetConfiguration().ToXml());
}
}
/// <summary>
/// Tests that default configuration throws.
/// </summary>
[Test]
public void TestDefaultConfigThrows()
{
Assert.Throws<ArgumentNullException>(() => Ignition.StartClient(new IgniteClientConfiguration()));
}
/// <summary>
/// Tests the incorrect protocol version error.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestIncorrectProtocolVersionError()
{
using (Ignition.Start(TestUtils.GetTestConfiguration()))
{
// ReSharper disable once ObjectCreationAsStatement
var ex = Assert.Throws<IgniteClientException>(() =>
new Impl.Client.ClientSocket(GetClientConfiguration(),
new Impl.Client.ClientProtocolVersion(-1, -1, -1)));
Assert.AreEqual(ClientStatusCode.Fail, ex.StatusCode);
Assert.AreEqual("Client handshake failed: 'Unsupported version.'. " +
"Client version: -1.-1.-1. Server version: 1.0.0", ex.Message);
}
}
/// <summary>
/// Tests that connector can be disabled.
/// </summary>
[Test]
public void TestDisabledConnector()
{
var servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
ClientConnectorConfigurationEnabled = false
};
var clientCfg = new IgniteClientConfiguration
{
Host = "localhost"
};
using (Ignition.Start(servCfg))
{
var ex = Assert.Throws<AggregateException>(() => Ignition.StartClient(clientCfg));
Assert.AreEqual("Failed to establish Ignite thin client connection, " +
"examine inner exceptions for details.", ex.Message.Substring(0, 88));
}
// Disable only thin client.
servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
ClientConnectorConfiguration = new ClientConnectorConfiguration
{
ThinClientEnabled = false
}
};
using (Ignition.Start(servCfg))
{
var ex = Assert.Throws<IgniteClientException>(() => Ignition.StartClient(clientCfg));
Assert.AreEqual("Client handshake failed: 'Thin client connection is not allowed, " +
"see ClientConnectorConfiguration.thinClientEnabled.'.",
ex.Message.Substring(0, 118));
}
}
/// <summary>
/// Tests that we get a proper exception when server disconnects (node shutdown, network issues, etc).
/// </summary>
[Test]
public void TestServerConnectionAborted()
{
var evt = new ManualResetEventSlim();
var ignite = Ignition.Start(TestUtils.GetTestConfiguration());
var putGetTask = Task.Factory.StartNew(() =>
{
using (var client = StartClient())
{
var cache = client.GetOrCreateCache<int, int>("foo");
evt.Set();
for (var i = 0; i < 100000; i++)
{
cache[i] = i;
Assert.AreEqual(i, cache.GetAsync(i).Result);
}
}
});
evt.Wait();
ignite.Dispose();
var ex = Assert.Throws<AggregateException>(() => putGetTask.Wait());
var baseEx = ex.GetBaseException();
var socketEx = baseEx as SocketException;
if (socketEx != null)
{
Assert.AreEqual(SocketError.ConnectionAborted, socketEx.SocketErrorCode);
}
else
{
Assert.Fail("Unexpected exception: " + ex);
}
}
/// <summary>
/// Tests the operation timeout.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestOperationTimeout()
{
var data = Enumerable.Range(1, 500000).ToDictionary(x => x, x => x.ToString());
Ignition.Start(TestUtils.GetTestConfiguration());
var cfg = GetClientConfiguration();
cfg.SocketTimeout = TimeSpan.FromMilliseconds(500);
var client = Ignition.StartClient(cfg);
var cache = client.CreateCache<int, string>("s");
Assert.AreEqual(cfg.SocketTimeout, client.GetConfiguration().SocketTimeout);
// Async.
var task = cache.PutAllAsync(data);
Assert.IsFalse(task.IsCompleted);
var ex = Assert.Catch(() => task.Wait());
Assert.AreEqual(SocketError.TimedOut, GetSocketException(ex).SocketErrorCode);
// Sync (reconnect for clean state).
Ignition.StopAll(true);
Ignition.Start(TestUtils.GetTestConfiguration());
client = Ignition.StartClient(cfg);
cache = client.CreateCache<int, string>("s");
ex = Assert.Catch(() => cache.PutAll(data));
Assert.AreEqual(SocketError.TimedOut, GetSocketException(ex).SocketErrorCode);
}
/// <summary>
/// Tests the client dispose while operations are in progress.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestClientDisposeWhileOperationsAreInProgress()
{
Ignition.Start(TestUtils.GetTestConfiguration());
var ops = new List<Task>();
using (var client = StartClient())
{
var cache = client.GetOrCreateCache<int, int>("foo");
for (var i = 0; i < 100000; i++)
{
ops.Add(cache.PutAsync(i, i));
}
ops.First().Wait();
}
var completed = ops.Count(x => x.Status == TaskStatus.RanToCompletion);
Assert.Greater(completed, 0, "Some tasks should have completed.");
var failed = ops.Where(x => x.Status == TaskStatus.Faulted).ToArray();
Assert.IsTrue(failed.Any(), "Some tasks should have failed.");
foreach (var task in failed)
{
var ex = task.Exception;
Assert.IsNotNull(ex);
var baseEx = ex.GetBaseException();
Assert.IsNotNull((object) (baseEx as SocketException) ?? baseEx as ObjectDisposedException,
ex.ToString());
}
}
/// <summary>
/// Tests the <see cref="ClientConnectorConfiguration.IdleTimeout"/> property.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestIdleTimeout()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
ClientConnectorConfiguration = new ClientConnectorConfiguration
{
IdleTimeout = TimeSpan.FromMilliseconds(100)
}
};
var ignite = Ignition.Start(cfg);
Assert.AreEqual(100, ignite.GetConfiguration().ClientConnectorConfiguration.IdleTimeout.TotalMilliseconds);
using (var client = StartClient())
{
var cache = client.GetOrCreateCache<int, int>("foo");
cache[1] = 1;
Assert.AreEqual(1, cache[1]);
Thread.Sleep(90);
Assert.AreEqual(1, cache[1]);
// Idle check frequency is 2 seconds.
Thread.Sleep(4000);
var ex = Assert.Catch(() => cache.Get(1));
Assert.AreEqual(SocketError.ConnectionAborted, GetSocketException(ex).SocketErrorCode);
}
}
/// <summary>
/// Tests the protocol mismatch behavior: attempt to connect to an HTTP endpoint.
/// </summary>
[Test]
public void TestProtocolMismatch()
{
using (Ignition.Start(TestUtils.GetTestConfiguration()))
{
// Connect to Ignite REST endpoint.
var cfg = new IgniteClientConfiguration {Host = "127.0.0.1", Port = 11211 };
var ex = Assert.Throws<SocketException>(() => Ignition.StartClient(cfg));
Assert.AreEqual(SocketError.ConnectionAborted, ex.SocketErrorCode);
}
}
/// <summary>
/// Starts the client.
/// </summary>
private static IIgniteClient StartClient()
{
return Ignition.StartClient(GetClientConfiguration());
}
/// <summary>
/// Gets the client configuration.
/// </summary>
private static IgniteClientConfiguration GetClientConfiguration()
{
return new IgniteClientConfiguration { Host = IPAddress.Loopback.ToString() };
}
/// <summary>
/// Finds SocketException in the hierarchy.
/// </summary>
private static SocketException GetSocketException(Exception ex)
{
Assert.IsNotNull(ex);
var origEx = ex;
while (ex != null)
{
var socketEx = ex as SocketException;
if (socketEx != null)
{
return socketEx;
}
ex = ex.InnerException;
}
throw new Exception("SocketException not found.", origEx);
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace DynamicCacheLayerManagerController
{
partial class CacheManagerDlg
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lblLayer = new System.Windows.Forms.Label();
this.cboLayerNames = new System.Windows.Forms.ComboBox();
this.btnOK = new System.Windows.Forms.Button();
this.btnApply = new System.Windows.Forms.Button();
this.btnDismiss = new System.Windows.Forms.Button();
this.groupDrawingProps = new System.Windows.Forms.GroupBox();
this.numDetaildThreshold = new System.Windows.Forms.NumericUpDown();
this.lblDetailsThreshold = new System.Windows.Forms.Label();
this.chkAlwaysDrawCoarsestLevel = new System.Windows.Forms.CheckBox();
this.lblUseDefaultTexture = new System.Windows.Forms.Label();
this.lblCacheFolderName = new System.Windows.Forms.Label();
this.lblFolderName = new System.Windows.Forms.Label();
this.btnFolderPath = new System.Windows.Forms.Button();
this.lblCacheFolderPath = new System.Windows.Forms.Label();
this.lblCachePathName = new System.Windows.Forms.Label();
this.btnRestoreDefaults = new System.Windows.Forms.Button();
this.numMaxCacheScale = new System.Windows.Forms.NumericUpDown();
this.lblMaxCacheScale = new System.Windows.Forms.Label();
this.chkStrictOnDemandMode = new System.Windows.Forms.CheckBox();
this.lblStrictOnDemandMode = new System.Windows.Forms.Label();
this.numProgressiveFetchingLevels = new System.Windows.Forms.NumericUpDown();
this.lblProgressiveFetchingLevels = new System.Windows.Forms.Label();
this.numProgressiveDrawingLevels = new System.Windows.Forms.NumericUpDown();
this.lblProgressiveDrawingLevels = new System.Windows.Forms.Label();
this.rdoJPEG = new System.Windows.Forms.RadioButton();
this.rdoPNG = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.groupDrawingProps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numDetaildThreshold)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numMaxCacheScale)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numProgressiveFetchingLevels)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numProgressiveDrawingLevels)).BeginInit();
this.SuspendLayout();
//
// lblLayer
//
this.lblLayer.AutoSize = true;
this.lblLayer.Location = new System.Drawing.Point(13, 13);
this.lblLayer.Name = "lblLayer";
this.lblLayer.Size = new System.Drawing.Size(69, 13);
this.lblLayer.TabIndex = 0;
this.lblLayer.Text = "Active Layer:";
//
// cboLayerNames
//
this.cboLayerNames.FormattingEnabled = true;
this.cboLayerNames.Location = new System.Drawing.Point(88, 10);
this.cboLayerNames.Name = "cboLayerNames";
this.cboLayerNames.Size = new System.Drawing.Size(327, 21);
this.cboLayerNames.TabIndex = 1;
this.cboLayerNames.SelectedIndexChanged += new System.EventHandler(this.cboLayerNames_SelectedIndexChanged);
//
// btnOK
//
this.btnOK.Location = new System.Drawing.Point(12, 632);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 23);
this.btnOK.TabIndex = 2;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnApply
//
this.btnApply.Location = new System.Drawing.Point(177, 632);
this.btnApply.Name = "btnApply";
this.btnApply.Size = new System.Drawing.Size(75, 23);
this.btnApply.TabIndex = 3;
this.btnApply.Text = "Apply";
this.btnApply.UseVisualStyleBackColor = true;
this.btnApply.Click += new System.EventHandler(this.btnApply_Click);
//
// btnDismiss
//
this.btnDismiss.Location = new System.Drawing.Point(340, 632);
this.btnDismiss.Name = "btnDismiss";
this.btnDismiss.Size = new System.Drawing.Size(75, 23);
this.btnDismiss.TabIndex = 4;
this.btnDismiss.Text = "Dismiss";
this.btnDismiss.UseVisualStyleBackColor = true;
this.btnDismiss.Click += new System.EventHandler(this.btnDismiss_Click);
//
// groupDrawingProps
//
this.groupDrawingProps.Controls.Add(this.numDetaildThreshold);
this.groupDrawingProps.Controls.Add(this.lblDetailsThreshold);
this.groupDrawingProps.Controls.Add(this.chkAlwaysDrawCoarsestLevel);
this.groupDrawingProps.Controls.Add(this.lblUseDefaultTexture);
this.groupDrawingProps.Controls.Add(this.lblCacheFolderName);
this.groupDrawingProps.Controls.Add(this.lblFolderName);
this.groupDrawingProps.Controls.Add(this.btnFolderPath);
this.groupDrawingProps.Controls.Add(this.lblCacheFolderPath);
this.groupDrawingProps.Controls.Add(this.lblCachePathName);
this.groupDrawingProps.Controls.Add(this.btnRestoreDefaults);
this.groupDrawingProps.Controls.Add(this.numMaxCacheScale);
this.groupDrawingProps.Controls.Add(this.lblMaxCacheScale);
this.groupDrawingProps.Controls.Add(this.chkStrictOnDemandMode);
this.groupDrawingProps.Controls.Add(this.lblStrictOnDemandMode);
this.groupDrawingProps.Controls.Add(this.numProgressiveFetchingLevels);
this.groupDrawingProps.Controls.Add(this.lblProgressiveFetchingLevels);
this.groupDrawingProps.Controls.Add(this.numProgressiveDrawingLevels);
this.groupDrawingProps.Controls.Add(this.lblProgressiveDrawingLevels);
this.groupDrawingProps.Controls.Add(this.rdoJPEG);
this.groupDrawingProps.Controls.Add(this.rdoPNG);
this.groupDrawingProps.Controls.Add(this.label1);
this.groupDrawingProps.Location = new System.Drawing.Point(12, 37);
this.groupDrawingProps.Name = "groupDrawingProps";
this.groupDrawingProps.Size = new System.Drawing.Size(403, 572);
this.groupDrawingProps.TabIndex = 5;
this.groupDrawingProps.TabStop = false;
this.groupDrawingProps.Text = "Cache drawing properties";
//
// numDetaildThreshold
//
this.numDetaildThreshold.DecimalPlaces = 2;
this.numDetaildThreshold.Increment = new decimal(new int[] {
1,
0,
0,
131072});
this.numDetaildThreshold.Location = new System.Drawing.Point(261, 342);
this.numDetaildThreshold.Maximum = new decimal(new int[] {
1,
0,
0,
0});
this.numDetaildThreshold.Name = "numDetaildThreshold";
this.numDetaildThreshold.Size = new System.Drawing.Size(136, 20);
this.numDetaildThreshold.TabIndex = 20;
//
// lblDetailsThreshold
//
this.lblDetailsThreshold.AutoSize = true;
this.lblDetailsThreshold.Location = new System.Drawing.Point(10, 349);
this.lblDetailsThreshold.Name = "lblDetailsThreshold";
this.lblDetailsThreshold.Size = new System.Drawing.Size(88, 13);
this.lblDetailsThreshold.TabIndex = 19;
this.lblDetailsThreshold.Text = "Details threshold:";
//
// chkAlwaysDrawCoarsestLevel
//
this.chkAlwaysDrawCoarsestLevel.AutoSize = true;
this.chkAlwaysDrawCoarsestLevel.Location = new System.Drawing.Point(260, 269);
this.chkAlwaysDrawCoarsestLevel.Name = "chkAlwaysDrawCoarsestLevel";
this.chkAlwaysDrawCoarsestLevel.Size = new System.Drawing.Size(15, 14);
this.chkAlwaysDrawCoarsestLevel.TabIndex = 18;
this.chkAlwaysDrawCoarsestLevel.UseVisualStyleBackColor = true;
//
// lblUseDefaultTexture
//
this.lblUseDefaultTexture.AutoSize = true;
this.lblUseDefaultTexture.Location = new System.Drawing.Point(10, 269);
this.lblUseDefaultTexture.Name = "lblUseDefaultTexture";
this.lblUseDefaultTexture.Size = new System.Drawing.Size(137, 13);
this.lblUseDefaultTexture.TabIndex = 17;
this.lblUseDefaultTexture.Text = "Always draw coarsest level:";
//
// lblCacheFolderName
//
this.lblCacheFolderName.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblCacheFolderName.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(177)));
this.lblCacheFolderName.Location = new System.Drawing.Point(10, 48);
this.lblCacheFolderName.Name = "lblCacheFolderName";
this.lblCacheFolderName.Size = new System.Drawing.Size(387, 20);
this.lblCacheFolderName.TabIndex = 16;
//
// lblFolderName
//
this.lblFolderName.AutoSize = true;
this.lblFolderName.Location = new System.Drawing.Point(10, 25);
this.lblFolderName.Name = "lblFolderName";
this.lblFolderName.Size = new System.Drawing.Size(70, 13);
this.lblFolderName.TabIndex = 15;
this.lblFolderName.Text = "Folder Name:";
//
// btnFolderPath
//
this.btnFolderPath.Location = new System.Drawing.Point(369, 112);
this.btnFolderPath.Name = "btnFolderPath";
this.btnFolderPath.Size = new System.Drawing.Size(28, 101);
this.btnFolderPath.TabIndex = 14;
this.btnFolderPath.Text = "...";
this.btnFolderPath.UseVisualStyleBackColor = true;
this.btnFolderPath.Click += new System.EventHandler(this.btnFolderPath_Click);
//
// lblCacheFolderPath
//
this.lblCacheFolderPath.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblCacheFolderPath.Location = new System.Drawing.Point(10, 112);
this.lblCacheFolderPath.Name = "lblCacheFolderPath";
this.lblCacheFolderPath.Size = new System.Drawing.Size(353, 101);
this.lblCacheFolderPath.TabIndex = 13;
this.lblCacheFolderPath.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblCachePathName
//
this.lblCachePathName.AutoSize = true;
this.lblCachePathName.Location = new System.Drawing.Point(7, 89);
this.lblCachePathName.Name = "lblCachePathName";
this.lblCachePathName.Size = new System.Drawing.Size(63, 13);
this.lblCachePathName.TabIndex = 12;
this.lblCachePathName.Text = "Folder path:";
//
// btnRestoreDefaults
//
this.btnRestoreDefaults.Location = new System.Drawing.Point(261, 531);
this.btnRestoreDefaults.Name = "btnRestoreDefaults";
this.btnRestoreDefaults.Size = new System.Drawing.Size(136, 23);
this.btnRestoreDefaults.TabIndex = 11;
this.btnRestoreDefaults.Text = "Restore Defaults";
this.btnRestoreDefaults.UseVisualStyleBackColor = true;
this.btnRestoreDefaults.Click += new System.EventHandler(this.btnRestoreDefaults_Click);
//
// numMaxCacheScale
//
this.numMaxCacheScale.Location = new System.Drawing.Point(261, 491);
this.numMaxCacheScale.Maximum = new decimal(new int[] {
100000000,
0,
0,
0});
this.numMaxCacheScale.Name = "numMaxCacheScale";
this.numMaxCacheScale.Size = new System.Drawing.Size(136, 20);
this.numMaxCacheScale.TabIndex = 10;
//
// lblMaxCacheScale
//
this.lblMaxCacheScale.AutoSize = true;
this.lblMaxCacheScale.Location = new System.Drawing.Point(10, 493);
this.lblMaxCacheScale.Name = "lblMaxCacheScale";
this.lblMaxCacheScale.Size = new System.Drawing.Size(115, 13);
this.lblMaxCacheScale.TabIndex = 9;
this.lblMaxCacheScale.Text = "Maximum cache scale:";
//
// chkStrictOnDemandMode
//
this.chkStrictOnDemandMode.AutoSize = true;
this.chkStrictOnDemandMode.Location = new System.Drawing.Point(261, 307);
this.chkStrictOnDemandMode.Name = "chkStrictOnDemandMode";
this.chkStrictOnDemandMode.Size = new System.Drawing.Size(15, 14);
this.chkStrictOnDemandMode.TabIndex = 8;
this.chkStrictOnDemandMode.UseVisualStyleBackColor = true;
//
// lblStrictOnDemandMode
//
this.lblStrictOnDemandMode.AutoSize = true;
this.lblStrictOnDemandMode.Location = new System.Drawing.Point(7, 307);
this.lblStrictOnDemandMode.Name = "lblStrictOnDemandMode";
this.lblStrictOnDemandMode.Size = new System.Drawing.Size(119, 13);
this.lblStrictOnDemandMode.TabIndex = 7;
this.lblStrictOnDemandMode.Text = "Strict on demand mode:";
//
// numProgressiveFetchingLevels
//
this.numProgressiveFetchingLevels.Location = new System.Drawing.Point(261, 441);
this.numProgressiveFetchingLevels.Maximum = new decimal(new int[] {
31,
0,
0,
0});
this.numProgressiveFetchingLevels.Name = "numProgressiveFetchingLevels";
this.numProgressiveFetchingLevels.Size = new System.Drawing.Size(136, 20);
this.numProgressiveFetchingLevels.TabIndex = 6;
//
// lblProgressiveFetchingLevels
//
this.lblProgressiveFetchingLevels.AutoSize = true;
this.lblProgressiveFetchingLevels.Location = new System.Drawing.Point(7, 441);
this.lblProgressiveFetchingLevels.Name = "lblProgressiveFetchingLevels";
this.lblProgressiveFetchingLevels.Size = new System.Drawing.Size(136, 13);
this.lblProgressiveFetchingLevels.TabIndex = 5;
this.lblProgressiveFetchingLevels.Text = "Progressive fetching levels:";
//
// numProgressiveDrawingLevels
//
this.numProgressiveDrawingLevels.Location = new System.Drawing.Point(261, 390);
this.numProgressiveDrawingLevels.Maximum = new decimal(new int[] {
31,
0,
0,
0});
this.numProgressiveDrawingLevels.Name = "numProgressiveDrawingLevels";
this.numProgressiveDrawingLevels.Size = new System.Drawing.Size(136, 20);
this.numProgressiveDrawingLevels.TabIndex = 4;
//
// lblProgressiveDrawingLevels
//
this.lblProgressiveDrawingLevels.AutoSize = true;
this.lblProgressiveDrawingLevels.Location = new System.Drawing.Point(7, 390);
this.lblProgressiveDrawingLevels.Name = "lblProgressiveDrawingLevels";
this.lblProgressiveDrawingLevels.Size = new System.Drawing.Size(135, 13);
this.lblProgressiveDrawingLevels.TabIndex = 3;
this.lblProgressiveDrawingLevels.Text = "Progressive drawing levels:";
//
// rdoJPEG
//
this.rdoJPEG.AutoSize = true;
this.rdoJPEG.Location = new System.Drawing.Point(345, 231);
this.rdoJPEG.Name = "rdoJPEG";
this.rdoJPEG.Size = new System.Drawing.Size(52, 17);
this.rdoJPEG.TabIndex = 2;
this.rdoJPEG.TabStop = true;
this.rdoJPEG.Text = "JPEG";
this.rdoJPEG.UseVisualStyleBackColor = true;
//
// rdoPNG
//
this.rdoPNG.AutoSize = true;
this.rdoPNG.Location = new System.Drawing.Point(261, 231);
this.rdoPNG.Name = "rdoPNG";
this.rdoPNG.Size = new System.Drawing.Size(48, 17);
this.rdoPNG.TabIndex = 1;
this.rdoPNG.TabStop = true;
this.rdoPNG.Text = "PNG";
this.rdoPNG.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(7, 231);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(42, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Format:";
//
// CacheManagerDlg
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(427, 667);
this.Controls.Add(this.groupDrawingProps);
this.Controls.Add(this.btnDismiss);
this.Controls.Add(this.btnApply);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.cboLayerNames);
this.Controls.Add(this.lblLayer);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "CacheManagerDlg";
this.ShowInTaskbar = false;
this.Text = "CacheManagerDlg";
this.TopMost = true;
this.Load += new System.EventHandler(this.CacheManagerDlg_Load);
this.groupDrawingProps.ResumeLayout(false);
this.groupDrawingProps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numDetaildThreshold)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numMaxCacheScale)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numProgressiveFetchingLevels)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numProgressiveDrawingLevels)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblLayer;
private System.Windows.Forms.ComboBox cboLayerNames;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnApply;
private System.Windows.Forms.Button btnDismiss;
private System.Windows.Forms.GroupBox groupDrawingProps;
private System.Windows.Forms.RadioButton rdoJPEG;
private System.Windows.Forms.RadioButton rdoPNG;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblProgressiveFetchingLevels;
private System.Windows.Forms.NumericUpDown numProgressiveDrawingLevels;
private System.Windows.Forms.Label lblProgressiveDrawingLevels;
private System.Windows.Forms.CheckBox chkStrictOnDemandMode;
private System.Windows.Forms.Label lblStrictOnDemandMode;
private System.Windows.Forms.NumericUpDown numProgressiveFetchingLevels;
private System.Windows.Forms.NumericUpDown numMaxCacheScale;
private System.Windows.Forms.Label lblMaxCacheScale;
private System.Windows.Forms.Button btnRestoreDefaults;
private System.Windows.Forms.Label lblCacheFolderPath;
private System.Windows.Forms.Label lblCachePathName;
private System.Windows.Forms.Button btnFolderPath;
private System.Windows.Forms.Label lblCacheFolderName;
private System.Windows.Forms.Label lblFolderName;
private System.Windows.Forms.CheckBox chkAlwaysDrawCoarsestLevel;
private System.Windows.Forms.Label lblUseDefaultTexture;
private System.Windows.Forms.Label lblDetailsThreshold;
private System.Windows.Forms.NumericUpDown numDetaildThreshold;
}
}
| |
/*! Achordeon - MIT License
Copyright (c) 2017 tiamatix / Wolf Robben
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
!*/
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Achordeon.Common.Extensions;
using Achordeon.Common.Helpers;
using Achordeon.Lib.SongOptions;
using Achordeon.Shell.Wpf.Helpers;
using Achordeon.Shell.Wpf.Helpers.FontViewModel;
using Achordeon.Shell.Wpf.Helpers.RecentFileList;
namespace Achordeon.Shell.Wpf.Contents
{
public class SettingsViewModel : ViewModelBase
{
private CoreViewModel m_Core;
private double m_ChordProFontSize;
private FontFamilyInfo m_ChordProFont;
private RecentFileList m_RecentFileList;
private WindowPosition m_MainWindowPosition;
private double m_ChordProEditorSplitPosition;
private LanguageInfo m_Language;
private bool m_UsePdfPreview;
private bool m_ShowLogger;
private bool m_AutoUpdates;
private SongOptionsViewModel m_GlobalSongOptions;
public ObservableCollection<LanguageInfo> SupportedLanguages { get; } = new ObservableCollection<LanguageInfo>();
public SettingsViewModel(CoreViewModel ACore)
{
Core = ACore;
RecentFileList = new RecentFileList();
MainWindowPosition = WindowPosition.Empty;
ChordProEditorSplitPosition = 0;
GlobalSongOptions = new SongOptionsViewModel(Core);
SetupSupportedLanguages();
Language = AchordeonConstants.DefaultLanguage;
ResetToUserDefault();
}
private void SetupSupportedLanguages()
{
SupportedLanguages.Add(AchordeonConstants.DefaultLanguage);
SupportedLanguages.Add(new LanguageInfo("de-DE", "Deutsch"));
}
public void ResetToUserDefault()
{
ChordProFont = Core.FontViewModel.GetFontInfo(FontViewModel.BUILDIN_SERIFE);
ChordProFontSize = 16;
UsePdfPreview = true;
ShowLogger = false;
AutoUpdates = true;
GlobalSongOptions.ResetToDefaults();
}
public CoreViewModel Core
{
get { return m_Core; }
set { SetProperty(ref m_Core, value, nameof(Core)); }
}
public SongOptionsViewModel GlobalSongOptions
{
get { return m_GlobalSongOptions; }
set { SetProperty(ref m_GlobalSongOptions, value, nameof(GlobalSongOptions)); }
}
public LanguageInfo Language
{
get { return m_Language; }
set { SetProperty(ref m_Language, value, nameof(Language)); }
}
public bool ShowLogger
{
get { return m_ShowLogger; }
set { SetProperty(ref m_ShowLogger, value, nameof(ShowLogger)); }
}
public bool AutoUpdates
{
get { return m_AutoUpdates; }
set { SetProperty(ref m_AutoUpdates, value, nameof(AutoUpdates)); }
}
public WindowPosition MainWindowPosition
{
get { return m_MainWindowPosition; }
set { SetProperty(ref m_MainWindowPosition, value, nameof(MainWindowPosition)); }
}
public double ChordProFontSize
{
get { return m_ChordProFontSize; }
set { SetProperty(ref m_ChordProFontSize, value, nameof(ChordProFontSize)); }
}
public double ChordProEditorSplitPosition
{
get { return m_ChordProEditorSplitPosition; }
set { SetProperty(ref m_ChordProEditorSplitPosition, value, nameof(ChordProEditorSplitPosition)); }
}
public bool UsePdfPreview
{
get { return m_UsePdfPreview; }
set { SetProperty(ref m_UsePdfPreview, value, nameof(UsePdfPreview)); }
}
public FontFamilyInfo ChordProFont
{
get { return m_ChordProFont; }
set { SetProperty(ref m_ChordProFont, value, nameof(ChordProFont)); }
}
public RecentFileList RecentFileList
{
get { return m_RecentFileList; }
set { SetProperty(ref m_RecentFileList, value, nameof(RecentFileList)); }
}
public void SaveSettings()
{
if (!Directory.Exists(AchordeonConstants.ApplicationDataDirectory))
Directory.CreateDirectory(AchordeonConstants.ApplicationDataDirectory);
var Xml = XmlFile.CreateEmpty(AchordeonConstants.SettingsFileRootNodeName);
var ChordProEditorNode = Xml.Add("ChordProEditor");
ChordProEditorNode.Set("ChordProFontSize", ChordProFontSize);
ChordProEditorNode.Set("ChordProFontName", ChordProFont.Source);
ChordProEditorNode.Set("ChordProEditorSplitPosition", ChordProEditorSplitPosition);
ChordProEditorNode.Set("UsePdfPreview", UsePdfPreview);
RecentFileList.SaveToXml(Xml);
if (MainWindowPosition != WindowPosition.Empty)
{
var MainWindowPositionNode = Xml.Add("MainWindowPosition");
MainWindowPosition.SaveToXml(MainWindowPositionNode);
}
var LoggerNode = Xml.Add("Logger");
LoggerNode.Set("ShowLogger", ShowLogger);
var GlobalSongOptionsNode = Xml.Add("GlobalSongOptions");
new SongOptionsConverter(DefaultSongOptions.Default).SaveToXml(GlobalSongOptions, GlobalSongOptionsNode);
var LanguageNode = Xml.Add("Language");
LanguageNode.Set("SelectedLanguageCode", Language.LanguageCode);
var AutoUpdatesNode = Xml.Add("AutoUpdates");
AutoUpdatesNode.Set("EnableAutomaticUpdate", AutoUpdates);
Xml.Save(AchordeonConstants.SettingsFileFullPath, true);
}
public void LoadSettings()
{
if (!File.Exists(AchordeonConstants.SettingsFileFullPath))
return;
var Xml = XmlFile.CreateFromFile(AchordeonConstants.SettingsFileFullPath);
if (!Xml.Root.Name.LocalName.CiEquals(AchordeonConstants.SettingsFileRootNodeName))
return;
var ChordProEditorNode = Xml.SelectSingle("ChordProEditor");
if (ChordProEditorNode != null)
{
ChordProFontSize = ChordProEditorNode.GetF("ChordProFontSize", ChordProFontSize);
ChordProFont = Core.FontViewModel.GetFontInfo(ChordProEditorNode.Get("ChordProFontName", ChordProFont.Source));
ChordProEditorSplitPosition = ChordProEditorNode.GetF("ChordProEditorSplitPosition", ChordProEditorSplitPosition);
UsePdfPreview = ChordProEditorNode.GetB("UsePdfPreview", UsePdfPreview);
}
RecentFileList.LoadFromXml(Xml);
var MainWindowPositionNode = Xml.SelectSingle("MainWindowPosition");
if (MainWindowPositionNode != null)
MainWindowPosition = new WindowPosition(MainWindowPositionNode);
else
MainWindowPosition = WindowPosition.Empty;
var LoggerNode = Xml.SelectSingle("Logger");
if (LoggerNode != null)
{
ShowLogger = LoggerNode.GetB("ShowLogger", ShowLogger);
}
var GlobalSongOptionsNode = Xml.SelectSingle("GlobalSongOptions");
if (GlobalSongOptionsNode != null)
{
new SongOptionsConverter(DefaultSongOptions.Default).LoadFromXml(GlobalSongOptions, GlobalSongOptionsNode);
}
var LanguageNode = Xml.SelectSingle("Language");
if (LanguageNode != null)
{
var LanguageCode = LanguageNode.Get("SelectedLanguageCode", Language.LanguageCode);
Language = SupportedLanguages.FirstOrDefault(a => a.LanguageCode.CiEquals(LanguageCode)) ?? AchordeonConstants.DefaultLanguage;
}
var AutoUpdatesNode = Xml.SelectSingle("AutoUpdates");
if (AutoUpdatesNode != null)
{
AutoUpdates = AutoUpdatesNode.GetB("EnableAutomaticUpdate", AutoUpdates);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace System.Drawing
{
/// <summary>
/// Translates colors to and from GDI+ <see cref='Color'/> objects.
/// </summary>
public static class ColorTranslator
{
// COLORREF is 0x00BBGGRR
internal const int COLORREF_RedShift = 0;
internal const int COLORREF_GreenShift = 8;
internal const int COLORREF_BlueShift = 16;
private const int OleSystemColorFlag = unchecked((int)0x80000000);
private static Dictionary<string, Color>? s_htmlSysColorTable;
internal static uint COLORREFToARGB(uint value)
=> ((value >> COLORREF_RedShift) & 0xFF) << Color.ARGBRedShift
| ((value >> COLORREF_GreenShift) & 0xFF) << Color.ARGBGreenShift
| ((value >> COLORREF_BlueShift) & 0xFF) << Color.ARGBBlueShift
| Color.ARGBAlphaMask; // COLORREF's are always fully opaque
/// <summary>
/// Translates the specified <see cref='Color'/> to a Win32 color.
/// </summary>
public static int ToWin32(Color c)
{
return c.R << COLORREF_RedShift | c.G << COLORREF_GreenShift | c.B << COLORREF_BlueShift;
}
/// <summary>
/// Translates the specified <see cref='Color'/> to an Ole color.
/// </summary>
public static int ToOle(Color c)
{
// IMPORTANT: This signature is invoked directly by the runtime marshaler and cannot change without
// also updating the runtime.
// This method converts Color to an OLE_COLOR.
// https://docs.microsoft.com/openspecs/office_file_formats/ms-oforms/4b8f4be0-3fff-4e42-9fc1-b9fd00251e8e
if (c.IsKnownColor && c.IsSystemColor)
{
// Unfortunately KnownColor didn't keep the same ordering as the various GetSysColor()
// COLOR_ * values, otherwise this could be greatly simplified.
switch (c.ToKnownColor())
{
case KnownColor.ActiveBorder:
return unchecked((int)0x8000000A);
case KnownColor.ActiveCaption:
return unchecked((int)0x80000002);
case KnownColor.ActiveCaptionText:
return unchecked((int)0x80000009);
case KnownColor.AppWorkspace:
return unchecked((int)0x8000000C);
case KnownColor.ButtonFace:
return unchecked((int)0x8000000F);
case KnownColor.ButtonHighlight:
return unchecked((int)0x80000014);
case KnownColor.ButtonShadow:
return unchecked((int)0x80000010);
case KnownColor.Control:
return unchecked((int)0x8000000F);
case KnownColor.ControlDark:
return unchecked((int)0x80000010);
case KnownColor.ControlDarkDark:
return unchecked((int)0x80000015);
case KnownColor.ControlLight:
return unchecked((int)0x80000016);
case KnownColor.ControlLightLight:
return unchecked((int)0x80000014);
case KnownColor.ControlText:
return unchecked((int)0x80000012);
case KnownColor.Desktop:
return unchecked((int)0x80000001);
case KnownColor.GradientActiveCaption:
return unchecked((int)0x8000001B);
case KnownColor.GradientInactiveCaption:
return unchecked((int)0x8000001C);
case KnownColor.GrayText:
return unchecked((int)0x80000011);
case KnownColor.Highlight:
return unchecked((int)0x8000000D);
case KnownColor.HighlightText:
return unchecked((int)0x8000000E);
case KnownColor.HotTrack:
return unchecked((int)0x8000001A);
case KnownColor.InactiveBorder:
return unchecked((int)0x8000000B);
case KnownColor.InactiveCaption:
return unchecked((int)0x80000003);
case KnownColor.InactiveCaptionText:
return unchecked((int)0x80000013);
case KnownColor.Info:
return unchecked((int)0x80000018);
case KnownColor.InfoText:
return unchecked((int)0x80000017);
case KnownColor.Menu:
return unchecked((int)0x80000004);
case KnownColor.MenuBar:
return unchecked((int)0x8000001E);
case KnownColor.MenuHighlight:
return unchecked((int)0x8000001D);
case KnownColor.MenuText:
return unchecked((int)0x80000007);
case KnownColor.ScrollBar:
return unchecked((int)0x80000000);
case KnownColor.Window:
return unchecked((int)0x80000005);
case KnownColor.WindowFrame:
return unchecked((int)0x80000006);
case KnownColor.WindowText:
return unchecked((int)0x80000008);
}
}
return ToWin32(c);
}
/// <summary>
/// Translates an Ole color value to a GDI+ <see cref='Color'/>.
/// </summary>
public static Color FromOle(int oleColor)
{
// IMPORTANT: This signature is invoked directly by the runtime marshaler and cannot change without
// also updating the runtime.
if ((oleColor & OleSystemColorFlag) != 0)
{
switch (oleColor)
{
case unchecked((int)0x8000000A):
return Color.FromKnownColor(KnownColor.ActiveBorder);
case unchecked((int)0x80000002):
return Color.FromKnownColor(KnownColor.ActiveCaption);
case unchecked((int)0x80000009):
return Color.FromKnownColor(KnownColor.ActiveCaptionText);
case unchecked((int)0x8000000C):
return Color.FromKnownColor(KnownColor.AppWorkspace);
case unchecked((int)0x8000000F):
return Color.FromKnownColor(KnownColor.Control);
case unchecked((int)0x80000010):
return Color.FromKnownColor(KnownColor.ControlDark);
case unchecked((int)0x80000015):
return Color.FromKnownColor(KnownColor.ControlDarkDark);
case unchecked((int)0x80000016):
return Color.FromKnownColor(KnownColor.ControlLight);
case unchecked((int)0x80000014):
return Color.FromKnownColor(KnownColor.ControlLightLight);
case unchecked((int)0x80000012):
return Color.FromKnownColor(KnownColor.ControlText);
case unchecked((int)0x80000001):
return Color.FromKnownColor(KnownColor.Desktop);
case unchecked((int)0x8000001B):
return Color.FromKnownColor(KnownColor.GradientActiveCaption);
case unchecked((int)0x8000001C):
return Color.FromKnownColor(KnownColor.GradientInactiveCaption);
case unchecked((int)0x80000011):
return Color.FromKnownColor(KnownColor.GrayText);
case unchecked((int)0x8000000D):
return Color.FromKnownColor(KnownColor.Highlight);
case unchecked((int)0x8000000E):
return Color.FromKnownColor(KnownColor.HighlightText);
case unchecked((int)0x8000001A):
return Color.FromKnownColor(KnownColor.HotTrack);
case unchecked((int)0x8000000B):
return Color.FromKnownColor(KnownColor.InactiveBorder);
case unchecked((int)0x80000003):
return Color.FromKnownColor(KnownColor.InactiveCaption);
case unchecked((int)0x80000013):
return Color.FromKnownColor(KnownColor.InactiveCaptionText);
case unchecked((int)0x80000018):
return Color.FromKnownColor(KnownColor.Info);
case unchecked((int)0x80000017):
return Color.FromKnownColor(KnownColor.InfoText);
case unchecked((int)0x80000004):
return Color.FromKnownColor(KnownColor.Menu);
case unchecked((int)0x8000001E):
return Color.FromKnownColor(KnownColor.MenuBar);
case unchecked((int)0x8000001D):
return Color.FromKnownColor(KnownColor.MenuHighlight);
case unchecked((int)0x80000007):
return Color.FromKnownColor(KnownColor.MenuText);
case unchecked((int)0x80000000):
return Color.FromKnownColor(KnownColor.ScrollBar);
case unchecked((int)0x80000005):
return Color.FromKnownColor(KnownColor.Window);
case unchecked((int)0x80000006):
return Color.FromKnownColor(KnownColor.WindowFrame);
case unchecked((int)0x80000008):
return Color.FromKnownColor(KnownColor.WindowText);
}
}
// When we don't find a system color, we treat the color as a COLORREF
return KnownColorTable.ArgbToKnownColor(COLORREFToARGB((uint)oleColor));
}
/// <summary>
/// Translates an Win32 color value to a GDI+ <see cref='Color'/>.
/// </summary>
public static Color FromWin32(int win32Color)
{
return FromOle(win32Color);
}
/// <summary>
/// Translates an Html color representation to a GDI+ <see cref='Color'/>.
/// </summary>
public static Color FromHtml(string htmlColor)
{
Color c = Color.Empty;
// empty color
if ((htmlColor == null) || (htmlColor.Length == 0))
return c;
// #RRGGBB or #RGB
if ((htmlColor[0] == '#') &&
((htmlColor.Length == 7) || (htmlColor.Length == 4)))
{
if (htmlColor.Length == 7)
{
c = Color.FromArgb(Convert.ToInt32(htmlColor.Substring(1, 2), 16),
Convert.ToInt32(htmlColor.Substring(3, 2), 16),
Convert.ToInt32(htmlColor.Substring(5, 2), 16));
}
else
{
string r = char.ToString(htmlColor[1]);
string g = char.ToString(htmlColor[2]);
string b = char.ToString(htmlColor[3]);
c = Color.FromArgb(Convert.ToInt32(r + r, 16),
Convert.ToInt32(g + g, 16),
Convert.ToInt32(b + b, 16));
}
}
// special case. Html requires LightGrey, but .NET uses LightGray
if (c.IsEmpty && string.Equals(htmlColor, "LightGrey", StringComparison.OrdinalIgnoreCase))
{
c = Color.LightGray;
}
// System color
if (c.IsEmpty)
{
if (s_htmlSysColorTable == null)
{
InitializeHtmlSysColorTable();
}
s_htmlSysColorTable!.TryGetValue(htmlColor.ToLower(CultureInfo.InvariantCulture), out c);
}
// resort to type converter which will handle named colors
if (c.IsEmpty)
{
try
{
c = ColorConverterCommon.ConvertFromString(htmlColor, CultureInfo.CurrentCulture);
}
catch (Exception ex)
{
throw new ArgumentException(ex.Message, nameof(htmlColor), ex);
}
}
return c;
}
/// <summary>
/// Translates the specified <see cref='Color'/> to an Html string color representation.
/// </summary>
public static string ToHtml(Color c)
{
string colorString = string.Empty;
if (c.IsEmpty)
return colorString;
if (c.IsSystemColor)
{
switch (c.ToKnownColor())
{
case KnownColor.ActiveBorder:
colorString = "activeborder";
break;
case KnownColor.GradientActiveCaption:
case KnownColor.ActiveCaption:
colorString = "activecaption";
break;
case KnownColor.AppWorkspace:
colorString = "appworkspace";
break;
case KnownColor.Desktop:
colorString = "background";
break;
case KnownColor.Control:
case KnownColor.ControlLight:
colorString = "buttonface";
break;
case KnownColor.ControlDark:
colorString = "buttonshadow";
break;
case KnownColor.ControlText:
colorString = "buttontext";
break;
case KnownColor.ActiveCaptionText:
colorString = "captiontext";
break;
case KnownColor.GrayText:
colorString = "graytext";
break;
case KnownColor.HotTrack:
case KnownColor.Highlight:
colorString = "highlight";
break;
case KnownColor.MenuHighlight:
case KnownColor.HighlightText:
colorString = "highlighttext";
break;
case KnownColor.InactiveBorder:
colorString = "inactiveborder";
break;
case KnownColor.GradientInactiveCaption:
case KnownColor.InactiveCaption:
colorString = "inactivecaption";
break;
case KnownColor.InactiveCaptionText:
colorString = "inactivecaptiontext";
break;
case KnownColor.Info:
colorString = "infobackground";
break;
case KnownColor.InfoText:
colorString = "infotext";
break;
case KnownColor.MenuBar:
case KnownColor.Menu:
colorString = "menu";
break;
case KnownColor.MenuText:
colorString = "menutext";
break;
case KnownColor.ScrollBar:
colorString = "scrollbar";
break;
case KnownColor.ControlDarkDark:
colorString = "threeddarkshadow";
break;
case KnownColor.ControlLightLight:
colorString = "buttonhighlight";
break;
case KnownColor.Window:
colorString = "window";
break;
case KnownColor.WindowFrame:
colorString = "windowframe";
break;
case KnownColor.WindowText:
colorString = "windowtext";
break;
}
}
else if (c.IsNamedColor)
{
if (c == Color.LightGray)
{
// special case due to mismatch between Html and enum spelling
colorString = "LightGrey";
}
else
{
colorString = c.Name;
}
}
else
{
colorString = "#" + c.R.ToString("X2", null) +
c.G.ToString("X2", null) +
c.B.ToString("X2", null);
}
return colorString;
}
private static void InitializeHtmlSysColorTable()
{
s_htmlSysColorTable = new Dictionary<string, Color>(27)
{
["activeborder"] = Color.FromKnownColor(KnownColor.ActiveBorder),
["activecaption"] = Color.FromKnownColor(KnownColor.ActiveCaption),
["appworkspace"] = Color.FromKnownColor(KnownColor.AppWorkspace),
["background"] = Color.FromKnownColor(KnownColor.Desktop),
["buttonface"] = Color.FromKnownColor(KnownColor.Control),
["buttonhighlight"] = Color.FromKnownColor(KnownColor.ControlLightLight),
["buttonshadow"] = Color.FromKnownColor(KnownColor.ControlDark),
["buttontext"] = Color.FromKnownColor(KnownColor.ControlText),
["captiontext"] = Color.FromKnownColor(KnownColor.ActiveCaptionText),
["graytext"] = Color.FromKnownColor(KnownColor.GrayText),
["highlight"] = Color.FromKnownColor(KnownColor.Highlight),
["highlighttext"] = Color.FromKnownColor(KnownColor.HighlightText),
["inactiveborder"] = Color.FromKnownColor(KnownColor.InactiveBorder),
["inactivecaption"] = Color.FromKnownColor(KnownColor.InactiveCaption),
["inactivecaptiontext"] = Color.FromKnownColor(KnownColor.InactiveCaptionText),
["infobackground"] = Color.FromKnownColor(KnownColor.Info),
["infotext"] = Color.FromKnownColor(KnownColor.InfoText),
["menu"] = Color.FromKnownColor(KnownColor.Menu),
["menutext"] = Color.FromKnownColor(KnownColor.MenuText),
["scrollbar"] = Color.FromKnownColor(KnownColor.ScrollBar),
["threeddarkshadow"] = Color.FromKnownColor(KnownColor.ControlDarkDark),
["threedface"] = Color.FromKnownColor(KnownColor.Control),
["threedhighlight"] = Color.FromKnownColor(KnownColor.ControlLight),
["threedlightshadow"] = Color.FromKnownColor(KnownColor.ControlLightLight),
["window"] = Color.FromKnownColor(KnownColor.Window),
["windowframe"] = Color.FromKnownColor(KnownColor.WindowFrame),
["windowtext"] = Color.FromKnownColor(KnownColor.WindowText)
};
}
}
}
| |
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Rubius
//
// 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.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Realmius.Contracts.Models;
using Realmius.Server.Configurations;
using Realmius.Server.Expressions;
using Realmius.Server.Infrastructure;
using Realmius.Server.Models;
using Realmius.Contracts.Logger;
namespace Realmius.Server
{
public class RealmiusServerProcessor : RealmiusServerProcessor<object>
{
public RealmiusServerProcessor(IRealmiusServerConfiguration<object> configuration)
: base(configuration)
{
}
}
public class RealmiusServerProcessor<TUser>
{
private readonly Func<ChangeTrackingDbContext> _dbContextFactoryFunc;
public IRealmiusServerConfiguration<TUser> Configuration { get; }
private ILogger Logger => Configuration.Logger;
private readonly Dictionary<string, Type> _syncedTypes;
private readonly string _connectionString;
public RealmiusServerProcessor(IRealmiusServerConfiguration<TUser> configuration)
{
if (configuration.Logger == null)
{
configuration.Logger = new Logger();
}
_dbContextFactoryFunc = configuration.ContextFactoryFunction;
Configuration = configuration;
_syncedTypes = Configuration.TypesToSync.ToDictionary(x => x.Name, x => x);
var syncObjectInterface = typeof(IRealmiusObjectServer);
foreach (var type in _syncedTypes.Values)
{
if (!syncObjectInterface.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
throw new InvalidOperationException($"Type {type} does not implement IRealmiusObjectServer, unable to continue");
}
_connectionString = _dbContextFactoryFunc().Database.Connection.ConnectionString;
}
public UploadDataResponse Upload(UploadDataRequest request, TUser user)
{
var result = new UploadDataResponse();
//var updatedResult = new UpdatedDataBatch();
var ef = _dbContextFactoryFunc();
ef.User = user;
foreach (var item in request.ChangeNotifications)
{
UploadDataResponseItem objectInfo = null;
string upObjectInfo = !item.IsDeleted
? item.SerializedObject
: "{" + $"\n \"{nameof(item.Type)}\": \"{item.Type}\",\n \"{nameof(item.PrimaryKey)}\": \"{item.PrimaryKey}\"\n \"{nameof(item.IsDeleted)}\": \"{item.IsDeleted}\"\n" + "}";
Logger.Debug($"User {user}, Saving entity: {upObjectInfo}"); //{JsonConvert.SerializeObject(item)}
IRealmiusObjectServer dbEntity = null;
try
{
var type = _syncedTypes[item.Type];
objectInfo = new UploadDataResponseItem(item.PrimaryKey, item.Type);
result.Results.Add(objectInfo);
var dbSet = ef.Set(type);
object[] key;
try
{
key = Configuration.KeyForType(type, item.PrimaryKey);
}
catch (Exception e)
{
Logger.Exception(e, $"Error getting key, {item.PrimaryKey}");
throw;
}
var referencesConverter = new RealmServerCollectionConverter
{
Database = ef,
};
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
referencesConverter
},
ObjectCreationHandling = ObjectCreationHandling.Reuse,
};
dbEntity = (IRealmiusObjectServer)dbSet.Find(key);
if (dbEntity != null)
{
if (item.IsDeleted)
{
dbSet.Remove(dbEntity);
}
else
{
//entity exists in DB, UPDATE it
var untouchedEntityClone = ef.CloneWithOriginalValues(dbEntity);
JsonConvert.PopulateObject(item.SerializedObject, dbEntity, settings);
var args = new CheckAndProcessArgs<TUser>
{
Database = ef,
OriginalDbEntity = untouchedEntityClone,
Entity = dbEntity,
User = user
};
if (!CheckAndProcess(args))
{
//revert all changes (no need to revert, entity was detached)
ef.Entry(dbEntity).Reload();
objectInfo.Error = "Object failed security checks";
}
else
{
//try
//{
// entry.State = EntityState.Modified;
//}
//catch (InvalidOperationException e)
//{
// var anotherEntry = dbSet.Find(key);
// ef.Entry(anotherEntry).State = EntityState.Detached;
// entry.State = EntityState.Modified;
//}
}
}
}
else
{
if (!item.IsDeleted)
{
//entity does not exist in DB, CREATE it
dbEntity = (IRealmiusObjectServer)JsonConvert.DeserializeObject(item.SerializedObject,
type, settings);
var args = new CheckAndProcessArgs<TUser>
{
Database = ef,
OriginalDbEntity = null,
Entity = dbEntity,
User = user
};
if (CheckAndProcess(args))
{
//dbEntity.LastChangeServer = DateTime.UtcNow;
//add to the database
dbSet.Attach(dbEntity);
ef.Entry(dbEntity).State = EntityState.Added;
}
else
{
objectInfo.Error = "Object failed security checks";
}
}
}
//updatedResult.Items.Add(new UpdatedDataItem()
//{
// DeserializedObject = dbEntity,
// Change = new DownloadResponseItem()
// {
// MobilePrimaryKey = item.PrimaryKey,
// Type = item.Type,
// SerializedObject = item.SerializedObject,
// },
//});
if (!string.IsNullOrEmpty(objectInfo.Error))
{
Logger.Debug($"Error saving the entity {objectInfo.Error}");
}
ef.SaveChanges();
}
catch (Exception e)
{
if (objectInfo != null)
{
objectInfo.Error = e.ToString();
}
if (e is DbEntityValidationException && dbEntity != null)
{
ef.Entry(dbEntity).State = EntityState.Detached; //if one entity fails EF validation, we should still save all the others (if possible)
}
Logger.Info($"Exception saving the entity {e}");
//continue processing anyway
//throw;
}
}
//OnDataUpdated(updatedResult);
return result;
}
public virtual IList<string> GetTagsForUser(TUser user)
{
var ef = _dbContextFactoryFunc();
return Configuration.GetTagsForUser(user, ef);
}
public DownloadDataResponse Download(DownloadDataRequest request, TUser user)
{
if (user == null)
throw new NullReferenceException("user arg cannot be null");
var response = new DownloadDataResponse
{
LastChange = GetTagsForUser(user).ToDictionary(x => x, x => DateTimeOffset.UtcNow),
};
request.Types = request.Types.Intersect(_syncedTypes.Keys).ToList();
//if (types.Count > 0)
//{
// throw new Exception("Some types are not configured to be synced: " + string.Join(",", types));
//}
var context = CreateSyncStatusDbContext();
var changes = CreateQuery(request, user, context);
foreach (var changedObject in changes)
{
var lastChangeTime = FindLastChangeTime(request, changedObject);
var jObject = JObject.Parse(changedObject.FullObjectAsJson);
var changedColumns =
changedObject.ColumnChangeDates.Where(x => x.Value > lastChangeTime)
.ToDictionary(x => x.Key);
foreach (var property in jObject.Properties().ToList())
{
if (!changedColumns.ContainsKey(property.Name))
{
jObject.Remove(property.Name);
}
}
var downloadResponseItem = new DownloadResponseItem
{
Type = changedObject.Type,
MobilePrimaryKey = changedObject.MobilePrimaryKey,
IsDeleted = changedObject.IsDeleted,
SerializedObject = jObject.ToString(),
};
response.ChangedObjects.Add(downloadResponseItem);
}
return response;
}
private DateTimeOffset FindLastChangeTime(DownloadDataRequest request, SyncStatusServerObject syncStatusServerObject)
{
var tags = new[]
{
syncStatusServerObject.Tag0,
syncStatusServerObject.Tag1,
syncStatusServerObject.Tag2,
syncStatusServerObject.Tag3,
};
var lastChangeTime = DateTimeOffset.MinValue;
foreach (var tag in tags.Where(x => !string.IsNullOrEmpty(x)))
{
if (request.LastChangeTime.TryGetValue(tag, out DateTimeOffset time))
{
if (time > lastChangeTime)
lastChangeTime = time;
}
}
return lastChangeTime;
}
internal IQueryable<SyncStatusServerObject> CreateQuery(DownloadDataRequest request, TUser user, SyncStatusDbContext context)
{
Expression<Func<SyncStatusServerObject, bool>> whereExpression = null;
foreach (var userTag in GetTagsForUser(user))
{
Expression<Func<SyncStatusServerObject, bool>> condition = null;
if (request.LastChangeTime.TryGetValue(userTag, out DateTimeOffset lastChange))
{
condition = x =>
(x.Tag0 == userTag || x.Tag1 == userTag || x.Tag2 == userTag || x.Tag3 == userTag) &&
x.LastChange > lastChange;
}
else if (!request.OnlyDownloadSpecifiedTags)
{
condition = x =>
!x.IsDeleted &&
(x.Tag0 == userTag || x.Tag1 == userTag || x.Tag2 == userTag || x.Tag3 == userTag);
}
if (condition != null)
{
whereExpression = whereExpression == null ? condition : whereExpression.Or(condition);
}
}
if (whereExpression == null)
whereExpression = x => false;
var changes = context.SyncStatusServerObjects.AsNoTracking()
.Where(x => request.Types.Contains(x.Type)).Where(whereExpression);
//var changes = context.SyncStatusServerObjects.AsNoTracking()
// .Where(x => x.LastChange > request.LastChangeTime &&
// request.Types.Contains(x.Type)
// && (user.Tags.Contains(x.Tag0) || user.Tags.Contains(x.Tag1) || user.Tags.Contains(x.Tag2) || user.Tags.Contains(x.Tag3)))
// .OrderBy(x => x.LastChange);
return changes;
}
/// <summary>
/// returns True if it's ok to save the object, False oterwise
/// </summary>
/// <returns></returns>
protected virtual bool CheckAndProcess(CheckAndProcessArgs<TUser> args)
{
return Configuration.CheckAndProcess(args);
}
protected SyncStatusDbContext CreateSyncStatusDbContext()
{
var context = new SyncStatusDbContext(_connectionString);
return context;
}
}
}
| |
namespace Fixtures.SwaggerBatRequiredOptional
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial interface IExplicitModel
{
/// <summary>
/// Test explicitly required integer. Please put null and the client
/// library should throw before the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredIntegerParameterWithHttpMessagesAsync(int? bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional integer. Please put null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalIntegerParameterWithHttpMessagesAsync(int? bodyParameter = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required integer. Please put a valid int-wrapper
/// with 'value' = null and the client library should throw before
/// the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredIntegerPropertyWithHttpMessagesAsync(IntWrapper bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional integer. Please put a valid int-wrapper
/// with 'value' = null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalIntegerPropertyWithHttpMessagesAsync(IntOptionalWrapper bodyParameter = default(IntOptionalWrapper), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required integer. Please put a header
/// 'headerParameter' => null and the client library should throw
/// before the request is sent.
/// </summary>
/// <param name='headerParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredIntegerHeaderWithHttpMessagesAsync(int? headerParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional integer. Please put a header
/// 'headerParameter' => null.
/// </summary>
/// <param name='headerParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalIntegerHeaderWithHttpMessagesAsync(int? headerParameter = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required string. Please put null and the client
/// library should throw before the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredStringParameterWithHttpMessagesAsync(string bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional string. Please put null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalStringParameterWithHttpMessagesAsync(string bodyParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required string. Please put a valid string-wrapper
/// with 'value' = null and the client library should throw before
/// the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredStringPropertyWithHttpMessagesAsync(StringWrapper bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional integer. Please put a valid
/// string-wrapper with 'value' = null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalStringPropertyWithHttpMessagesAsync(StringOptionalWrapper bodyParameter = default(StringOptionalWrapper), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required string. Please put a header
/// 'headerParameter' => null and the client library should throw
/// before the request is sent.
/// </summary>
/// <param name='headerParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredStringHeaderWithHttpMessagesAsync(string headerParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional string. Please put a header
/// 'headerParameter' => null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalStringHeaderWithHttpMessagesAsync(string bodyParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required complex object. Please put null and the
/// client library should throw before the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredClassParameterWithHttpMessagesAsync(Product bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional complex object. Please put null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalClassParameterWithHttpMessagesAsync(Product bodyParameter = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required complex object. Please put a valid
/// class-wrapper with 'value' = null and the client library should
/// throw before the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredClassPropertyWithHttpMessagesAsync(ClassWrapper bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional complex object. Please put a valid
/// class-wrapper with 'value' = null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalClassPropertyWithHttpMessagesAsync(ClassOptionalWrapper bodyParameter = default(ClassOptionalWrapper), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required array. Please put null and the client
/// library should throw before the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredArrayParameterWithHttpMessagesAsync(IList<string> bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional array. Please put null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalArrayParameterWithHttpMessagesAsync(IList<string> bodyParameter = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required array. Please put a valid array-wrapper
/// with 'value' = null and the client library should throw before
/// the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredArrayPropertyWithHttpMessagesAsync(ArrayWrapper bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional array. Please put a valid array-wrapper
/// with 'value' = null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalArrayPropertyWithHttpMessagesAsync(ArrayOptionalWrapper bodyParameter = default(ArrayOptionalWrapper), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required array. Please put a header
/// 'headerParameter' => null and the client library should throw
/// before the request is sent.
/// </summary>
/// <param name='headerParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<Error>> PostRequiredArrayHeaderWithHttpMessagesAsync(IList<string> headerParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional integer. Please put a header
/// 'headerParameter' => null.
/// </summary>
/// <param name='headerParameter'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> PostOptionalArrayHeaderWithHttpMessagesAsync(IList<string> headerParameter = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A type of virtual GPU
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
public partial class VGPU_type : XenObject<VGPU_type>
{
#region Constructors
public VGPU_type()
{
}
public VGPU_type(string uuid,
string vendor_name,
string model_name,
long framebuffer_size,
long max_heads,
long max_resolution_x,
long max_resolution_y,
List<XenRef<PGPU>> supported_on_PGPUs,
List<XenRef<PGPU>> enabled_on_PGPUs,
List<XenRef<VGPU>> VGPUs,
List<XenRef<GPU_group>> supported_on_GPU_groups,
List<XenRef<GPU_group>> enabled_on_GPU_groups,
vgpu_type_implementation implementation,
string identifier,
bool experimental,
List<XenRef<VGPU_type>> compatible_types_in_vm)
{
this.uuid = uuid;
this.vendor_name = vendor_name;
this.model_name = model_name;
this.framebuffer_size = framebuffer_size;
this.max_heads = max_heads;
this.max_resolution_x = max_resolution_x;
this.max_resolution_y = max_resolution_y;
this.supported_on_PGPUs = supported_on_PGPUs;
this.enabled_on_PGPUs = enabled_on_PGPUs;
this.VGPUs = VGPUs;
this.supported_on_GPU_groups = supported_on_GPU_groups;
this.enabled_on_GPU_groups = enabled_on_GPU_groups;
this.implementation = implementation;
this.identifier = identifier;
this.experimental = experimental;
this.compatible_types_in_vm = compatible_types_in_vm;
}
/// <summary>
/// Creates a new VGPU_type from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public VGPU_type(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new VGPU_type from a Proxy_VGPU_type.
/// </summary>
/// <param name="proxy"></param>
public VGPU_type(Proxy_VGPU_type proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given VGPU_type.
/// </summary>
public override void UpdateFrom(VGPU_type update)
{
uuid = update.uuid;
vendor_name = update.vendor_name;
model_name = update.model_name;
framebuffer_size = update.framebuffer_size;
max_heads = update.max_heads;
max_resolution_x = update.max_resolution_x;
max_resolution_y = update.max_resolution_y;
supported_on_PGPUs = update.supported_on_PGPUs;
enabled_on_PGPUs = update.enabled_on_PGPUs;
VGPUs = update.VGPUs;
supported_on_GPU_groups = update.supported_on_GPU_groups;
enabled_on_GPU_groups = update.enabled_on_GPU_groups;
implementation = update.implementation;
identifier = update.identifier;
experimental = update.experimental;
compatible_types_in_vm = update.compatible_types_in_vm;
}
internal void UpdateFrom(Proxy_VGPU_type proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
vendor_name = proxy.vendor_name == null ? null : proxy.vendor_name;
model_name = proxy.model_name == null ? null : proxy.model_name;
framebuffer_size = proxy.framebuffer_size == null ? 0 : long.Parse(proxy.framebuffer_size);
max_heads = proxy.max_heads == null ? 0 : long.Parse(proxy.max_heads);
max_resolution_x = proxy.max_resolution_x == null ? 0 : long.Parse(proxy.max_resolution_x);
max_resolution_y = proxy.max_resolution_y == null ? 0 : long.Parse(proxy.max_resolution_y);
supported_on_PGPUs = proxy.supported_on_PGPUs == null ? null : XenRef<PGPU>.Create(proxy.supported_on_PGPUs);
enabled_on_PGPUs = proxy.enabled_on_PGPUs == null ? null : XenRef<PGPU>.Create(proxy.enabled_on_PGPUs);
VGPUs = proxy.VGPUs == null ? null : XenRef<VGPU>.Create(proxy.VGPUs);
supported_on_GPU_groups = proxy.supported_on_GPU_groups == null ? null : XenRef<GPU_group>.Create(proxy.supported_on_GPU_groups);
enabled_on_GPU_groups = proxy.enabled_on_GPU_groups == null ? null : XenRef<GPU_group>.Create(proxy.enabled_on_GPU_groups);
implementation = proxy.implementation == null ? (vgpu_type_implementation) 0 : (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), (string)proxy.implementation);
identifier = proxy.identifier == null ? null : proxy.identifier;
experimental = (bool)proxy.experimental;
compatible_types_in_vm = proxy.compatible_types_in_vm == null ? null : XenRef<VGPU_type>.Create(proxy.compatible_types_in_vm);
}
public Proxy_VGPU_type ToProxy()
{
Proxy_VGPU_type result_ = new Proxy_VGPU_type();
result_.uuid = uuid ?? "";
result_.vendor_name = vendor_name ?? "";
result_.model_name = model_name ?? "";
result_.framebuffer_size = framebuffer_size.ToString();
result_.max_heads = max_heads.ToString();
result_.max_resolution_x = max_resolution_x.ToString();
result_.max_resolution_y = max_resolution_y.ToString();
result_.supported_on_PGPUs = supported_on_PGPUs == null ? new string[] {} : Helper.RefListToStringArray(supported_on_PGPUs);
result_.enabled_on_PGPUs = enabled_on_PGPUs == null ? new string[] {} : Helper.RefListToStringArray(enabled_on_PGPUs);
result_.VGPUs = VGPUs == null ? new string[] {} : Helper.RefListToStringArray(VGPUs);
result_.supported_on_GPU_groups = supported_on_GPU_groups == null ? new string[] {} : Helper.RefListToStringArray(supported_on_GPU_groups);
result_.enabled_on_GPU_groups = enabled_on_GPU_groups == null ? new string[] {} : Helper.RefListToStringArray(enabled_on_GPU_groups);
result_.implementation = vgpu_type_implementation_helper.ToString(implementation);
result_.identifier = identifier ?? "";
result_.experimental = experimental;
result_.compatible_types_in_vm = compatible_types_in_vm == null ? new string[] {} : Helper.RefListToStringArray(compatible_types_in_vm);
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this VGPU_type
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("vendor_name"))
vendor_name = Marshalling.ParseString(table, "vendor_name");
if (table.ContainsKey("model_name"))
model_name = Marshalling.ParseString(table, "model_name");
if (table.ContainsKey("framebuffer_size"))
framebuffer_size = Marshalling.ParseLong(table, "framebuffer_size");
if (table.ContainsKey("max_heads"))
max_heads = Marshalling.ParseLong(table, "max_heads");
if (table.ContainsKey("max_resolution_x"))
max_resolution_x = Marshalling.ParseLong(table, "max_resolution_x");
if (table.ContainsKey("max_resolution_y"))
max_resolution_y = Marshalling.ParseLong(table, "max_resolution_y");
if (table.ContainsKey("supported_on_PGPUs"))
supported_on_PGPUs = Marshalling.ParseSetRef<PGPU>(table, "supported_on_PGPUs");
if (table.ContainsKey("enabled_on_PGPUs"))
enabled_on_PGPUs = Marshalling.ParseSetRef<PGPU>(table, "enabled_on_PGPUs");
if (table.ContainsKey("VGPUs"))
VGPUs = Marshalling.ParseSetRef<VGPU>(table, "VGPUs");
if (table.ContainsKey("supported_on_GPU_groups"))
supported_on_GPU_groups = Marshalling.ParseSetRef<GPU_group>(table, "supported_on_GPU_groups");
if (table.ContainsKey("enabled_on_GPU_groups"))
enabled_on_GPU_groups = Marshalling.ParseSetRef<GPU_group>(table, "enabled_on_GPU_groups");
if (table.ContainsKey("implementation"))
implementation = (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), Marshalling.ParseString(table, "implementation"));
if (table.ContainsKey("identifier"))
identifier = Marshalling.ParseString(table, "identifier");
if (table.ContainsKey("experimental"))
experimental = Marshalling.ParseBool(table, "experimental");
if (table.ContainsKey("compatible_types_in_vm"))
compatible_types_in_vm = Marshalling.ParseSetRef<VGPU_type>(table, "compatible_types_in_vm");
}
public bool DeepEquals(VGPU_type other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._vendor_name, other._vendor_name) &&
Helper.AreEqual2(this._model_name, other._model_name) &&
Helper.AreEqual2(this._framebuffer_size, other._framebuffer_size) &&
Helper.AreEqual2(this._max_heads, other._max_heads) &&
Helper.AreEqual2(this._max_resolution_x, other._max_resolution_x) &&
Helper.AreEqual2(this._max_resolution_y, other._max_resolution_y) &&
Helper.AreEqual2(this._supported_on_PGPUs, other._supported_on_PGPUs) &&
Helper.AreEqual2(this._enabled_on_PGPUs, other._enabled_on_PGPUs) &&
Helper.AreEqual2(this._VGPUs, other._VGPUs) &&
Helper.AreEqual2(this._supported_on_GPU_groups, other._supported_on_GPU_groups) &&
Helper.AreEqual2(this._enabled_on_GPU_groups, other._enabled_on_GPU_groups) &&
Helper.AreEqual2(this._implementation, other._implementation) &&
Helper.AreEqual2(this._identifier, other._identifier) &&
Helper.AreEqual2(this._experimental, other._experimental) &&
Helper.AreEqual2(this._compatible_types_in_vm, other._compatible_types_in_vm);
}
internal static List<VGPU_type> ProxyArrayToObjectList(Proxy_VGPU_type[] input)
{
var result = new List<VGPU_type>();
foreach (var item in input)
result.Add(new VGPU_type(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, VGPU_type server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static VGPU_type get_record(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_record(session.opaque_ref, _vgpu_type);
else
return new VGPU_type(session.XmlRpcProxy.vgpu_type_get_record(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get a reference to the VGPU_type instance with the specified UUID.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VGPU_type> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<VGPU_type>.Create(session.XmlRpcProxy.vgpu_type_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_uuid(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_uuid(session.opaque_ref, _vgpu_type);
else
return session.XmlRpcProxy.vgpu_type_get_uuid(session.opaque_ref, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the vendor_name field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_vendor_name(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_vendor_name(session.opaque_ref, _vgpu_type);
else
return session.XmlRpcProxy.vgpu_type_get_vendor_name(session.opaque_ref, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the model_name field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_model_name(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_model_name(session.opaque_ref, _vgpu_type);
else
return session.XmlRpcProxy.vgpu_type_get_model_name(session.opaque_ref, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the framebuffer_size field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_framebuffer_size(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_framebuffer_size(session.opaque_ref, _vgpu_type);
else
return long.Parse(session.XmlRpcProxy.vgpu_type_get_framebuffer_size(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the max_heads field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_heads(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_max_heads(session.opaque_ref, _vgpu_type);
else
return long.Parse(session.XmlRpcProxy.vgpu_type_get_max_heads(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the max_resolution_x field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_resolution_x(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_max_resolution_x(session.opaque_ref, _vgpu_type);
else
return long.Parse(session.XmlRpcProxy.vgpu_type_get_max_resolution_x(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the max_resolution_y field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_resolution_y(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_max_resolution_y(session.opaque_ref, _vgpu_type);
else
return long.Parse(session.XmlRpcProxy.vgpu_type_get_max_resolution_y(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the supported_on_PGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<PGPU>> get_supported_on_PGPUs(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_supported_on_pgpus(session.opaque_ref, _vgpu_type);
else
return XenRef<PGPU>.Create(session.XmlRpcProxy.vgpu_type_get_supported_on_pgpus(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the enabled_on_PGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<PGPU>> get_enabled_on_PGPUs(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_enabled_on_pgpus(session.opaque_ref, _vgpu_type);
else
return XenRef<PGPU>.Create(session.XmlRpcProxy.vgpu_type_get_enabled_on_pgpus(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the VGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<VGPU>> get_VGPUs(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_vgpus(session.opaque_ref, _vgpu_type);
else
return XenRef<VGPU>.Create(session.XmlRpcProxy.vgpu_type_get_vgpus(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the supported_on_GPU_groups field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<GPU_group>> get_supported_on_GPU_groups(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_supported_on_gpu_groups(session.opaque_ref, _vgpu_type);
else
return XenRef<GPU_group>.Create(session.XmlRpcProxy.vgpu_type_get_supported_on_gpu_groups(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the enabled_on_GPU_groups field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<GPU_group>> get_enabled_on_GPU_groups(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_enabled_on_gpu_groups(session.opaque_ref, _vgpu_type);
else
return XenRef<GPU_group>.Create(session.XmlRpcProxy.vgpu_type_get_enabled_on_gpu_groups(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the implementation field of the given VGPU_type.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static vgpu_type_implementation get_implementation(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_implementation(session.opaque_ref, _vgpu_type);
else
return (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), (string)session.XmlRpcProxy.vgpu_type_get_implementation(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the identifier field of the given VGPU_type.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_identifier(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_identifier(session.opaque_ref, _vgpu_type);
else
return session.XmlRpcProxy.vgpu_type_get_identifier(session.opaque_ref, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the experimental field of the given VGPU_type.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static bool get_experimental(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_experimental(session.opaque_ref, _vgpu_type);
else
return (bool)session.XmlRpcProxy.vgpu_type_get_experimental(session.opaque_ref, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the compatible_types_in_vm field of the given VGPU_type.
/// First published in Citrix Hypervisor 8.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<VGPU_type>> get_compatible_types_in_vm(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_compatible_types_in_vm(session.opaque_ref, _vgpu_type);
else
return XenRef<VGPU_type>.Create(session.XmlRpcProxy.vgpu_type_get_compatible_types_in_vm(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Return a list of all the VGPU_types known to the system.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VGPU_type>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_all(session.opaque_ref);
else
return XenRef<VGPU_type>.Create(session.XmlRpcProxy.vgpu_type_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the VGPU_type Records at once, in a single XML RPC call
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VGPU_type>, VGPU_type> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_all_records(session.opaque_ref);
else
return XenRef<VGPU_type>.Create<Proxy_VGPU_type>(session.XmlRpcProxy.vgpu_type_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// Name of VGPU vendor
/// </summary>
public virtual string vendor_name
{
get { return _vendor_name; }
set
{
if (!Helper.AreEqual(value, _vendor_name))
{
_vendor_name = value;
NotifyPropertyChanged("vendor_name");
}
}
}
private string _vendor_name = "";
/// <summary>
/// Model name associated with the VGPU type
/// </summary>
public virtual string model_name
{
get { return _model_name; }
set
{
if (!Helper.AreEqual(value, _model_name))
{
_model_name = value;
NotifyPropertyChanged("model_name");
}
}
}
private string _model_name = "";
/// <summary>
/// Framebuffer size of the VGPU type, in bytes
/// </summary>
public virtual long framebuffer_size
{
get { return _framebuffer_size; }
set
{
if (!Helper.AreEqual(value, _framebuffer_size))
{
_framebuffer_size = value;
NotifyPropertyChanged("framebuffer_size");
}
}
}
private long _framebuffer_size = 0;
/// <summary>
/// Maximum number of displays supported by the VGPU type
/// </summary>
public virtual long max_heads
{
get { return _max_heads; }
set
{
if (!Helper.AreEqual(value, _max_heads))
{
_max_heads = value;
NotifyPropertyChanged("max_heads");
}
}
}
private long _max_heads = 0;
/// <summary>
/// Maximum resolution (width) supported by the VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual long max_resolution_x
{
get { return _max_resolution_x; }
set
{
if (!Helper.AreEqual(value, _max_resolution_x))
{
_max_resolution_x = value;
NotifyPropertyChanged("max_resolution_x");
}
}
}
private long _max_resolution_x = 0;
/// <summary>
/// Maximum resolution (height) supported by the VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual long max_resolution_y
{
get { return _max_resolution_y; }
set
{
if (!Helper.AreEqual(value, _max_resolution_y))
{
_max_resolution_y = value;
NotifyPropertyChanged("max_resolution_y");
}
}
}
private long _max_resolution_y = 0;
/// <summary>
/// List of PGPUs that support this VGPU type
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PGPU>))]
public virtual List<XenRef<PGPU>> supported_on_PGPUs
{
get { return _supported_on_PGPUs; }
set
{
if (!Helper.AreEqual(value, _supported_on_PGPUs))
{
_supported_on_PGPUs = value;
NotifyPropertyChanged("supported_on_PGPUs");
}
}
}
private List<XenRef<PGPU>> _supported_on_PGPUs = new List<XenRef<PGPU>>() {};
/// <summary>
/// List of PGPUs that have this VGPU type enabled
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PGPU>))]
public virtual List<XenRef<PGPU>> enabled_on_PGPUs
{
get { return _enabled_on_PGPUs; }
set
{
if (!Helper.AreEqual(value, _enabled_on_PGPUs))
{
_enabled_on_PGPUs = value;
NotifyPropertyChanged("enabled_on_PGPUs");
}
}
}
private List<XenRef<PGPU>> _enabled_on_PGPUs = new List<XenRef<PGPU>>() {};
/// <summary>
/// List of VGPUs of this type
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VGPU>))]
public virtual List<XenRef<VGPU>> VGPUs
{
get { return _VGPUs; }
set
{
if (!Helper.AreEqual(value, _VGPUs))
{
_VGPUs = value;
NotifyPropertyChanged("VGPUs");
}
}
}
private List<XenRef<VGPU>> _VGPUs = new List<XenRef<VGPU>>() {};
/// <summary>
/// List of GPU groups in which at least one PGPU supports this VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<GPU_group>))]
public virtual List<XenRef<GPU_group>> supported_on_GPU_groups
{
get { return _supported_on_GPU_groups; }
set
{
if (!Helper.AreEqual(value, _supported_on_GPU_groups))
{
_supported_on_GPU_groups = value;
NotifyPropertyChanged("supported_on_GPU_groups");
}
}
}
private List<XenRef<GPU_group>> _supported_on_GPU_groups = new List<XenRef<GPU_group>>() {};
/// <summary>
/// List of GPU groups in which at least one have this VGPU type enabled
/// First published in XenServer 6.2 SP1.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<GPU_group>))]
public virtual List<XenRef<GPU_group>> enabled_on_GPU_groups
{
get { return _enabled_on_GPU_groups; }
set
{
if (!Helper.AreEqual(value, _enabled_on_GPU_groups))
{
_enabled_on_GPU_groups = value;
NotifyPropertyChanged("enabled_on_GPU_groups");
}
}
}
private List<XenRef<GPU_group>> _enabled_on_GPU_groups = new List<XenRef<GPU_group>>() {};
/// <summary>
/// The internal implementation of this VGPU type
/// First published in XenServer 7.0.
/// </summary>
[JsonConverter(typeof(vgpu_type_implementationConverter))]
public virtual vgpu_type_implementation implementation
{
get { return _implementation; }
set
{
if (!Helper.AreEqual(value, _implementation))
{
_implementation = value;
NotifyPropertyChanged("implementation");
}
}
}
private vgpu_type_implementation _implementation = vgpu_type_implementation.passthrough;
/// <summary>
/// Key used to identify VGPU types and avoid creating duplicates - this field is used internally and not intended for interpretation by API clients
/// First published in XenServer 7.0.
/// </summary>
public virtual string identifier
{
get { return _identifier; }
set
{
if (!Helper.AreEqual(value, _identifier))
{
_identifier = value;
NotifyPropertyChanged("identifier");
}
}
}
private string _identifier = "";
/// <summary>
/// Indicates whether VGPUs of this type should be considered experimental
/// First published in XenServer 7.0.
/// </summary>
public virtual bool experimental
{
get { return _experimental; }
set
{
if (!Helper.AreEqual(value, _experimental))
{
_experimental = value;
NotifyPropertyChanged("experimental");
}
}
}
private bool _experimental = false;
/// <summary>
/// List of VGPU types which are compatible in one VM
/// First published in Citrix Hypervisor 8.1.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VGPU_type>))]
public virtual List<XenRef<VGPU_type>> compatible_types_in_vm
{
get { return _compatible_types_in_vm; }
set
{
if (!Helper.AreEqual(value, _compatible_types_in_vm))
{
_compatible_types_in_vm = value;
NotifyPropertyChanged("compatible_types_in_vm");
}
}
}
private List<XenRef<VGPU_type>> _compatible_types_in_vm = new List<XenRef<VGPU_type>>() {};
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// A PCI device
/// First published in XenServer 6.0.
/// </summary>
public partial class PCI : XenObject<PCI>
{
public PCI()
{
}
public PCI(string uuid,
string class_name,
string vendor_name,
string device_name,
XenRef<Host> host,
string pci_id,
List<XenRef<PCI>> dependencies,
Dictionary<string, string> other_config,
string subsystem_vendor_name,
string subsystem_device_name)
{
this.uuid = uuid;
this.class_name = class_name;
this.vendor_name = vendor_name;
this.device_name = device_name;
this.host = host;
this.pci_id = pci_id;
this.dependencies = dependencies;
this.other_config = other_config;
this.subsystem_vendor_name = subsystem_vendor_name;
this.subsystem_device_name = subsystem_device_name;
}
/// <summary>
/// Creates a new PCI from a Proxy_PCI.
/// </summary>
/// <param name="proxy"></param>
public PCI(Proxy_PCI proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(PCI update)
{
uuid = update.uuid;
class_name = update.class_name;
vendor_name = update.vendor_name;
device_name = update.device_name;
host = update.host;
pci_id = update.pci_id;
dependencies = update.dependencies;
other_config = update.other_config;
subsystem_vendor_name = update.subsystem_vendor_name;
subsystem_device_name = update.subsystem_device_name;
}
internal void UpdateFromProxy(Proxy_PCI proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
class_name = proxy.class_name == null ? null : (string)proxy.class_name;
vendor_name = proxy.vendor_name == null ? null : (string)proxy.vendor_name;
device_name = proxy.device_name == null ? null : (string)proxy.device_name;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
pci_id = proxy.pci_id == null ? null : (string)proxy.pci_id;
dependencies = proxy.dependencies == null ? null : XenRef<PCI>.Create(proxy.dependencies);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
subsystem_vendor_name = proxy.subsystem_vendor_name == null ? null : (string)proxy.subsystem_vendor_name;
subsystem_device_name = proxy.subsystem_device_name == null ? null : (string)proxy.subsystem_device_name;
}
public Proxy_PCI ToProxy()
{
Proxy_PCI result_ = new Proxy_PCI();
result_.uuid = (uuid != null) ? uuid : "";
result_.class_name = (class_name != null) ? class_name : "";
result_.vendor_name = (vendor_name != null) ? vendor_name : "";
result_.device_name = (device_name != null) ? device_name : "";
result_.host = (host != null) ? host : "";
result_.pci_id = (pci_id != null) ? pci_id : "";
result_.dependencies = (dependencies != null) ? Helper.RefListToStringArray(dependencies) : new string[] {};
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.subsystem_vendor_name = (subsystem_vendor_name != null) ? subsystem_vendor_name : "";
result_.subsystem_device_name = (subsystem_device_name != null) ? subsystem_device_name : "";
return result_;
}
/// <summary>
/// Creates a new PCI from a Hashtable.
/// </summary>
/// <param name="table"></param>
public PCI(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
class_name = Marshalling.ParseString(table, "class_name");
vendor_name = Marshalling.ParseString(table, "vendor_name");
device_name = Marshalling.ParseString(table, "device_name");
host = Marshalling.ParseRef<Host>(table, "host");
pci_id = Marshalling.ParseString(table, "pci_id");
dependencies = Marshalling.ParseSetRef<PCI>(table, "dependencies");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
subsystem_vendor_name = Marshalling.ParseString(table, "subsystem_vendor_name");
subsystem_device_name = Marshalling.ParseString(table, "subsystem_device_name");
}
public bool DeepEquals(PCI other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._class_name, other._class_name) &&
Helper.AreEqual2(this._vendor_name, other._vendor_name) &&
Helper.AreEqual2(this._device_name, other._device_name) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._pci_id, other._pci_id) &&
Helper.AreEqual2(this._dependencies, other._dependencies) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._subsystem_vendor_name, other._subsystem_vendor_name) &&
Helper.AreEqual2(this._subsystem_device_name, other._subsystem_device_name);
}
public override string SaveChanges(Session session, string opaqueRef, PCI server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
PCI.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static PCI get_record(Session session, string _pci)
{
return new PCI((Proxy_PCI)session.proxy.pci_get_record(session.uuid, (_pci != null) ? _pci : "").parse());
}
/// <summary>
/// Get a reference to the PCI instance with the specified UUID.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PCI> get_by_uuid(Session session, string _uuid)
{
return XenRef<PCI>.Create(session.proxy.pci_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get the uuid field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_uuid(Session session, string _pci)
{
return (string)session.proxy.pci_get_uuid(session.uuid, (_pci != null) ? _pci : "").parse();
}
/// <summary>
/// Get the class_name field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_class_name(Session session, string _pci)
{
return (string)session.proxy.pci_get_class_name(session.uuid, (_pci != null) ? _pci : "").parse();
}
/// <summary>
/// Get the vendor_name field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_vendor_name(Session session, string _pci)
{
return (string)session.proxy.pci_get_vendor_name(session.uuid, (_pci != null) ? _pci : "").parse();
}
/// <summary>
/// Get the device_name field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_device_name(Session session, string _pci)
{
return (string)session.proxy.pci_get_device_name(session.uuid, (_pci != null) ? _pci : "").parse();
}
/// <summary>
/// Get the host field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static XenRef<Host> get_host(Session session, string _pci)
{
return XenRef<Host>.Create(session.proxy.pci_get_host(session.uuid, (_pci != null) ? _pci : "").parse());
}
/// <summary>
/// Get the pci_id field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_pci_id(Session session, string _pci)
{
return (string)session.proxy.pci_get_pci_id(session.uuid, (_pci != null) ? _pci : "").parse();
}
/// <summary>
/// Get the dependencies field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static List<XenRef<PCI>> get_dependencies(Session session, string _pci)
{
return XenRef<PCI>.Create(session.proxy.pci_get_dependencies(session.uuid, (_pci != null) ? _pci : "").parse());
}
/// <summary>
/// Get the other_config field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static Dictionary<string, string> get_other_config(Session session, string _pci)
{
return Maps.convert_from_proxy_string_string(session.proxy.pci_get_other_config(session.uuid, (_pci != null) ? _pci : "").parse());
}
/// <summary>
/// Get the subsystem_vendor_name field of the given PCI.
/// First published in XenServer 6.2 SP1 Hotfix 11.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_subsystem_vendor_name(Session session, string _pci)
{
return (string)session.proxy.pci_get_subsystem_vendor_name(session.uuid, (_pci != null) ? _pci : "").parse();
}
/// <summary>
/// Get the subsystem_device_name field of the given PCI.
/// First published in XenServer 6.2 SP1 Hotfix 11.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_subsystem_device_name(Session session, string _pci)
{
return (string)session.proxy.pci_get_subsystem_device_name(session.uuid, (_pci != null) ? _pci : "").parse();
}
/// <summary>
/// Set the other_config field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pci, Dictionary<string, string> _other_config)
{
session.proxy.pci_set_other_config(session.uuid, (_pci != null) ? _pci : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pci, string _key, string _value)
{
session.proxy.pci_add_to_other_config(session.uuid, (_pci != null) ? _pci : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given PCI. If the key is not in that Map, then do nothing.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pci, string _key)
{
session.proxy.pci_remove_from_other_config(session.uuid, (_pci != null) ? _pci : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Return a list of all the PCIs known to the system.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PCI>> get_all(Session session)
{
return XenRef<PCI>.Create(session.proxy.pci_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the PCI Records at once, in a single XML RPC call
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PCI>, PCI> get_all_records(Session session)
{
return XenRef<PCI>.Create<Proxy_PCI>(session.proxy.pci_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// PCI class name
/// </summary>
public virtual string class_name
{
get { return _class_name; }
set
{
if (!Helper.AreEqual(value, _class_name))
{
_class_name = value;
Changed = true;
NotifyPropertyChanged("class_name");
}
}
}
private string _class_name;
/// <summary>
/// Vendor name
/// </summary>
public virtual string vendor_name
{
get { return _vendor_name; }
set
{
if (!Helper.AreEqual(value, _vendor_name))
{
_vendor_name = value;
Changed = true;
NotifyPropertyChanged("vendor_name");
}
}
}
private string _vendor_name;
/// <summary>
/// Device name
/// </summary>
public virtual string device_name
{
get { return _device_name; }
set
{
if (!Helper.AreEqual(value, _device_name))
{
_device_name = value;
Changed = true;
NotifyPropertyChanged("device_name");
}
}
}
private string _device_name;
/// <summary>
/// Physical machine that owns the PCI device
/// </summary>
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host;
/// <summary>
/// PCI ID of the physical device
/// </summary>
public virtual string pci_id
{
get { return _pci_id; }
set
{
if (!Helper.AreEqual(value, _pci_id))
{
_pci_id = value;
Changed = true;
NotifyPropertyChanged("pci_id");
}
}
}
private string _pci_id;
/// <summary>
/// List of dependent PCI devices
/// </summary>
public virtual List<XenRef<PCI>> dependencies
{
get { return _dependencies; }
set
{
if (!Helper.AreEqual(value, _dependencies))
{
_dependencies = value;
Changed = true;
NotifyPropertyChanged("dependencies");
}
}
}
private List<XenRef<PCI>> _dependencies;
/// <summary>
/// Additional configuration
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
/// <summary>
/// Subsystem vendor name
/// First published in XenServer 6.2 SP1 Hotfix 11.
/// </summary>
public virtual string subsystem_vendor_name
{
get { return _subsystem_vendor_name; }
set
{
if (!Helper.AreEqual(value, _subsystem_vendor_name))
{
_subsystem_vendor_name = value;
Changed = true;
NotifyPropertyChanged("subsystem_vendor_name");
}
}
}
private string _subsystem_vendor_name;
/// <summary>
/// Subsystem device name
/// First published in XenServer 6.2 SP1 Hotfix 11.
/// </summary>
public virtual string subsystem_device_name
{
get { return _subsystem_device_name; }
set
{
if (!Helper.AreEqual(value, _subsystem_device_name))
{
_subsystem_device_name = value;
Changed = true;
NotifyPropertyChanged("subsystem_device_name");
}
}
}
private string _subsystem_device_name;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Streams;
namespace Orleans
{
/// <summary>
/// Client runtime for connecting to Orleans system
/// </summary>
/// TODO: Make this class non-static and inject it where it is needed.
public static class GrainClient
{
/// <summary>
/// Whether the client runtime has already been initialized
/// </summary>
/// <returns><c>true</c> if client runtime is already initialized</returns>
public static bool IsInitialized { get { return isFullyInitialized && RuntimeClient.Current != null; } }
internal static ClientConfiguration CurrentConfig { get; private set; }
internal static bool TestOnlyNoConnect { get; set; }
private static bool isFullyInitialized = false;
private static OutsideRuntimeClient outsideRuntimeClient;
private static readonly object initLock = new Object();
private static GrainFactory grainFactory;
// RuntimeClient.Current is set to something different than OutsideRuntimeClient - it can only be set to InsideRuntimeClient, since we only have 2.
// That means we are running in side a silo.
private static bool IsRunningInsideSilo { get { return RuntimeClient.Current != null && !(RuntimeClient.Current is OutsideRuntimeClient); } }
//TODO: prevent client code from using this from inside a Grain or provider
public static IGrainFactory GrainFactory
{
get
{
return GetGrainFactory();
}
}
private static IGrainFactory GetGrainFactory()
{
if (IsRunningInsideSilo)
{
// just in case, make sure we don't get NullRefExc when checking RuntimeContext.
bool runningInsideGrain = RuntimeContext.Current != null && RuntimeContext.CurrentActivationContext != null
&& RuntimeContext.CurrentActivationContext.ContextType == SchedulingContextType.Activation;
if (runningInsideGrain)
{
throw new OrleansException("You are running inside a grain. GrainClient.GrainFactory should only be used on the client side. " +
"Inside a grain use GrainFactory property of the Grain base class (use this.GrainFactory).");
}
else // running inside provider or else where
{
throw new OrleansException("You are running inside the provider code, on the silo. GrainClient.GrainFactory should only be used on the client side. " +
"Inside the provider code use GrainFactory that is passed via IProviderRuntime (use providerRuntime.GrainFactory).");
}
}
if (!IsInitialized)
{
throw new OrleansException("You must initialize the Grain Client before accessing the GrainFactory");
}
return grainFactory;
}
internal static GrainFactory InternalGrainFactory
{
get
{
if (!IsInitialized)
{
throw new OrleansException("You must initialize the Grain Client before accessing the InternalGrainFactory");
}
return grainFactory;
}
}
/// <summary>
/// Initializes the client runtime from the standard client configuration file.
/// </summary>
public static void Initialize()
{
ClientConfiguration config = ClientConfiguration.StandardLoad();
if (config == null)
{
Console.WriteLine("Error loading standard client configuration file.");
throw new ArgumentException("Error loading standard client configuration file");
}
InternalInitialize(config);
}
/// <summary>
/// Initializes the client runtime from the provided client configuration file.
/// If an error occurs reading the specified configuration file, the initialization fails.
/// </summary>
/// <param name="configFilePath">A relative or absolute pathname for the client configuration file.</param>
public static void Initialize(string configFilePath)
{
Initialize(new FileInfo(configFilePath));
}
/// <summary>
/// Initializes the client runtime from the provided client configuration file.
/// If an error occurs reading the specified configuration file, the initialization fails.
/// </summary>
/// <param name="configFile">The client configuration file.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static void Initialize(FileInfo configFile)
{
ClientConfiguration config;
try
{
config = ClientConfiguration.LoadFromFile(configFile.FullName);
}
catch (Exception ex)
{
Console.WriteLine("Error loading client configuration file {0}: {1}", configFile.FullName, ex);
throw;
}
if (config == null)
{
Console.WriteLine("Error loading client configuration file {0}:", configFile.FullName);
throw new ArgumentException(String.Format("Error loading client configuration file {0}:", configFile.FullName), "configFile");
}
InternalInitialize(config);
}
/// <summary>
/// Initializes the client runtime from the provided client configuration object.
/// If the configuration object is null, the initialization fails.
/// </summary>
/// <param name="config">A ClientConfiguration object.</param>
public static void Initialize(ClientConfiguration config)
{
if (config == null)
{
Console.WriteLine("Initialize was called with null ClientConfiguration object.");
throw new ArgumentException("Initialize was called with null ClientConfiguration object.", "config");
}
InternalInitialize(config);
}
/// <summary>
/// Initializes the client runtime from the standard client configuration file using the provided gateway address.
/// Any gateway addresses specified in the config file will be ignored and the provided gateway address wil be used instead.
/// </summary>
/// <param name="gatewayAddress">IP address and port of the gateway silo</param>
/// <param name="overrideConfig">Whether the specified gateway endpoint should override / replace the values from config file, or be additive</param>
public static void Initialize(IPEndPoint gatewayAddress, bool overrideConfig = true)
{
var config = ClientConfiguration.StandardLoad();
if (config == null)
{
Console.WriteLine("Error loading standard client configuration file.");
throw new ArgumentException("Error loading standard client configuration file");
}
if (overrideConfig)
{
config.Gateways = new List<IPEndPoint>(new[] { gatewayAddress });
}
else if (!config.Gateways.Contains(gatewayAddress))
{
config.Gateways.Add(gatewayAddress);
}
config.PreferedGatewayIndex = config.Gateways.IndexOf(gatewayAddress);
InternalInitialize(config);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void InternalInitialize(ClientConfiguration config, OutsideRuntimeClient runtimeClient = null)
{
// We deliberately want to run this initialization code on .NET thread pool thread to escape any
// TPL execution environment and avoid any conflicts with client's synchronization context
var tcs = new TaskCompletionSource<ClientConfiguration>();
WaitCallback doInit = state =>
{
try
{
if (TestOnlyNoConnect)
{
Trace.TraceInformation("TestOnlyNoConnect - Returning before connecting to cluster.");
}
else
{
// Finish initializing this client connection to the Orleans cluster
DoInternalInitialize(config, runtimeClient);
}
tcs.SetResult(config); // Resolve promise
}
catch (Exception exc)
{
tcs.SetException(exc); // Break promise
}
};
// Queue Init call to thread pool thread
ThreadPool.QueueUserWorkItem(doInit, null);
try
{
CurrentConfig = tcs.Task.Result; // Wait for Init to finish
}
catch (AggregateException ae)
{
// Flatten the aggregate exception, which can be deeply nested.
ae = ae.Flatten();
// If there is just one exception in the aggregate exception, throw that, otherwise throw the entire
// flattened aggregate exception.
var innerExceptions = ae.InnerExceptions;
var exceptionToThrow = innerExceptions.Count == 1 ? innerExceptions[0] : ae;
ExceptionDispatchInfo.Capture(exceptionToThrow).Throw();
}
}
/// <summary>
/// Initializes client runtime from client configuration object.
/// </summary>
private static void DoInternalInitialize(ClientConfiguration config, OutsideRuntimeClient runtimeClient = null)
{
if (IsInitialized)
return;
lock (initLock)
{
if (!IsInitialized)
{
try
{
// this is probably overkill, but this ensures isFullyInitialized false
// before we make a call that makes RuntimeClient.Current not null
isFullyInitialized = false;
grainFactory = new GrainFactory();
if (runtimeClient == null)
{
runtimeClient = new OutsideRuntimeClient(config, grainFactory);
}
outsideRuntimeClient = runtimeClient; // Keep reference, to avoid GC problems
outsideRuntimeClient.Start();
// this needs to be the last successful step inside the lock so
// IsInitialized doesn't return true until we're fully initialized
isFullyInitialized = true;
}
catch (Exception exc)
{
// just make sure to fully Uninitialize what we managed to partially initialize, so we don't end up in inconsistent state and can later on re-initialize.
Console.WriteLine("Initialization failed. {0}", exc);
InternalUninitialize();
throw;
}
}
}
}
/// <summary>
/// Uninitializes client runtime.
/// </summary>
public static void Uninitialize()
{
lock (initLock)
{
InternalUninitialize();
}
}
/// <summary>
/// Test hook to uninitialize client without cleanup
/// </summary>
public static void HardKill()
{
lock (initLock)
{
InternalUninitialize(false);
}
}
/// <summary>
/// This is the lock free version of uninitilize so we can share
/// it between the public method and error paths inside initialize.
/// This should only be called inside a lock(initLock) block.
/// </summary>
private static void InternalUninitialize(bool cleanup = true)
{
// Update this first so IsInitialized immediately begins returning
// false. Since this method should be protected externally by
// a lock(initLock) we should be able to reset everything else
// before the next init attempt.
isFullyInitialized = false;
if (RuntimeClient.Current != null)
{
try
{
RuntimeClient.Current.Reset(cleanup);
}
catch (Exception) { }
RuntimeClient.Current = null;
}
outsideRuntimeClient = null;
grainFactory = null;
ClientInvokeCallback = null;
}
/// <summary>
/// Check that the runtime is intialized correctly, and throw InvalidOperationException if not
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
private static void CheckInitialized()
{
if (!IsInitialized)
throw new InvalidOperationException("Runtime is not initialized. Call Client.Initialize method to initialize the runtime.");
}
/// <summary>
/// Provides logging facility for applications.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
public static Logger Logger
{
get
{
CheckInitialized();
return RuntimeClient.Current.AppLogger;
}
}
/// <summary>
/// Set a timeout for responses on this Orleans client.
/// </summary>
/// <param name="timeout"></param>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
public static void SetResponseTimeout(TimeSpan timeout)
{
CheckInitialized();
RuntimeClient.Current.SetResponseTimeout(timeout);
}
/// <summary>
/// Get a timeout of responses on this Orleans client.
/// </summary>
/// <returns>The response timeout.</returns>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
public static TimeSpan GetResponseTimeout()
{
CheckInitialized();
return RuntimeClient.Current.GetResponseTimeout();
}
/// <summary>
/// Global pre-call interceptor function
/// Synchronous callback made just before a message is about to be constructed and sent by a client to a grain.
/// This call will be made from the same thread that constructs the message to be sent, so any thread-local settings
/// such as <c>Orleans.RequestContext</c> will be picked up.
/// The action receives an <see cref="InvokeMethodRequest"/> with details of the method to be invoked, including InterfaceId and MethodId,
/// and a <see cref="IGrain"/> which is the GrainReference this request is being sent through
/// </summary>
/// <remarks>This callback method should return promptly and do a minimum of work, to avoid blocking calling thread or impacting throughput.</remarks>
public static Action<InvokeMethodRequest, IGrain> ClientInvokeCallback { get; set; }
public static IEnumerable<Streams.IStreamProvider> GetStreamProviders()
{
return RuntimeClient.Current.CurrentStreamProviderManager.GetStreamProviders();
}
internal static IStreamProviderRuntime CurrentStreamProviderRuntime
{
get { return RuntimeClient.Current.CurrentStreamProviderRuntime; }
}
public static Streams.IStreamProvider GetStreamProvider(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException("name");
return RuntimeClient.Current.CurrentStreamProviderManager.GetProvider(name) as Streams.IStreamProvider;
}
internal static IList<Uri> Gateways
{
get
{
CheckInitialized();
return outsideRuntimeClient.Gateways;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>BillingSetup</c> resource.</summary>
public sealed partial class BillingSetupName : gax::IResourceName, sys::IEquatable<BillingSetupName>
{
/// <summary>The possible contents of <see cref="BillingSetupName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/billingSetups/{billing_setup_id}</c>.
/// </summary>
CustomerBillingSetup = 1,
}
private static gax::PathTemplate s_customerBillingSetup = new gax::PathTemplate("customers/{customer_id}/billingSetups/{billing_setup_id}");
/// <summary>Creates a <see cref="BillingSetupName"/> 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="BillingSetupName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static BillingSetupName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new BillingSetupName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="BillingSetupName"/> with the pattern
/// <c>customers/{customer_id}/billingSetups/{billing_setup_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="billingSetupId">The <c>BillingSetup</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="BillingSetupName"/> constructed from the provided ids.</returns>
public static BillingSetupName FromCustomerBillingSetup(string customerId, string billingSetupId) =>
new BillingSetupName(ResourceNameType.CustomerBillingSetup, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), billingSetupId: gax::GaxPreconditions.CheckNotNullOrEmpty(billingSetupId, nameof(billingSetupId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BillingSetupName"/> with pattern
/// <c>customers/{customer_id}/billingSetups/{billing_setup_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="billingSetupId">The <c>BillingSetup</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BillingSetupName"/> with pattern
/// <c>customers/{customer_id}/billingSetups/{billing_setup_id}</c>.
/// </returns>
public static string Format(string customerId, string billingSetupId) =>
FormatCustomerBillingSetup(customerId, billingSetupId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BillingSetupName"/> with pattern
/// <c>customers/{customer_id}/billingSetups/{billing_setup_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="billingSetupId">The <c>BillingSetup</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BillingSetupName"/> with pattern
/// <c>customers/{customer_id}/billingSetups/{billing_setup_id}</c>.
/// </returns>
public static string FormatCustomerBillingSetup(string customerId, string billingSetupId) =>
s_customerBillingSetup.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(billingSetupId, nameof(billingSetupId)));
/// <summary>Parses the given resource name string into a new <see cref="BillingSetupName"/> 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}/billingSetups/{billing_setup_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="billingSetupName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="BillingSetupName"/> if successful.</returns>
public static BillingSetupName Parse(string billingSetupName) => Parse(billingSetupName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="BillingSetupName"/> 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}/billingSetups/{billing_setup_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="billingSetupName">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="BillingSetupName"/> if successful.</returns>
public static BillingSetupName Parse(string billingSetupName, bool allowUnparsed) =>
TryParse(billingSetupName, allowUnparsed, out BillingSetupName 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="BillingSetupName"/> 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}/billingSetups/{billing_setup_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="billingSetupName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BillingSetupName"/>, 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 billingSetupName, out BillingSetupName result) =>
TryParse(billingSetupName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BillingSetupName"/> 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}/billingSetups/{billing_setup_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="billingSetupName">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="BillingSetupName"/>, 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 billingSetupName, bool allowUnparsed, out BillingSetupName result)
{
gax::GaxPreconditions.CheckNotNull(billingSetupName, nameof(billingSetupName));
gax::TemplatedResourceName resourceName;
if (s_customerBillingSetup.TryParseName(billingSetupName, out resourceName))
{
result = FromCustomerBillingSetup(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(billingSetupName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private BillingSetupName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string billingSetupId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
BillingSetupId = billingSetupId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="BillingSetupName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/billingSetups/{billing_setup_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="billingSetupId">The <c>BillingSetup</c> ID. Must not be <c>null</c> or empty.</param>
public BillingSetupName(string customerId, string billingSetupId) : this(ResourceNameType.CustomerBillingSetup, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), billingSetupId: gax::GaxPreconditions.CheckNotNullOrEmpty(billingSetupId, nameof(billingSetupId)))
{
}
/// <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>BillingSetup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string BillingSetupId { 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>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.CustomerBillingSetup: return s_customerBillingSetup.Expand(CustomerId, BillingSetupId);
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 BillingSetupName);
/// <inheritdoc/>
public bool Equals(BillingSetupName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(BillingSetupName a, BillingSetupName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(BillingSetupName a, BillingSetupName b) => !(a == b);
}
public partial class BillingSetup
{
/// <summary>
/// <see cref="BillingSetupName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal BillingSetupName ResourceNameAsBillingSetupName
{
get => string.IsNullOrEmpty(ResourceName) ? null : BillingSetupName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="PaymentsAccountName"/>-typed view over the <see cref="PaymentsAccount"/> resource name property.
/// </summary>
internal PaymentsAccountName PaymentsAccountAsPaymentsAccountName
{
get => string.IsNullOrEmpty(PaymentsAccount) ? null : PaymentsAccountName.Parse(PaymentsAccount, allowUnparsed: true);
set => PaymentsAccount = value?.ToString() ?? "";
}
}
}
| |
//
// LabelBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using AppKit;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using Xwt.Backends;
namespace Xwt.Mac
{
public class LabelBackend: ViewBackend<NSView,IWidgetEventSink>, ILabelBackend
{
public LabelBackend () : this (new TextFieldView ())
{
}
protected LabelBackend (IViewObject view)
{
View = view;
view.Backend = this;
}
IViewObject View;
public override void Initialize ()
{
ViewObject = new CustomAlignedContainer (EventSink, ApplicationContext, (NSView)View);
CanGetFocus = false;
Widget.StringValue = string.Empty;
Widget.Editable = false;
Widget.Bezeled = false;
Widget.DrawsBackground = false;
Widget.BackgroundColor = NSColor.Clear;
Wrap = WrapMode.None;
Container.ExpandVertically = true;
Widget.Cell.Scrollable = false;
}
public override Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint)
{
var r = new CGRect (0, 0, widthConstraint.IsConstrained ? (float)widthConstraint.AvailableSize : float.MaxValue, heightConstraint.IsConstrained ? (float)heightConstraint.AvailableSize : float.MaxValue);
var s = Widget.Cell.CellSizeForBounds (r);
return new Size (s.Width, s.Height);
}
CustomAlignedContainer Container {
get { return (CustomAlignedContainer)base.Widget; }
}
public new NSTextField Widget {
get { return (NSTextField) Container.Child; }
}
public virtual string Text {
get {
return Widget.StringValue;
}
set {
Widget.StringValue = value ?? string.Empty;
ResetFittingSize ();
}
}
public bool Selectable {
get { return Widget.Selectable; }
set { Widget.Selectable = value; }
}
public void SetFormattedText (FormattedText text)
{
// HACK: wrapping needs to be enabled in order to display Attributed string correctly on Mac
if (Wrap == WrapMode.None)
Wrap = WrapMode.Character;
Widget.AllowsEditingTextAttributes = true;
if (TextAlignment == Alignment.Start)
Widget.AttributedStringValue = text.ToAttributedString ();
else
Widget.AttributedStringValue = text.ToAttributedString ().WithAlignment (Widget.Alignment);
ResetFittingSize ();
}
public Xwt.Drawing.Color TextColor {
get { return Widget.TextColor.ToXwtColor (); }
set { Widget.TextColor = value.ToNSColor (); }
}
public Alignment TextAlignment {
get {
return Widget.Alignment.ToAlignment ();
}
set {
Widget.Alignment = value.ToNSTextAlignment ();
if (Widget.AttributedStringValue != null)
Widget.AttributedStringValue = (Widget.AttributedStringValue.MutableCopy () as NSMutableAttributedString).WithAlignment (Widget.Alignment);
}
}
public EllipsizeMode Ellipsize {
get {
switch (Widget.Cell.LineBreakMode) {
case NSLineBreakMode.TruncatingHead: return Xwt.EllipsizeMode.Start;
case NSLineBreakMode.TruncatingMiddle: return Xwt.EllipsizeMode.Middle;
case NSLineBreakMode.TruncatingTail: return Xwt.EllipsizeMode.End;
default: return Xwt.EllipsizeMode.None;
}
}
set {
switch (value) {
case Xwt.EllipsizeMode.None: Widget.Cell.LineBreakMode = NSLineBreakMode.Clipping; break;
case Xwt.EllipsizeMode.Start: Widget.Cell.LineBreakMode = NSLineBreakMode.TruncatingHead; break;
case Xwt.EllipsizeMode.Middle: Widget.Cell.LineBreakMode = NSLineBreakMode.TruncatingMiddle; break;
case Xwt.EllipsizeMode.End: Widget.Cell.LineBreakMode = NSLineBreakMode.TruncatingTail; break;
}
}
}
public override Xwt.Drawing.Color BackgroundColor {
get { return Widget.BackgroundColor.ToXwtColor (); }
set {
Widget.BackgroundColor = value.ToNSColor ();
((TextFieldView)Widget).SetBackgroundColor (value.ToCGColor ());
}
}
// FIXME: technically not possible if we keep NSTextField
// as the backend because it's one-line only
public WrapMode Wrap {
get {
if (!Widget.Cell.Wraps)
return WrapMode.None;
switch (Widget.Cell.LineBreakMode) {
case NSLineBreakMode.ByWordWrapping:
return WrapMode.Word;
case NSLineBreakMode.CharWrapping:
return WrapMode.Character;
default:
return WrapMode.None;
}
}
set {
if (value == WrapMode.None) {
Widget.Cell.Wraps = false;
Widget.Cell.UsesSingleLineMode = false; //Bug in monomac causes single line mode to display with incorrect vertical alignment
} else {
Widget.Cell.Wraps = true;
Widget.Cell.UsesSingleLineMode = false;
switch (value) {
case WrapMode.Word:
case WrapMode.WordAndCharacter:
Widget.Cell.LineBreakMode = NSLineBreakMode.ByWordWrapping;
break;
case WrapMode.Character:
Widget.Cell.LineBreakMode = NSLineBreakMode.CharWrapping;
break;
}
}
}
}
}
public class CustomAlignedContainer: WidgetView
{
public NSView Child;
public CustomAlignedContainer (IWidgetEventSink eventSink, ApplicationContext context, NSView child) : base (eventSink, context)
{
Child = child;
AddSubview (child);
UpdateTextFieldFrame ();
}
static readonly Selector sizeToFitSel = new Selector ("sizeToFit");
public void SizeToFit ()
{
if (Child.RespondsToSelector (sizeToFitSel))
Messaging.void_objc_msgSend (Child.Handle, sizeToFitSel.Handle);
else
throw new NotSupportedException ();
Frame = new CGRect (Frame.X, Frame.Y, Child.Frame.Width, Child.Frame.Height);
}
bool expandVertically;
public bool ExpandVertically {
get {
return expandVertically;
}
set {
expandVertically = value;
UpdateTextFieldFrame ();
}
}
public override void SetFrameSize (CGSize newSize)
{
base.SetFrameSize (newSize);
UpdateTextFieldFrame ();
}
void UpdateTextFieldFrame ()
{
if (expandVertically)
Child.Frame = new CGRect (0, 0, Frame.Width, Frame.Height);
else {
Child.Frame = new CGRect (0, (Frame.Height - Child.Frame.Height) / 2, Frame.Width, Child.Frame.Height);
}
Child.NeedsDisplay = true;
}
public override bool AcceptsFirstResponder()
{
return false;
}
}
class TextFieldView: NSTextField, IViewObject
{
public override CGRect Frame {
get { return base.Frame; }
set {
base.Frame = value;
this.StringValue = this.StringValue;
}
}
CustomTextFieldCell cell;
public ViewBackend Backend { get; set; }
public NSView View {
get { return this; }
}
public TextFieldView ()
{
Cell = cell = new CustomTextFieldCell ();
AccessibilityRole = NSAccessibilityRoles.StaticTextRole;
}
public void SetBackgroundColor (CGColor c)
{
cell.SetBackgroundColor (c);
}
public override bool AcceptsFirstResponder ()
{
return false;
}
public override bool AllowsVibrancy {
get {
// we don't support vibrancy
if (EffectiveAppearance.AllowsVibrancy)
return false;
return base.AllowsVibrancy;
}
}
}
class CustomTextFieldCell: NSTextFieldCell
{
CGColor bgColor;
public CustomTextFieldCell ()
{
}
protected CustomTextFieldCell (IntPtr ptr) : base (ptr)
{
}
/// <summary>
/// Like what happens for the ios designer, AppKit can sometimes clone the native `NSTextFieldCell` using the Copy (NSZone)
/// method. We *need* to ensure we can create a new managed wrapper for the cloned native object so we need the IntPtr
/// constructor. NOTE: By keeping this override in managed we ensure the new wrapper C# object is created ~immediately,
/// which makes it easier to debug issues.
/// </summary>
/// <returns>The copy.</returns>
/// <param name="zone">Zone.</param>
public override NSObject Copy(NSZone zone)
{
// Don't remove this override because the comment on this explains why we need this!
var newCell = (CustomTextFieldCell)base.Copy(zone);
newCell.bgColor = bgColor;
return newCell;
}
public void SetBackgroundColor (CGColor c)
{
bgColor = c;
DrawsBackground = true;
}
public override CGRect TitleRectForBounds (CGRect theRect)
{
var rect = base.TitleRectForBounds (theRect);
var textSize = CellSizeForBounds (theRect);
nfloat dif = rect.Height - textSize.Height;
if (dif > 0) {
rect.Height -= dif;
rect.Y += (dif / 2);
}
return rect;
}
public override void DrawInteriorWithFrame (CGRect cellFrame, NSView inView)
{
if (DrawsBackground) {
CGContext ctx = NSGraphicsContext.CurrentContext.GraphicsPort;
ctx.AddRect (cellFrame);
ctx.SetFillColorSpace (Util.DeviceRGBColorSpace);
ctx.SetStrokeColorSpace (Util.DeviceRGBColorSpace);
ctx.SetFillColor (bgColor);
ctx.DrawPath (CGPathDrawingMode.Fill);
}
base.DrawInteriorWithFrame (TitleRectForBounds (cellFrame), inView);
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public class PartialViewResultExecutorTest
{
[Fact]
public void FindView_UsesViewEngine_FromPartialViewResult()
{
// Arrange
var context = GetActionContext();
var executor = GetViewExecutor();
var viewName = "my-view";
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(e => e.GetView(/*executingFilePath*/ null, viewName, /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound(viewName, Enumerable.Empty<string>()))
.Verifiable();
viewEngine
.Setup(e => e.FindView(context, viewName, /*isMainPage*/ false))
.Returns(ViewEngineResult.Found(viewName, Mock.Of<IView>()))
.Verifiable();
var viewResult = new PartialViewResult
{
ViewEngine = viewEngine.Object,
ViewName = viewName,
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
TempData = Mock.Of<ITempDataDictionary>(),
};
// Act
var viewEngineResult = executor.FindView(context, viewResult);
// Assert
Assert.Equal(viewName, viewEngineResult.ViewName);
viewEngine.Verify();
}
[Fact]
public void FindView_UsesActionDescriptorName_IfViewNameIsNull()
{
// Arrange
var viewName = "some-view-name";
var context = GetActionContext(viewName);
var executor = GetViewExecutor();
var viewResult = new PartialViewResult
{
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
TempData = Mock.Of<ITempDataDictionary>(),
};
// Act
var viewEngineResult = executor.FindView(context, viewResult);
// Assert
Assert.Equal(viewName, viewEngineResult.ViewName);
}
[Fact]
[ReplaceCulture("de-CH", "de-CH")]
public void FindView_UsesActionDescriptorName_IfViewNameIsNull_UsesInvariantCulture()
{
// Arrange
var viewName = "10/31/2018 07:37:38 -07:00";
var context = GetActionContext(viewName);
context.RouteData.Values["action"] = new DateTimeOffset(2018, 10, 31, 7, 37, 38, TimeSpan.FromHours(-7));
var executor = GetViewExecutor();
var viewResult = new PartialViewResult
{
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
TempData = Mock.Of<ITempDataDictionary>(),
};
// Act
var viewEngineResult = executor.FindView(context, viewResult);
// Assert
Assert.Equal(viewName, viewEngineResult.ViewName);
}
[Fact]
public void FindView_ReturnsExpectedNotFoundResult_WithGetViewLocations()
{
// Arrange
var expectedLocations = new[] { "location1", "location2" };
var context = GetActionContext();
var executor = GetViewExecutor();
var viewName = "myview";
var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(e => e.GetView(/*executingFilePath*/ null, "myview", /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("myview", expectedLocations))
.Verifiable();
viewEngine
.Setup(e => e.FindView(context, "myview", /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("myview", Enumerable.Empty<string>()));
var viewResult = new PartialViewResult
{
ViewName = viewName,
ViewEngine = viewEngine.Object,
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
TempData = Mock.Of<ITempDataDictionary>(),
};
// Act
var result = executor.FindView(context, viewResult);
// Assert
Assert.False(result.Success);
Assert.Null(result.View);
Assert.Equal(expectedLocations, result.SearchedLocations);
}
[Fact]
public void FindView_ReturnsExpectedNotFoundResult_WithFindViewLocations()
{
// Arrange
var expectedLocations = new[] { "location1", "location2" };
var context = GetActionContext();
var executor = GetViewExecutor();
var viewName = "myview";
var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(e => e.GetView(/*executingFilePath*/ null, "myview", /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("myview", Enumerable.Empty<string>()))
.Verifiable();
viewEngine
.Setup(e => e.FindView(context, "myview", /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("myview", expectedLocations));
var viewResult = new PartialViewResult
{
ViewName = viewName,
ViewEngine = viewEngine.Object,
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
TempData = Mock.Of<ITempDataDictionary>(),
};
// Act
var result = executor.FindView(context, viewResult);
// Assert
Assert.False(result.Success);
Assert.Null(result.View);
Assert.Equal(expectedLocations, result.SearchedLocations);
}
[Fact]
public void FindView_ReturnsExpectedNotFoundResult_WithAllLocations()
{
// Arrange
var expectedLocations = new[] { "location1", "location2", "location3", "location4" };
var context = GetActionContext();
var executor = GetViewExecutor();
var viewName = "myview";
var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(e => e.GetView(/*executingFilePath*/ null, "myview", /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("myview", new[] { "location1", "location2" }))
.Verifiable();
viewEngine
.Setup(e => e.FindView(context, "myview", /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("myview", new[] { "location3", "location4" }));
var viewResult = new PartialViewResult
{
ViewName = viewName,
ViewEngine = viewEngine.Object,
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
TempData = Mock.Of<ITempDataDictionary>(),
};
// Act
var result = executor.FindView(context, viewResult);
// Assert
Assert.False(result.Success);
Assert.Null(result.View);
Assert.Equal(expectedLocations, result.SearchedLocations);
}
[Fact]
public void FindView_WritesDiagnostic_ViewFound()
{
// Arrange
var diagnosticListener = new DiagnosticListener("Test");
var listener = new TestDiagnosticListener();
diagnosticListener.SubscribeWithAdapter(listener);
var context = GetActionContext();
var executor = GetViewExecutor(diagnosticListener);
var viewName = "myview";
var viewResult = new PartialViewResult
{
ViewName = viewName,
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
TempData = Mock.Of<ITempDataDictionary>(),
};
// Act
var viewEngineResult = executor.FindView(context, viewResult);
// Assert
Assert.Equal(viewName, viewEngineResult.ViewName);
Assert.NotNull(listener.ViewFound);
Assert.NotNull(listener.ViewFound.ActionContext);
Assert.NotNull(listener.ViewFound.Result);
Assert.NotNull(listener.ViewFound.View);
Assert.False(listener.ViewFound.IsMainPage);
Assert.Equal("myview", listener.ViewFound.ViewName);
}
[Fact]
public void FindView_WritesDiagnostic_ViewNotFound()
{
// Arrange
var diagnosticListener = new DiagnosticListener("Test");
var listener = new TestDiagnosticListener();
diagnosticListener.SubscribeWithAdapter(listener);
var context = GetActionContext();
var executor = GetViewExecutor(diagnosticListener);
var viewName = "myview";
var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(e => e.GetView(/*executingFilePath*/ null, "myview", /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("myview", Enumerable.Empty<string>()))
.Verifiable();
viewEngine
.Setup(e => e.FindView(context, "myview", /*isMainPage*/ false))
.Returns(ViewEngineResult.NotFound("myview", new string[] { "location/myview" }));
var viewResult = new PartialViewResult
{
ViewName = viewName,
ViewEngine = viewEngine.Object,
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
TempData = Mock.Of<ITempDataDictionary>(),
};
// Act
var viewEngineResult = executor.FindView(context, viewResult);
// Assert
Assert.False(viewEngineResult.Success);
Assert.NotNull(listener.ViewNotFound);
Assert.NotNull(listener.ViewNotFound.ActionContext);
Assert.NotNull(listener.ViewNotFound.Result);
Assert.Equal(new string[] { "location/myview" }, listener.ViewNotFound.SearchedLocations);
Assert.Equal("myview", listener.ViewNotFound.ViewName);
}
[Fact]
public async Task ExecuteAsync_UsesContentType_FromPartialViewResult()
{
// Arrange
var context = GetActionContext();
var executor = GetViewExecutor();
var contentType = "application/x-my-content-type";
var viewResult = new PartialViewResult
{
ViewName = "my-view",
ContentType = contentType,
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
TempData = Mock.Of<ITempDataDictionary>(),
};
// Act
await executor.ExecuteAsync(context, Mock.Of<IView>(), viewResult);
// Assert
Assert.Equal("application/x-my-content-type", context.HttpContext.Response.ContentType);
// Check if the original instance provided by the user has not changed.
// Since we do not have access to the new instance created within the view executor,
// check if at least the content is the same.
Assert.Null(MediaType.GetEncoding(contentType));
}
[Fact]
public async Task ExecuteAsync_UsesStatusCode_FromPartialViewResult()
{
// Arrange
var context = GetActionContext();
var executor = GetViewExecutor();
var contentType = MediaTypeHeaderValue.Parse("application/x-my-content-type");
var viewResult = new PartialViewResult
{
ViewName = "my-view",
StatusCode = 404,
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()),
TempData = Mock.Of<ITempDataDictionary>(),
};
// Act
await executor.ExecuteAsync(context, Mock.Of<IView>(), viewResult);
// Assert
Assert.Equal(404, context.HttpContext.Response.StatusCode);
}
private ActionContext GetActionContext(string actionName = null)
{
var routeData = new RouteData();
routeData.Values["action"] = actionName;
return new ActionContext(new DefaultHttpContext(), routeData, new ControllerActionDescriptor() { ActionName = actionName });
}
private PartialViewResultExecutor GetViewExecutor(DiagnosticListener diagnosticListener = null)
{
if (diagnosticListener == null)
{
diagnosticListener = new DiagnosticListener("Test");
}
var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(e => e.GetView(/*executingFilePath*/ null, It.IsAny<string>(), /*isMainPage*/ false))
.Returns<string, string, bool>(
(executing, name, isMainPage) => ViewEngineResult.NotFound(name, Enumerable.Empty<string>()));
viewEngine
.Setup(e => e.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ false))
.Returns<ActionContext, string, bool>(
(context, name, isMainPage) => ViewEngineResult.Found(name, Mock.Of<IView>()));
var options = Options.Create(new MvcViewOptions());
options.Value.ViewEngines.Add(viewEngine.Object);
var viewExecutor = new PartialViewResultExecutor(
options,
new TestHttpResponseStreamWriterFactory(),
new CompositeViewEngine(options),
Mock.Of<ITempDataDictionaryFactory>(),
diagnosticListener,
NullLoggerFactory.Instance,
new EmptyModelMetadataProvider());
return viewExecutor;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcdv = Google.Cloud.Dialogflow.V2;
using sys = System;
namespace Google.Cloud.Dialogflow.V2
{
/// <summary>Resource name for the <c>Fulfillment</c> resource.</summary>
public sealed partial class FulfillmentName : gax::IResourceName, sys::IEquatable<FulfillmentName>
{
/// <summary>The possible contents of <see cref="FulfillmentName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/agent/fulfillment</c>.</summary>
Project = 1,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/agent/fulfillment</c>.
/// </summary>
ProjectLocation = 2,
}
private static gax::PathTemplate s_project = new gax::PathTemplate("projects/{project}/agent/fulfillment");
private static gax::PathTemplate s_projectLocation = new gax::PathTemplate("projects/{project}/locations/{location}/agent/fulfillment");
/// <summary>Creates a <see cref="FulfillmentName"/> 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="FulfillmentName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static FulfillmentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new FulfillmentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="FulfillmentName"/> with the pattern <c>projects/{project}/agent/fulfillment</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="FulfillmentName"/> constructed from the provided ids.</returns>
public static FulfillmentName FromProject(string projectId) =>
new FulfillmentName(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>
/// Creates a <see cref="FulfillmentName"/> with the pattern
/// <c>projects/{project}/locations/{location}/agent/fulfillment</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="FulfillmentName"/> constructed from the provided ids.</returns>
public static FulfillmentName FromProjectLocation(string projectId, string locationId) =>
new FulfillmentName(ResourceNameType.ProjectLocation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FulfillmentName"/> with pattern
/// <c>projects/{project}/agent/fulfillment</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FulfillmentName"/> with pattern
/// <c>projects/{project}/agent/fulfillment</c>.
/// </returns>
public static string Format(string projectId) => FormatProject(projectId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FulfillmentName"/> with pattern
/// <c>projects/{project}/agent/fulfillment</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FulfillmentName"/> with pattern
/// <c>projects/{project}/agent/fulfillment</c>.
/// </returns>
public static string FormatProject(string projectId) =>
s_project.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FulfillmentName"/> with pattern
/// <c>projects/{project}/locations/{location}/agent/fulfillment</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FulfillmentName"/> with pattern
/// <c>projects/{project}/locations/{location}/agent/fulfillment</c>.
/// </returns>
public static string FormatProjectLocation(string projectId, string locationId) =>
s_projectLocation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)));
/// <summary>Parses the given resource name string into a new <see cref="FulfillmentName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/agent/fulfillment</c></description></item>
/// <item><description><c>projects/{project}/locations/{location}/agent/fulfillment</c></description></item>
/// </list>
/// </remarks>
/// <param name="fulfillmentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="FulfillmentName"/> if successful.</returns>
public static FulfillmentName Parse(string fulfillmentName) => Parse(fulfillmentName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="FulfillmentName"/> 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>projects/{project}/agent/fulfillment</c></description></item>
/// <item><description><c>projects/{project}/locations/{location}/agent/fulfillment</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="fulfillmentName">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="FulfillmentName"/> if successful.</returns>
public static FulfillmentName Parse(string fulfillmentName, bool allowUnparsed) =>
TryParse(fulfillmentName, allowUnparsed, out FulfillmentName 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="FulfillmentName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/agent/fulfillment</c></description></item>
/// <item><description><c>projects/{project}/locations/{location}/agent/fulfillment</c></description></item>
/// </list>
/// </remarks>
/// <param name="fulfillmentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="FulfillmentName"/>, 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 fulfillmentName, out FulfillmentName result) =>
TryParse(fulfillmentName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="FulfillmentName"/> 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>projects/{project}/agent/fulfillment</c></description></item>
/// <item><description><c>projects/{project}/locations/{location}/agent/fulfillment</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="fulfillmentName">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="FulfillmentName"/>, 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 fulfillmentName, bool allowUnparsed, out FulfillmentName result)
{
gax::GaxPreconditions.CheckNotNull(fulfillmentName, nameof(fulfillmentName));
gax::TemplatedResourceName resourceName;
if (s_project.TryParseName(fulfillmentName, out resourceName))
{
result = FromProject(resourceName[0]);
return true;
}
if (s_projectLocation.TryParseName(fulfillmentName, out resourceName))
{
result = FromProjectLocation(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(fulfillmentName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private FulfillmentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="FulfillmentName"/> class from the component parts of pattern
/// <c>projects/{project}/agent/fulfillment</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
public FulfillmentName(string projectId) : this(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)))
{
}
/// <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>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { 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.Project: return s_project.Expand(ProjectId);
case ResourceNameType.ProjectLocation: return s_projectLocation.Expand(ProjectId, LocationId);
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 FulfillmentName);
/// <inheritdoc/>
public bool Equals(FulfillmentName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(FulfillmentName a, FulfillmentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(FulfillmentName a, FulfillmentName b) => !(a == b);
}
public partial class Fulfillment
{
/// <summary>
/// <see cref="gcdv::FulfillmentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::FulfillmentName FulfillmentName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::FulfillmentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetFulfillmentRequest
{
/// <summary>
/// <see cref="gcdv::FulfillmentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::FulfillmentName FulfillmentName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::FulfillmentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Serialization.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Akka.Actor;
using Akka.Util.Internal;
namespace Akka.Serialization
{
public class Information
{
public Address Address { get; set; }
public ActorSystem System { get; set; }
}
public class Serialization
{
[ThreadStatic]
private static Information _currentTransportInformation;
public static T SerializeWithTransport<T>(ActorSystem system, Address address, Func<T> action)
{
_currentTransportInformation = new Information()
{
System = system,
Address = address
};
var res = action();
_currentTransportInformation = null;
return res;
}
private readonly Serializer _nullSerializer;
private readonly Dictionary<Type, Serializer> _serializerMap = new Dictionary<Type, Serializer>();
private readonly Dictionary<int, Serializer> _serializers = new Dictionary<int, Serializer>();
public Serialization(ExtendedActorSystem system)
{
System = system;
_nullSerializer = new NullSerializer(system);
_serializers.Add(_nullSerializer.Identifier, _nullSerializer);
var serializersConfig = system.Settings.Config.GetConfig("akka.actor.serializers").AsEnumerable().ToList();
var serializerBindingConfig = system.Settings.Config.GetConfig("akka.actor.serialization-bindings").AsEnumerable().ToList();
var namedSerializers = new Dictionary<string, Serializer>();
foreach (var kvp in serializersConfig)
{
var serializerTypeName = kvp.Value.GetString();
var serializerType = Type.GetType(serializerTypeName);
if (serializerType == null)
{
system.Log.Warning("The type name for serializer '{0}' did not resolve to an actual Type: '{1}'", kvp.Key, serializerTypeName);
continue;
}
var serializer = (Serializer)Activator.CreateInstance(serializerType, system);
_serializers.Add(serializer.Identifier, serializer);
namedSerializers.Add(kvp.Key, serializer);
}
foreach (var kvp in serializerBindingConfig)
{
var typename = kvp.Key;
var serializerName = kvp.Value.GetString();
var messageType = Type.GetType(typename);
if (messageType == null)
{
system.Log.Warning("The type name for message/serializer binding '{0}' did not resolve to an actual Type: '{1}'", serializerName, typename);
continue;
}
Serializer serializer;
if (!namedSerializers.TryGetValue(serializerName, out serializer))
{
system.Log.Warning("Serialization binding to non existing serializer: '{0}'", serializerName);
continue;
}
_serializerMap.Add(messageType, serializer);
}
}
public ActorSystem System { get; private set; }
public void AddSerializer(Serializer serializer)
{
_serializers.Add(serializer.Identifier, serializer);
}
public void AddSerializationMap(Type type, Serializer serializer)
{
_serializerMap.Add(type, serializer);
}
/// <summary></summary>
/// <exception cref="SerializationException">
/// This exception is thrown if the system cannot find the serializer with the given <paramref name="serializerId"/>.
/// </exception>
public object Deserialize(byte[] bytes, int serializerId, Type type)
{
Serializer serializer;
if (!_serializers.TryGetValue(serializerId, out serializer))
throw new SerializationException(
$"Cannot find serializer with id [{serializerId}]. The most probable reason" +
" is that the configuration entry 'akka.actor.serializers' is not in sync between the two systems.");
return serializer.FromBinary(bytes, type);
}
/// <summary></summary>
/// <exception cref="SerializationException">
/// This exception is thrown if the system cannot find the serializer with the given <paramref name="serializerId"/>
/// or it couldn't find the given <paramref name="manifest"/> with the given <paramref name="serializerId"/>.
/// </exception>
public object Deserialize(byte[] bytes, int serializerId, string manifest)
{
Serializer serializer;
if (!_serializers.TryGetValue(serializerId, out serializer))
throw new SerializationException(
$"Cannot find serializer with id [{serializerId}]. The most probable reason" +
" is that the configuration entry 'akka.actor.serializers' is not in sync between the two systems.");
if (serializer is SerializerWithStringManifest)
return ((SerializerWithStringManifest)serializer).FromBinary(bytes, manifest);
if (string.IsNullOrEmpty(manifest))
return serializer.FromBinary(bytes, null);
Type type;
try
{
type = Type.GetType(manifest);
}
catch
{
throw new SerializationException($"Cannot find manifest class [{manifest}] for serializer with id [{serializerId}].");
}
return serializer.FromBinary(bytes, type);
}
public Serializer FindSerializerFor(object obj)
{
if (obj == null)
return _nullSerializer;
Type type = obj.GetType();
return FindSerializerForType(type);
}
//cache to eliminate lots of typeof operator calls
private readonly Type _objectType = typeof(object);
/// <summary></summary>
/// <exception cref="SerializationException">
/// This exception is thrown if the serializer of the given <paramref name="objectType"/> could not be found.
/// </exception>
public Serializer FindSerializerForType(Type objectType)
{
Type type = objectType;
//TODO: see if we can do a better job with proper type sorting here - most specific to least specific (object serializer goes last)
foreach (var serializerType in _serializerMap)
{
//force deferral of the base "object" serializer until all other higher-level types have been evaluated
if (serializerType.Key.IsAssignableFrom(type) && serializerType.Key != _objectType)
return serializerType.Value;
}
//do a final check for the "object" serializer
if (_serializerMap.ContainsKey(_objectType) && _objectType.IsAssignableFrom(type))
return _serializerMap[_objectType];
throw new SerializationException($"Serializer not found for type {objectType.Name}");
}
public static string SerializedActorPath(IActorRef actorRef)
{
if (Equals(actorRef, ActorRefs.NoSender))
return String.Empty;
var path = actorRef.Path;
ExtendedActorSystem originalSystem = null;
if (actorRef is ActorRefWithCell)
{
originalSystem = actorRef.AsInstanceOf<ActorRefWithCell>().Underlying.System.AsInstanceOf<ExtendedActorSystem>();
}
if (_currentTransportInformation == null)
{
if (originalSystem == null)
{
var res = path.ToSerializationFormat();
return res;
}
else
{
var defaultAddress = originalSystem.Provider.DefaultAddress;
var res = path.ToSerializationFormatWithAddress(defaultAddress);
return res;
}
}
//CurrentTransportInformation exists
var system = _currentTransportInformation.System;
var address = _currentTransportInformation.Address;
if (originalSystem == null || originalSystem == system)
{
var res = path.ToSerializationFormatWithAddress(address);
return res;
}
else
{
var provider = originalSystem.Provider;
var res =
path.ToSerializationFormatWithAddress(provider.GetExternalAddressFor(address).GetOrElse(provider.DefaultAddress));
return res;
}
}
public Serializer GetSerializerById(int serializerId)
{
return _serializers[serializerId];
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Linq;
using System.Threading;
using Microsoft.PythonTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Win32;
using TestUtilities;
namespace PythonToolsTests {
[TestClass]
public class RegistryWatcherTest {
const string TESTKEY = @"Software\PythonToolsTestKey";
const int TIMEOUT = 500;
[TestInitialize]
public void CreateTestKey() {
Registry.CurrentUser.CreateSubKey(TESTKEY).Close();
}
[TestCleanup]
public void RemoveTestKey() {
Registry.CurrentUser.DeleteSubKeyTree(TESTKEY, throwOnMissingSubKey: false);
}
void SetValue(string subkey, string name, object value) {
using (var reg1 = Registry.CurrentUser.OpenSubKey(TESTKEY, true))
using (var reg2 = reg1.CreateSubKey(subkey)) {
reg2.SetValue(name, value);
}
}
void DeleteValue(string subkey, string name) {
using (var reg1 = Registry.CurrentUser.OpenSubKey(TESTKEY, true))
using (var reg2 = reg1.CreateSubKey(subkey)) {
reg2.DeleteValue(name, throwOnMissingValue: false);
}
}
void DeleteKey(string subkey) {
using (var reg1 = Registry.CurrentUser.OpenSubKey(TESTKEY, true)) {
reg1.DeleteSubKeyTree(subkey, throwOnMissingSubKey: false);
}
}
string GetKey(string subkey) {
return TESTKEY + "\\" + subkey;
}
object AddWatch(RegistryWatcher watcher,
string subkey,
Action<RegistryChangedEventArgs> callback,
bool recursive = false,
bool notifyValueChange = true,
bool notifyKeyChange = true) {
return watcher.Add(
RegistryHive.CurrentUser,
RegistryView.Default,
GetKey(subkey),
(s, e) => { callback(e); },
recursive,
notifyValueChange,
notifyKeyChange);
}
[TestMethod, Priority(UnitTestPriority.P1)]
public void RegistryWatcherUpdateNonRecursive() {
string keyName = "RegistryWatcherUpdateNonRecursive";
SetValue(keyName, "TestValue", "ABC");
SetValue(keyName + "\\TestKey", "Value", 123);
using (var watcher = new RegistryWatcher()) {
RegistryChangedEventArgs args = null;
var argsSet = new ManualResetEventSlim();
var watch1 = AddWatch(watcher, keyName,
e => { args = e; argsSet.Set(); });
// Value is set, but does not actually change
SetValue(keyName, "TestValue", "ABC");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
// Value is changed
SetValue(keyName, "TestValue", "DEF");
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
// Value in subkey is changed, but we don't notice
SetValue(keyName + "\\TestKey", "Value", 456);
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
watcher.Remove(watch1);
// Value is changed back, but we don't get notified
SetValue(keyName, "TestValue", "ABC");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
// Value in subkey is changed back, but we don't notice
SetValue(keyName + "\\TestKey", "Value", 123);
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
}
}
[TestMethod, Priority(UnitTestPriority.P1)]
public void RegistryWatcherAddNonRecursive() {
string keyName = "RegistryWatcherAddNonRecursive";
SetValue(keyName, "TestValue", "ABC");
SetValue(keyName + "\\TestKey", "Value", 123);
using (var watcher = new RegistryWatcher()) {
RegistryChangedEventArgs args = null;
var argsSet = new ManualResetEventSlim();
var watch1 = AddWatch(watcher, keyName,
e => { args = e; argsSet.Set(); });
// Value is created
SetValue(keyName, "TestValue2", "DEF");
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
// Value in subkey is added, but we don't notice
SetValue(keyName + "\\TestKey", "Value2", 456);
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
// Subkey is added
SetValue(keyName + "\\TestKey2", "Value", 789);
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
watcher.Remove(watch1);
// Another value is created, but we don't get notified
SetValue(keyName, "TestValue3", "GHI");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
// Another value in subkey is added, but we don't notice
SetValue(keyName + "\\TestKey", "Value3", 789);
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
}
}
[TestMethod, Priority(UnitTestPriority.P1)]
public void RegistryWatcherDeleteNonRecursive() {
string keyName = "RegistryWatcherDeleteNonRecursive";
SetValue(keyName, "TestValue1", "ABC");
SetValue(keyName, "TestValue2", "DEF");
SetValue(keyName, "TestValue3", "GHI");
SetValue(keyName + "\\TestKey1", "Value", 123);
SetValue(keyName + "\\TestKey2", "Value", 456);
using (var watcher = new RegistryWatcher()) {
RegistryChangedEventArgs args = null;
var argsSet = new ManualResetEventSlim();
var watch1 = AddWatch(watcher, keyName,
e => { args = e; argsSet.Set(); });
// Value is deleted
DeleteValue(keyName, "TestValue2");
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
// Value in subkey is deleted, and we don't notice
DeleteValue(keyName + "\\TestKey1", "Value");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
// Subkey is deleted
DeleteKey(keyName + "\\TestKey1");
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
watcher.Remove(watch1);
// Another value is deleted, but we don't get notified
DeleteValue(keyName, "TestValue3");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
// Another key is deleted, but we don't get notified
DeleteKey(keyName + "\\TestKey2");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
}
}
[TestMethod, Priority(UnitTestPriority.P1)]
public void RegistryWatcherUpdateRecursive() {
string keyName = "RegistryWatcherUpdateRecursive";
SetValue(keyName, "TestValue", "ABC");
SetValue(keyName + "\\TestKey", "Value", 123);
using (var watcher = new RegistryWatcher()) {
RegistryChangedEventArgs args = null;
var argsSet = new ManualResetEventSlim();
var watch1 = AddWatch(watcher, keyName,
e => { args = e; argsSet.Set(); },
recursive: true);
// Value is set, but does not actually change
SetValue(keyName, "TestValue", "ABC");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
// Value is changed
SetValue(keyName, "TestValue", "DEF");
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
// Value in subkey is changed
SetValue(keyName + "\\TestKey", "Value", 456);
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
watcher.Remove(watch1);
// Value is changed back, but we don't get notified
SetValue(keyName, "TestValue", "ABC");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
// Value in subkey is changed back, but we don't notice
SetValue(keyName + "\\TestKey", "Value", 123);
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
}
}
[TestMethod, Priority(UnitTestPriority.P1)]
public void RegistryWatcherAddRecursive() {
string keyName = "RegistryWatcherAddRecursive";
SetValue(keyName, "TestValue", "ABC");
SetValue(keyName + "\\TestKey", "Value", 123);
using (var watcher = new RegistryWatcher()) {
RegistryChangedEventArgs args = null;
var argsSet = new ManualResetEventSlim();
var watch1 = AddWatch(watcher, keyName,
e => { args = e; argsSet.Set(); },
recursive: true);
// Value is created
SetValue(keyName, "TestValue2", "DEF");
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.IsTrue(args.IsRecursive);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
// Subkey is added
SetValue(keyName + "\\TestKey2", "Value", 789);
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
// Value in subkey is added
SetValue(keyName + "\\TestKey", "Value2", 456);
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
watcher.Remove(watch1);
// Another value is created, but we don't get notified
SetValue(keyName, "TestValue3", "GHI");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
// Another value in subkey is added, but we don't notice
SetValue(keyName + "\\TestKey", "Value3", 789);
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
}
}
[TestMethod, Priority(UnitTestPriority.P1)]
public void RegistryWatcherDeleteRecursive() {
string keyName = "RegistryWatcherDeleteRecursive";
SetValue(keyName, "TestValue1", "ABC");
SetValue(keyName, "TestValue2", "DEF");
SetValue(keyName, "TestValue3", "GHI");
SetValue(keyName + "\\TestKey1", "Value", 123);
SetValue(keyName + "\\TestKey2", "Value", 456);
using (var watcher = new RegistryWatcher()) {
RegistryChangedEventArgs args = null;
var argsSet = new ManualResetEventSlim();
var watch1 = AddWatch(watcher, keyName,
e => { args = e; argsSet.Set(); },
recursive: true);
// Value is deleted
DeleteValue(keyName, "TestValue2");
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
// Value in subkey is deleted
DeleteValue(keyName + "\\TestKey1", "Value");
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
// Subkey is deleted
DeleteKey(keyName + "\\TestKey1");
Assert.IsTrue(argsSet.Wait(TIMEOUT));
Assert.IsNotNull(args);
Assert.AreEqual(GetKey(keyName), args.Key);
argsSet.Reset();
args = null;
watcher.Remove(watch1);
// Another value is deleted, but we don't get notified
DeleteValue(keyName, "TestValue3");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
// Another key is deleted, but we don't get notified
DeleteKey(keyName + "\\TestKey2");
Assert.IsFalse(argsSet.Wait(TIMEOUT));
Assert.IsNull(args);
}
}
class ArgSetter {
readonly RegistryChangedEventArgs[] Args;
readonly ManualResetEventSlim[] ArgsSet;
readonly int Index;
public ArgSetter(RegistryChangedEventArgs[] args, ManualResetEventSlim[] argsSet, int i) {
Args = args;
ArgsSet = argsSet;
Index = i;
}
public void Raised(RegistryChangedEventArgs e) {
Args[Index] = e;
ArgsSet[Index].Set();
}
}
[TestMethod, Priority(UnitTestPriority.P0)]
public void RegistryWatcher100Keys() {
string keyName = "RegistryWatcher100Keys";
for (int i = 0; i < 100; ++i) {
SetValue(string.Format("{0}\\Key{1}", keyName, i), "Value", "ABC");
}
using (var watcher = new RegistryWatcher()) {
var args = new RegistryChangedEventArgs[100];
var argsSet = args.Select(_ => new ManualResetEventSlim()).ToArray();
var tokens = new object[100];
for (int i = 0; i < 100; ++i) {
tokens[i] = AddWatch(watcher, string.Format("{0}\\Key{1}", keyName, i),
new ArgSetter(args, argsSet, i).Raised);
}
// Change the first value
SetValue(keyName + "\\Key0", "Value", "DEF");
Assert.IsTrue(argsSet[0].Wait(TIMEOUT));
Assert.IsNotNull(args[0]);
Assert.AreEqual(GetKey(keyName + "\\Key0"), args[0].Key);
argsSet[0].Reset();
args[0] = null;
// Change the last value
SetValue(keyName + "\\Key99", "Value", "DEF");
Assert.IsTrue(argsSet[99].Wait(TIMEOUT));
Assert.IsNotNull(args[99]);
Assert.AreEqual(GetKey(keyName + "\\Key99"), args[99].Key);
argsSet[99].Reset();
args[99] = null;
watcher.Remove(tokens[0]);
watcher.Remove(tokens[99]);
// Change the first value
SetValue(keyName + "\\Key0", "Value", "GHI");
Assert.IsFalse(argsSet[0].Wait(TIMEOUT));
Assert.IsNull(args[0]);
// Change the last value
SetValue(keyName + "\\Key99", "Value", "GHI");
Assert.IsFalse(argsSet[99].Wait(TIMEOUT));
Assert.IsNull(args[99]);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace OptionsApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
namespace Sabresaurus.SabreCSG
{
[CustomEditor(typeof(CSGModel))]
public class CSGModelInspector : Editor
{
// Build settings for the next build
SerializedProperty generateCollisionMeshesProperty;
SerializedProperty generateTangentsProperty;
SerializedProperty generateLightmapUVsProperty;
SerializedProperty unwrapAngleErrorProperty;
SerializedProperty unwrapAreaErrorProperty;
SerializedProperty unwrapHardAngleProperty;
SerializedProperty unwrapPackMarginProperty;
SerializedProperty defaultPhysicsMaterialProperty;
SerializedProperty defaultVisualMaterialProperty;
// Build settings from the last build
SerializedProperty lastBuildDefaultPhysicsMaterialProperty;
SerializedProperty lastBuildDefaultVisualMaterialProperty;
public void OnEnable()
{
// Build settings for the next build
generateCollisionMeshesProperty = serializedObject.FindProperty("buildSettings.GenerateCollisionMeshes");
generateTangentsProperty = serializedObject.FindProperty("buildSettings.GenerateTangents");
generateLightmapUVsProperty = serializedObject.FindProperty("buildSettings.GenerateLightmapUVs");
unwrapAngleErrorProperty = serializedObject.FindProperty("buildSettings.UnwrapAngleError");
unwrapAreaErrorProperty = serializedObject.FindProperty("buildSettings.UnwrapAreaError");
unwrapHardAngleProperty = serializedObject.FindProperty("buildSettings.UnwrapHardAngle");
unwrapPackMarginProperty = serializedObject.FindProperty("buildSettings.UnwrapPackMargin");
defaultPhysicsMaterialProperty = serializedObject.FindProperty("buildSettings.DefaultPhysicsMaterial");
defaultVisualMaterialProperty = serializedObject.FindProperty("buildSettings.DefaultVisualMaterial");
// Build settings from the last build
lastBuildDefaultPhysicsMaterialProperty = serializedObject.FindProperty("lastBuildSettings.DefaultPhysicsMaterial");
lastBuildDefaultVisualMaterialProperty = serializedObject.FindProperty("lastBuildSettings.DefaultVisualMaterial");
}
public override void OnInspectorGUI()
{
CSGModel csgModel = (CSGModel)target;
// Ensure the default material is set
csgModel.EnsureDefaultMaterialSet();
DrawDefaultInspector();
this.serializedObject.Update();
GUILayout.Label("Build Settings", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(generateCollisionMeshesProperty, new GUIContent("Generate Collision Meshes"));
EditorGUILayout.PropertyField(generateTangentsProperty, new GUIContent("Generate Tangents"));
EditorGUILayout.PropertyField(generateLightmapUVsProperty, new GUIContent("Generate Lightmap UVs"));
GUI.enabled = generateLightmapUVsProperty.boolValue;
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(unwrapAngleErrorProperty, new GUIContent("Unwrap Angle Error"));
EditorGUILayout.PropertyField(unwrapAreaErrorProperty, new GUIContent("Unwrap Area Error"));
EditorGUILayout.PropertyField(unwrapHardAngleProperty, new GUIContent("Unwrap Hard Angle"));
EditorGUILayout.PropertyField(unwrapPackMarginProperty, new GUIContent("Unwrap Pack Margin"));
EditorGUI.indentLevel = 0;
GUI.enabled = true;
PhysicMaterial lastPhysicsMaterial = defaultPhysicsMaterialProperty.objectReferenceValue as PhysicMaterial;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(defaultPhysicsMaterialProperty, new GUIContent("Default Physics Material"));
if(EditorGUI.EndChangeCheck())
{
PhysicMaterial newPhysicsMaterial = defaultPhysicsMaterialProperty.objectReferenceValue as PhysicMaterial;
// Update the built mesh colliders that use the old material
UpdatePhysicsMaterial(lastPhysicsMaterial, newPhysicsMaterial);
}
// Track the last visual material, so that if the user changes it we can update built renderers instantly
Material lastVisualMaterial = defaultVisualMaterialProperty.objectReferenceValue as Material;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(defaultVisualMaterialProperty, new GUIContent("Default Visual Material"));
if(EditorGUI.EndChangeCheck())
{
// User has changed the material, so grab the new material
Material newVisualMaterial = defaultVisualMaterialProperty.objectReferenceValue as Material;
// EnsureDefaultMaterialSet hasn't had a chance to run yet, so make sure we have a solid material reference
if(newVisualMaterial == null)
{
newVisualMaterial = csgModel.GetDefaultFallbackMaterial();
defaultVisualMaterialProperty.objectReferenceValue = newVisualMaterial;
}
// Update the built renderers that use the old material, also update source brush polygons
UpdateVisualMaterial(lastVisualMaterial, newVisualMaterial);
// Update the last build's default material because we don't need to build again
lastBuildDefaultVisualMaterialProperty.objectReferenceValue = newVisualMaterial;
}
EditorGUILayout.BeginHorizontal();
if(GUILayout.Button("Lit Texture (No Tint)"))
{
Material newVisualMaterial = AssetDatabase.LoadMainAssetAtPath(CSGModel.GetSabreCSGPath() + "Resources/Materials/Default_Map.mat") as Material;
// EnsureDefaultMaterialSet hasn't had a chance to run yet, so make sure we have a solid material reference
if(newVisualMaterial == null)
{
newVisualMaterial = csgModel.GetDefaultFallbackMaterial();
}
// Update the built renderers that use the old material, also update source brush polygons
UpdateVisualMaterial(lastVisualMaterial, newVisualMaterial);
defaultVisualMaterialProperty.objectReferenceValue = newVisualMaterial;
// Update the last build's default material because we don't need to build again
lastBuildDefaultVisualMaterialProperty.objectReferenceValue = newVisualMaterial;
}
if(GUILayout.Button("Lit Vertex Tint"))
{
Material newVisualMaterial = AssetDatabase.LoadMainAssetAtPath(CSGModel.GetSabreCSGPath() + "Resources/Materials/Default_LitWithTint.mat") as Material;
// EnsureDefaultMaterialSet hasn't had a chance to run yet, so make sure we have a solid material reference
if(newVisualMaterial == null)
{
newVisualMaterial = csgModel.GetDefaultFallbackMaterial();
}
// Update the built renderers that use the old material, also update source brush polygons
UpdateVisualMaterial(lastVisualMaterial, newVisualMaterial);
defaultVisualMaterialProperty.objectReferenceValue = newVisualMaterial;
// Update the last build's default material because we don't need to build again
lastBuildDefaultVisualMaterialProperty.objectReferenceValue = newVisualMaterial;
}
if(GUILayout.Button("Unlit Vertex Color"))
{
Material newVisualMaterial = AssetDatabase.LoadMainAssetAtPath(CSGModel.GetSabreCSGPath() + "Resources/Materials/Default_VertexColor.mat") as Material;
// EnsureDefaultMaterialSet hasn't had a chance to run yet, so make sure we have a solid material reference
if(newVisualMaterial == null)
{
newVisualMaterial = csgModel.GetDefaultFallbackMaterial();
}
// Update the built renderers that use the old material, also update source brush polygons
UpdateVisualMaterial(lastVisualMaterial, newVisualMaterial);
defaultVisualMaterialProperty.objectReferenceValue = newVisualMaterial;
// Update the last build's default material because we don't need to build again
lastBuildDefaultVisualMaterialProperty.objectReferenceValue = newVisualMaterial;
}
EditorGUILayout.EndHorizontal();
// Divider line
GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1));
if(GUILayout.Button("Export OBJ"))
{
csgModel.ExportOBJ();
}
BuildMetrics buildMetrics = csgModel.BuildMetrics;
GUILayout.Label("Vertices: " + buildMetrics.TotalVertices);
GUILayout.Label("Triangles: " + buildMetrics.TotalTriangles);
GUILayout.Label("Meshes: " + buildMetrics.TotalMeshes);
GUILayout.Label("Build Time: " + buildMetrics.BuildTime.ToString());
// Make sure any serialize property changes are committed to the underlying Unity Object
bool anyApplied = this.serializedObject.ApplyModifiedProperties();
if(anyApplied)
{
// Make sure that nothing else is included in the Undo, as an immediate rebuild may take place and
// we don't want the rebuild's lastBuildSettings being included in the undo step
Undo.IncrementCurrentGroup();
}
}
private void UpdateVisualMaterial(Material oldMaterial, Material newMaterial)
{
// If the material has changed and the new material is not null
if(newMaterial != oldMaterial && newMaterial != null)
{
CSGModel csgModel = (CSGModel)target;
// Update the built mesh renderers that use the old material
Transform meshGroup = csgModel.GetMeshGroupTransform();
if(meshGroup != null)
{
MeshRenderer[] meshRenderers = meshGroup.GetComponentsInChildren<MeshRenderer>();
for (int i = 0; i < meshRenderers.Length; i++)
{
if(meshRenderers[i].sharedMaterial == oldMaterial)
{
meshRenderers[i].sharedMaterial = newMaterial;
}
}
}
// Update all the polygons in the source brushes
List<Brush> brushes = csgModel.GetBrushes();
for (int i = 0; i < brushes.Count; i++)
{
if(brushes[i] != null) // Make sure the tracked brush still exists
{
Polygon[] polygons = brushes[i].GetPolygons();
for (int j = 0; j < polygons.Length; j++)
{
// If the polygon uses the old material (as an override)
if(polygons[j].Material == oldMaterial)
{
// Set the polygon to null, this removes the material override which gives consistent behaviour
polygons[j].Material = null;
}
}
}
}
}
}
private void UpdatePhysicsMaterial(PhysicMaterial oldMaterial, PhysicMaterial newMaterial)
{
// If the physics material has changed
if(newMaterial != oldMaterial)
{
CSGModel csgModel = (CSGModel)target;
// Update the built mesh renderers that use the old material
Transform meshGroup = csgModel.GetMeshGroupTransform();
if(meshGroup != null)
{
MeshCollider[] meshColliders = meshGroup.GetComponentsInChildren<MeshCollider>();
for (int i = 0; i < meshColliders.Length; i++)
{
if(meshColliders[i].sharedMaterial == oldMaterial)
{
meshColliders[i].sharedMaterial = newMaterial;
}
}
}
// Update the last build's default material because we don't need to build again
lastBuildDefaultPhysicsMaterialProperty.objectReferenceValue = newMaterial;
}
}
}
}
| |
using System.Collections.Generic;
using System;
using System.Linq;
using System.Threading;
using System.Collections;
using System.Diagnostics;
namespace UnityThreading
{
public abstract class ThreadBase : IDisposable
{
public static int AvailableProcessors
{
get
{
#if !NO_UNITY
return UnityEngine.SystemInfo.processorCount;
#else
return Environment.ProcessorCount;
#endif
}
}
protected Dispatcher targetDispatcher;
protected Thread thread;
protected ManualResetEvent exitEvent = new ManualResetEvent(false);
[ThreadStatic]
private static ThreadBase currentThread;
private string threadName;
/// <summary>
/// Returns the currently ThreadBase instance which is running in this thread.
/// </summary>
public static ThreadBase CurrentThread { get { return currentThread; } }
public ThreadBase(string threadName)
: this(threadName, true)
{
}
public ThreadBase(string threadName, bool autoStartThread)
: this(threadName, Dispatcher.CurrentNoThrow, autoStartThread)
{
}
public ThreadBase(string threadName, Dispatcher targetDispatcher)
: this(threadName, targetDispatcher, true)
{
}
public ThreadBase(string threadName, Dispatcher targetDispatcher, bool autoStartThread)
{
this.threadName = threadName;
this.targetDispatcher = targetDispatcher;
if (autoStartThread)
Start();
}
/// <summary>
/// Returns true if the thread is working.
/// </summary>
public bool IsAlive { get { return thread == null ? false : thread.IsAlive; } }
/// <summary>
/// Returns true if the thread should stop working.
/// </summary>
public bool ShouldStop { get { return exitEvent.InterWaitOne(0); } }
/// <summary>
/// Starts the thread.
/// </summary>
public void Start()
{
if (thread != null)
Abort();
exitEvent.Reset();
thread = new Thread(DoInternal);
thread.Name = threadName;
thread.Priority = priority;
thread.Start();
}
/// <summary>
/// Notifies the thread to stop working.
/// </summary>
public void Exit()
{
if (thread != null)
exitEvent.Set();
}
/// <summary>
/// Notifies the thread to stop working.
/// </summary>
public void Abort()
{
Exit();
if (thread != null)
thread.Join();
}
/// <summary>
/// Notifies the thread to stop working and waits for completion for the given ammount of time.
/// When the thread soes not stop after the given timeout the thread will be terminated.
/// </summary>
/// <param name="seconds">The time this method will wait until the thread will be terminated.</param>
public void AbortWaitForSeconds(float seconds)
{
Exit();
if (thread != null)
{
thread.Join((int)(seconds * 1000));
if (thread.IsAlive)
thread.Abort();
}
}
/// <summary>
/// Creates a new Task for the target Dispatcher (default: the main Dispatcher) based upon the given function.
/// </summary>
/// <typeparam name="T">The return value of the task.</typeparam>
/// <param name="function">The function to process at the dispatchers thread.</param>
/// <returns>The new task.</returns>
public Task<T> Dispatch<T>(Func<T> function)
{
return targetDispatcher.Dispatch(function);
}
/// <summary>
/// Creates a new Task for the target Dispatcher (default: the main Dispatcher) based upon the given function.
/// This method will wait for the task completion and returns the return value.
/// </summary>
/// <typeparam name="T">The return value of the task.</typeparam>
/// <param name="function">The function to process at the dispatchers thread.</param>
/// <returns>The return value of the tasks function.</returns>
public T DispatchAndWait<T>(Func<T> function)
{
var task = this.Dispatch(function);
task.Wait();
return task.Result;
}
/// <summary>
/// Creates a new Task for the target Dispatcher (default: the main Dispatcher) based upon the given function.
/// This method will wait for the task completion or the timeout and returns the return value.
/// </summary>
/// <typeparam name="T">The return value of the task.</typeparam>
/// <param name="function">The function to process at the dispatchers thread.</param>
/// <param name="timeOutSeconds">Time in seconds after the waiting process will stop.</param>
/// <returns>The return value of the tasks function.</returns>
public T DispatchAndWait<T>(Func<T> function, float timeOutSeconds)
{
var task = this.Dispatch(function);
task.WaitForSeconds(timeOutSeconds);
return task.Result;
}
/// <summary>
/// Creates a new Task for the target Dispatcher (default: the main Dispatcher) based upon the given action.
/// </summary>
/// <param name="action">The action to process at the dispatchers thread.</param>
/// <returns>The new task.</returns>
public Task Dispatch(Action action)
{
return targetDispatcher.Dispatch(action);
}
/// <summary>
/// Creates a new Task for the target Dispatcher (default: the main Dispatcher) based upon the given action.
/// This method will wait for the task completion.
/// </summary>
/// <param name="action">The action to process at the dispatchers thread.</param>
public void DispatchAndWait(Action action)
{
var task = this.Dispatch(action);
task.Wait();
}
/// <summary>
/// Creates a new Task for the target Dispatcher (default: the main Dispatcher) based upon the given action.
/// This method will wait for the task completion or the timeout.
/// </summary>
/// <param name="action">The action to process at the dispatchers thread.</param>
/// <param name="timeOutSeconds">Time in seconds after the waiting process will stop.</param>
public void DispatchAndWait(Action action, float timeOutSeconds)
{
var task = this.Dispatch(action);
task.WaitForSeconds(timeOutSeconds);
}
/// <summary>
/// Dispatches the given task to the target Dispatcher (default: the main Dispatcher).
/// </summary>
/// <param name="taskBase">The task to process at the dispatchers thread.</param>
/// <returns>The new task.</returns>
public Task Dispatch(Task taskBase)
{
return targetDispatcher.Dispatch(taskBase);
}
/// <summary>
/// Dispatches the given task to the target Dispatcher (default: the main Dispatcher).
/// This method will wait for the task completion.
/// </summary>
/// <param name="taskBase">The task to process at the dispatchers thread.</param>
public void DispatchAndWait(Task taskBase)
{
var task = this.Dispatch(taskBase);
task.Wait();
}
/// <summary>
/// Dispatches the given task to the target Dispatcher (default: the main Dispatcher).
/// This method will wait for the task completion or the timeout.
/// </summary>
/// <param name="taskBase">The task to process at the dispatchers thread.</param>
/// <param name="timeOutSeconds">Time in seconds after the waiting process will stop.</param>
public void DispatchAndWait(Task taskBase, float timeOutSeconds)
{
var task = this.Dispatch(taskBase);
task.WaitForSeconds(timeOutSeconds);
}
protected void DoInternal()
{
currentThread = this;
var enumerator = Do();
if (enumerator == null)
{
return;
}
RunEnumerator(enumerator);
}
private void RunEnumerator(IEnumerator enumerator)
{
do
{
if (enumerator.Current is Task)
{
var task = (Task)enumerator.Current;
this.DispatchAndWait(task);
}
else if (enumerator.Current is SwitchTo)
{
var switchTo = (SwitchTo)enumerator.Current;
if (switchTo.Target == SwitchTo.TargetType.Main && CurrentThread != null)
{
var task = Task.Create(() =>
{
if (enumerator.MoveNext() && !ShouldStop)
RunEnumerator(enumerator);
});
this.DispatchAndWait(task);
}
else if (switchTo.Target == SwitchTo.TargetType.Thread && CurrentThread == null)
{
return;
}
}
}
while (enumerator.MoveNext() && !ShouldStop);
}
protected abstract IEnumerator Do();
#region IDisposable Members
/// <summary>
/// Disposes the thread and all resources.
/// </summary>
public virtual void Dispose()
{
AbortWaitForSeconds(1.0f);
}
#endregion
private ThreadPriority priority = ThreadPriority.BelowNormal;
public ThreadPriority Priority
{
get { return priority; }
set
{
priority = value;
if (thread != null)
thread.Priority = priority;
}
}
}
public sealed class ActionThread : ThreadBase
{
private Action<ActionThread> action;
/// <summary>
/// Creates a new Thread which runs the given action.
/// The thread will start running after creation.
/// </summary>
/// <param name="action">The action to run.</param>
public ActionThread(Action<ActionThread> action)
: this(action, true)
{
}
/// <summary>
/// Creates a new Thread which runs the given action.
/// </summary>
/// <param name="action">The action to run.</param>
/// <param name="autoStartThread">Should the thread start after creation.</param>
public ActionThread(Action<ActionThread> action, bool autoStartThread)
: base("ActionThread", Dispatcher.Current, false)
{
this.action = action;
if (autoStartThread)
Start();
}
protected override IEnumerator Do()
{
action(this);
return null;
}
}
public sealed class EnumeratableActionThread : ThreadBase
{
private Func<ThreadBase, IEnumerator> enumeratableAction;
/// <summary>
/// Creates a new Thread which runs the given enumeratable action.
/// The thread will start running after creation.
/// </summary>
/// <param name="action">The enumeratable action to run.</param>
public EnumeratableActionThread(Func<ThreadBase, IEnumerator> enumeratableAction)
: this(enumeratableAction, true)
{
}
/// <summary>
/// Creates a new Thread which runs the given enumeratable action.
/// </summary>
/// <param name="action">The enumeratable action to run.</param>
/// <param name="autoStartThread">Should the thread start after creation.</param>
public EnumeratableActionThread(Func<ThreadBase, IEnumerator> enumeratableAction, bool autoStartThread)
: base("EnumeratableActionThread", Dispatcher.Current, false)
{
this.enumeratableAction = enumeratableAction;
if (autoStartThread)
Start();
}
protected override IEnumerator Do()
{
return enumeratableAction(this);
}
}
public sealed class TickThread : ThreadBase
{
private Action action;
private int tickLengthInMilliseconds;
private ManualResetEvent tickEvent = new ManualResetEvent(false);
/// <summary>
/// Creates a new Thread which runs the given action.
/// The thread will start running after creation.
/// </summary>
/// <param name="action">The enumeratable action to run.</param>
/// <param name="tickLengthInMilliseconds">Time between ticks.</param>
public TickThread(Action action, int tickLengthInMilliseconds)
: this(action, tickLengthInMilliseconds, true)
{
}
/// <summary>
/// Creates a new Thread which runs the given action.
/// </summary>
/// <param name="action">The action to run.</param>
/// <param name="tickLengthInMilliseconds">Time between ticks.</param>
/// <param name="autoStartThread">Should the thread start after creation.</param>
public TickThread(Action action, int tickLengthInMilliseconds, bool autoStartThread)
: base("TickThread", Dispatcher.CurrentNoThrow, false)
{
this.tickLengthInMilliseconds = tickLengthInMilliseconds;
this.action = action;
if (autoStartThread)
Start();
}
protected override IEnumerator Do()
{
while (!exitEvent.InterWaitOne(0))
{
action();
var result = WaitHandle.WaitAny(new WaitHandle[] { exitEvent, tickEvent }, tickLengthInMilliseconds);
if (result == 0)
return null;
}
return null;
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.BitStamp.Native.BitStamp
File: HttpClient.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.BitStamp.Native
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Security.Cryptography;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Net;
using Ecng.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using StockSharp.Localization;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.BitStamp.Native.Model;
class HttpClient : BaseLogReceiver
{
private readonly string _clientId;
private readonly SecureString _key;
private readonly bool _authV2;
private readonly HashAlgorithm _hasher;
private const string _baseAddr = "www.bitstamp.net";
private readonly IdGenerator _nonceGen;
public HttpClient(string clientId, SecureString key, SecureString secret, bool authV2)
{
_clientId = clientId;
_key = key;
_authV2 = authV2;
_hasher = secret.IsEmpty() ? null : new HMACSHA256(secret.UnSecure().ASCII());
_nonceGen = new UTCMlsIncrementalIdGenerator();
}
protected override void DisposeManaged()
{
_hasher?.Dispose();
base.DisposeManaged();
}
// to get readable name after obfuscation
public override string Name => nameof(BitStamp) + "_" + nameof(HttpClient);
public IEnumerable<Symbol> GetPairsInfo()
{
return MakeRequest<IEnumerable<Symbol>>(CreateUrl("trading-pairs-info"), CreateRequest(Method.GET));
}
public IEnumerable<Transaction> RequestTransactions(string ticker, string interval = null)
{
var url = CreateUrl($"transactions/{ticker}");
var request = CreateRequest(Method.GET);
if (interval != null)
request.AddParameter("time", interval);
return MakeRequest<IEnumerable<Transaction>>(url, request, true);
}
public Tuple<Dictionary<string, RefTriple<decimal?, decimal?, decimal?>>, Dictionary<string, decimal>> GetBalances(string ticker = null)
{
var url = CreateUrl(ticker.IsEmpty() ? "balance" : $"balance/{ticker}");
dynamic response = MakeRequest<object>(url, ApplySecret(CreateRequest(Method.POST), url));
var balances = new Dictionary<string, RefTriple<decimal?, decimal?, decimal?>>(StringComparer.InvariantCultureIgnoreCase);
var fees = new Dictionary<string, decimal>(StringComparer.InvariantCultureIgnoreCase);
RefTriple<decimal?, decimal?, decimal?> GetBalance(string symbol)
{
return balances.SafeAdd(symbol, key => new RefTriple<decimal?, decimal?, decimal?>());
}
foreach (var property in ((JObject)response).Properties())
{
var parts = property.Name.Split('_');
var symbol = parts[0];
var value = (decimal)property.Value;
switch (parts[1].ToLowerInvariant())
{
case "fee":
fees.Add(symbol, value);
break;
case "available":
GetBalance(symbol).First = value;
break;
case "balance":
GetBalance(symbol).Second = value;
break;
case "reserved":
GetBalance(symbol).Third = value;
break;
}
}
return Tuple.Create(balances, fees);
}
public UserTransaction[] RequestUserTransactions(string ticker, int? offset, int? limit)
{
var request = CreateRequest(Method.POST);
if (offset != null)
request.AddParameter("offset", offset.Value);
if (limit != null)
request.AddParameter("limit", limit.Value);
var url = CreateUrl(ticker.IsEmpty() ? "user_transactions" : $"user_transactions/{ticker}");
return MakeRequest<UserTransaction[]>(url, ApplySecret(request, url));
}
public IEnumerable<UserOrder> RequestOpenOrders(string ticker = "all")
{
var url = CreateUrl($"open_orders/{ticker}");
return MakeRequest<IEnumerable<UserOrder>>(url, ApplySecret(CreateRequest(Method.POST), url));
}
public UserOrder RegisterOrder(string pair, string side, decimal? price, decimal volume, decimal? stopPrice, bool daily, bool ioc)
{
var market = price == null ? "market/" : string.Empty;
var request = CreateRequest(Method.POST);
request.AddParameter("amount", volume);
if (price != null)
request.AddParameter("price", price.Value);
if (stopPrice != null)
request.AddParameter("limit_price", stopPrice.Value);
if (daily)
request.AddParameter("daily_order", true);
if (ioc)
request.AddParameter("ioc_order", true);
var url = CreateUrl($"{side}/{market}{pair}");
return MakeRequest<UserOrder>(url, ApplySecret(request, url));
}
public UserOrder CancelOrder(long orderId)
{
var url = CreateUrl("cancel_order");
return MakeRequest<UserOrder>(url, ApplySecret(CreateRequest(Method.POST).AddParameter("id", orderId), url));
}
public void CancelAllOrders()
{
var url = CreateUrl("cancel_all_orders", string.Empty);
var result = MakeRequest<bool>(url, ApplySecret(CreateRequest(Method.POST), url));
if (!result)
throw new InvalidOperationException();
}
public long Withdraw(string currency, decimal volume, WithdrawInfo info)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
var request = CreateRequest(Method.POST);
switch (info.Type)
{
case WithdrawTypes.BankWire:
{
if (info.BankDetails == null)
throw new InvalidOperationException(LocalizedStrings.BankDetailsIsMissing);
request
.AddParameter("amount", volume)
.AddParameter("account_currency", info.BankDetails.Currency.To<string>())
.AddParameter("name", info.BankDetails.AccountName)
.AddParameter("IBAN", info.BankDetails.Iban)
.AddParameter("BIC", info.BankDetails.Bic)
.AddParameter("address", info.CompanyDetails?.Address)
.AddParameter("postal_code", info.CompanyDetails?.PostalCode)
.AddParameter("city", info.CompanyDetails?.City)
.AddParameter("country", info.CompanyDetails?.Country)
.AddParameter("type", volume)
.AddParameter("bank_name", info.BankDetails.Name)
.AddParameter("bank_address", info.BankDetails.Address)
.AddParameter("bank_postal_code", info.BankDetails.PostalCode)
.AddParameter("bank_city", info.BankDetails.City)
.AddParameter("bank_country", info.BankDetails.Country)
.AddParameter("currency", currency)
.AddParameter("comment", info.Comment);
var url = CreateUrl("withdrawal/open");
dynamic response = MakeRequest<object>(url, ApplySecret(request, url));
if (response.id == null)
throw new InvalidOperationException();
return (long)response.id;
}
case WithdrawTypes.Crypto:
{
request
.AddParameter("amount", volume)
.AddParameter("address", info.CryptoAddress);
string methodName;
string version;
switch (currency.To<CurrencyTypes>())
{
case CurrencyTypes.BTC:
{
methodName = "bitcoin_withdrawal";
version = string.Empty;
request
.AddParameter("instant", info.Express ? 1 : 0);
break;
}
case CurrencyTypes.LTC:
case CurrencyTypes.ETH:
case CurrencyTypes.BCH:
case CurrencyTypes.XRP:
{
methodName = $"{currency}_withdrawal".ToLowerInvariant();
version = "v2/";
if (!info.Comment.IsEmpty())
request.AddParameter("destination_tag", info.Comment);
break;
}
default:
throw new NotSupportedException(LocalizedStrings.Str1212Params.Put(currency));
}
var url = CreateUrl(methodName, version);
dynamic response = MakeRequest<object>(url, ApplySecret(request, url));
if (response.id == null)
throw new InvalidOperationException();
return (long)response.id;
}
default:
throw new NotSupportedException(LocalizedStrings.WithdrawTypeNotSupported.Put(info.Type));
}
}
private static Uri CreateUrl(string methodName, string version = "v2/")
{
if (methodName.IsEmpty())
throw new ArgumentNullException(nameof(methodName));
return $"https://{_baseAddr}/api/{version}{methodName}/".To<Uri>();
}
private static IRestRequest CreateRequest(Method method)
{
return new RestRequest(method);
}
private static readonly JsonSerializerSettings _serializerSettings = JsonHelper.CreateJsonSerializerSettings();
private IRestRequest ApplySecret(IRestRequest request, Uri url)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
var urlStr = url.ToString();
if (_authV2 && urlStr.ContainsIgnoreCase("/v2/"))
{
var apiKey = "BITSTAMP " + _key.UnSecure();
var version = "v2";
var nonce = Guid.NewGuid().ToString();
var timeStamp = ((long)TimeHelper.UnixNowMls).To<string>();
var payload = request
.Parameters
.Where(p => p.Type == ParameterType.GetOrPost && p.Value != null)
.OrderBy(p => p.Name)
.Select(p => $"{p.Name}={p.Value}")
.Join("&");
var str = apiKey +
request.Method +
url.Host +
url.PathAndQuery.Remove(url.Query, true) +
url.Query +
"application/json" +
nonce +
timeStamp +
version +
payload;
var signature = _hasher
.ComputeHash(str.UTF8())
.Digest()
.ToUpperInvariant();
request
.AddHeader("X-Auth", apiKey)
.AddHeader("X-Auth-Signature", signature)
.AddHeader("X-Auth-Nonce", nonce)
.AddHeader("X-Auth-Timestamp", timeStamp)
.AddHeader("X-Auth-Version", version);
}
else
{
var nonce = _nonceGen.GetNextId();
var signature = _hasher
.ComputeHash((nonce + _clientId + _key.UnSecure()).UTF8())
.Digest()
.ToUpperInvariant();
request
.AddParameter("key", _key.UnSecure())
.AddParameter("nonce", nonce)
.AddParameter("signature", signature);
}
return request;
}
private T MakeRequest<T>(Uri url, IRestRequest request, bool cookies = false)
{
dynamic obj = request.Invoke(url, this, this.AddVerboseLog, client =>
{
if (cookies)
client.CookieContainer = new CookieContainer();
});
if (((JToken)obj).Type == JTokenType.Object && obj.status == "error")
throw new InvalidOperationException((string)obj.reason.ToString());
return ((JToken)obj).DeserializeObject<T>();
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using DotSpatial.Controls;
using DotSpatial.Data;
using DotSpatial.NTSExtension;
using DotSpatial.Serialization;
using DotSpatial.Symbology;
using NetTopologySuite.Geometries;
using Point = System.Drawing.Point;
namespace DotSpatial.Plugins.ShapeEditor
{
/// <summary>
/// MoveVertexFunction works only with the actively selected layer in the legend.
/// MoveVertex requires clicking on a shape in order to first select the shape to work with.
/// Moving the mouse should highlight potential shapes for editing when not in edit mode.
/// Clicking on the shape establishes "edit mode" for that shape.
/// It should display all the vertices of the selected polygon in blue.
/// The mouse down on a vertex starts dragging.
/// but previous polygon location should be ok as well.
/// A right click during drag should cancel the movement if dragging.
/// A further right click will de-select the shape to edit.
/// </summary>
public class MoveVertexFunction : SnappableMapFunction
{
#region Fields
private IFeatureCategory _activeCategory;
private IFeature _activeFeature; // not yet selected
private Coordinate _activeVertex;
private Coordinate _closedCircleCoord;
private Coordinate _dragCoord;
private bool _dragging;
private IFeatureSet _featureSet;
private Rectangle _imageRect;
private IFeatureLayer _layer;
private Point _mousePosition;
private Coordinate _nextPoint;
private IFeatureCategory _oldCategory;
private Coordinate _previousPoint;
private IFeatureCategory _selectedCategory;
private IFeature _selectedFeature;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MoveVertexFunction"/> class where the Map will be defined.
/// </summary>
/// <param name="map">The map control that implements the IMap interface.</param>
public MoveVertexFunction(IMap map)
: base(map)
{
Configure();
}
#endregion
#region Events
/// <summary>
/// Is raised after a vertex was moved.
/// </summary>
public event EventHandler<VertexMovedEventArgs> VertextMoved;
#endregion
#region Properties
/// <summary>
/// Gets or sets the layer.
/// </summary>
public IFeatureLayer Layer
{
get
{
return _layer;
}
set
{
_layer = value;
_featureSet = _layer.DataSet;
InitializeSnapLayers();
}
}
#endregion
#region Methods
/// <summary>
/// Deselects the selected feature and removes the highlight from any highlighted feature.
/// </summary>
public void ClearSelection()
{
DeselectFeature();
RemoveHighlightFromFeature();
_oldCategory = null;
}
/// <summary>
/// This should be called if for some reason the layer gets un-selected or whatever so that the selection
/// should clear.
/// </summary>
public void DeselectFeature()
{
if (_selectedFeature != null)
{
_layer.SetCategory(_selectedFeature, _oldCategory);
}
_selectedFeature = null;
Map.MapFrame.Initialize();
Map.Invalidate();
}
/// <summary>
/// Removes the highlighting from the actively highlighted feature.
/// </summary>
public void RemoveHighlightFromFeature()
{
if (_activeFeature != null)
{
_layer.SetCategory(_activeFeature, _oldCategory);
}
_activeFeature = null;
}
/// <inheritdoc />
protected override void OnDeactivate()
{
ClearSelection();
base.OnDeactivate();
}
/// <inheritdoc />
protected override void OnDraw(MapDrawArgs e)
{
Rectangle mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
if (_selectedFeature != null)
{
foreach (Coordinate c in _selectedFeature.Geometry.Coordinates)
{
Point pt = e.GeoGraphics.ProjToPixel(c);
if (e.GeoGraphics.ImageRectangle.Contains(pt))
{
e.Graphics.FillRectangle(Brushes.Blue, pt.X - 2, pt.Y - 2, 4, 4);
}
if (mouseRect.Contains(pt))
{
e.Graphics.FillRectangle(Brushes.Red, mouseRect);
}
}
}
if (_dragging)
{
if (_featureSet.FeatureType == FeatureType.Point || _featureSet.FeatureType == FeatureType.MultiPoint)
{
Rectangle r = new Rectangle(_mousePosition.X - (_imageRect.Width / 2), _mousePosition.Y - (_imageRect.Height / 2), _imageRect.Width, _imageRect.Height);
_selectedCategory.Symbolizer.Draw(e.Graphics, r);
}
else
{
e.Graphics.FillRectangle(Brushes.Red, _mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
Point b = _mousePosition;
Pen p = new Pen(Color.Blue)
{
DashStyle = DashStyle.Dash
};
if (_previousPoint != null)
{
Point a = e.GeoGraphics.ProjToPixel(_previousPoint);
e.Graphics.DrawLine(p, a, b);
}
if (_nextPoint != null)
{
Point c = e.GeoGraphics.ProjToPixel(_nextPoint);
e.Graphics.DrawLine(p, b, c);
}
p.Dispose();
}
}
}
/// <inheritdoc />
protected override void OnMouseDown(GeoMouseArgs e)
{
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right)
{
_mousePosition = e.Location;
if (_dragging)
{
if (e.Button == MouseButtons.Right)
{
_dragging = false;
Map.Invalidate();
Map.IsBusy = false;
}
}
else
{
if (_selectedFeature != null)
{
Rectangle mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
Envelope env = Map.PixelToProj(mouseRect).ToEnvelope();
if (CheckForVertexDrag(e))
{
return;
}
// No vertex selection has occured.
if (!_selectedFeature.Geometry.Intersects(env.ToPolygon()))
{
// We are clicking down outside of the given polygon, so clear our selected feature
DeselectFeature();
return;
}
}
if (_activeFeature != null)
{
// Don't start dragging a vertices right away for polygons and lines.
// First you select the polygon, which displays the vertices, then they can be moved.
if (_featureSet.FeatureType == FeatureType.Polygon)
{
_selectedFeature = _activeFeature;
_activeFeature = null;
if (!(_selectedCategory is IPolygonCategory sc))
{
_selectedCategory = new PolygonCategory(Color.FromArgb(55, 0, 255, 255), Color.Blue, 1)
{
LegendItemVisible = false
};
}
_layer.SetCategory(_selectedFeature, _selectedCategory);
}
else if (_featureSet.FeatureType == FeatureType.Line)
{
_selectedFeature = _activeFeature;
_activeFeature = null;
if (!(_selectedCategory is ILineCategory sc))
{
_selectedCategory = new LineCategory(Color.Cyan, 1)
{
LegendItemVisible = false
};
}
_layer.SetCategory(_selectedFeature, _selectedCategory);
}
else
{
_dragging = true;
Map.IsBusy = true;
_dragCoord = _activeFeature.Geometry.Coordinates[0];
MapPointLayer mpl = _layer as MapPointLayer;
mpl?.SetVisible(_activeFeature, false);
if (!(_selectedCategory is IPointCategory sc))
{
if (_layer.GetCategory(_activeFeature).Symbolizer.Copy() is IPointSymbolizer ps)
{
ps.SetFillColor(Color.Cyan);
_selectedCategory = new PointCategory(ps);
}
}
}
}
Map.MapFrame.Initialize();
Map.Invalidate();
}
}
base.OnMouseDown(e);
}
/// <inheritdoc />
protected override void OnMouseMove(GeoMouseArgs e)
{
_mousePosition = e.Location;
if (_dragging)
{
// Begin snapping changes
Coordinate snappedCoord = e.GeographicLocation;
if (ComputeSnappedLocation(e, ref snappedCoord))
{
_mousePosition = Map.ProjToPixel(snappedCoord);
}
// End snapping changes
UpdateDragCoordinate(snappedCoord); // Snapping changes
}
else
{
if (_selectedFeature != null)
{
VertexHighlight();
}
else
{
// Before a shape is selected it should be possible to highlight shapes to indicate which one
// will be selected.
bool requiresInvalidate = false;
if (_activeFeature != null)
{
if (ShapeRemoveHighlight(e))
{
requiresInvalidate = true;
}
}
if (_activeFeature == null)
{
if (ShapeHighlight(e))
{
requiresInvalidate = true;
}
}
if (requiresInvalidate)
{
Map.MapFrame.Initialize();
Map.Invalidate();
}
}
// check to see if the coordinates intersect with a shape in our current featureset.
}
base.OnMouseMove(e);
}
/// <inheritdoc />
protected override void OnMouseUp(GeoMouseArgs e)
{
if (e.Button == MouseButtons.Left && _dragging)
{
_dragging = false;
Map.IsBusy = false;
_featureSet.InvalidateVertices();
if (_featureSet.FeatureType == FeatureType.Point || _featureSet.FeatureType == FeatureType.MultiPoint)
{
if (_activeFeature == null)
{
return;
}
OnVertexMoved(new VertexMovedEventArgs(_activeFeature));
if (_layer.GetCategory(_activeFeature) != _selectedCategory)
{
_layer.SetCategory(_activeFeature, _selectedCategory);
_layer.SetVisible(_activeFeature, true);
}
}
else
{
if (_selectedFeature == null)
{
return;
}
OnVertexMoved(new VertexMovedEventArgs(_selectedFeature));
if (_layer.GetCategory(_selectedFeature) != _selectedCategory)
{
_layer.SetCategory(_selectedFeature, _selectedCategory);
}
}
}
Map.MapFrame.Initialize();
base.OnMouseUp(e);
}
/// <summary>
/// This function checks to see if the current mouse location is over a vertex.
/// </summary>
/// <param name="e">The GeoMouseArgs parameter contains information about the mouse location and geographic coordinates.</param>
/// <returns>True, if the current mouse location is over a vertex.</returns>
private bool CheckForVertexDrag(GeoMouseArgs e)
{
Rectangle mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
Envelope env = Map.PixelToProj(mouseRect).ToEnvelope();
if (e.Button == MouseButtons.Left)
{
if (_layer.DataSet.FeatureType == FeatureType.Polygon)
{
for (int prt = 0; prt < _selectedFeature.Geometry.NumGeometries; prt++)
{
Geometry g = _selectedFeature.Geometry.GetGeometryN(prt);
IList<Coordinate> coords = g.Coordinates;
for (int ic = 0; ic < coords.Count; ic++)
{
Coordinate c = coords[ic];
if (env.Contains(c))
{
_dragging = true;
_dragCoord = c;
if (ic == 0)
{
_closedCircleCoord = coords[coords.Count - 1];
_previousPoint = coords[coords.Count - 2];
_nextPoint = coords[1];
}
else if (ic == coords.Count - 1)
{
_closedCircleCoord = coords[0];
_previousPoint = coords[coords.Count - 2];
_nextPoint = coords[1];
}
else
{
_previousPoint = coords[ic - 1];
_nextPoint = coords[ic + 1];
_closedCircleCoord = null;
}
Map.Invalidate();
return true;
}
}
}
}
else if (_layer.DataSet.FeatureType == FeatureType.Line)
{
for (int prt = 0; prt < _selectedFeature.Geometry.NumGeometries; prt++)
{
Geometry g = _selectedFeature.Geometry.GetGeometryN(prt);
IList<Coordinate> coords = g.Coordinates;
for (int ic = 0; ic < coords.Count; ic++)
{
Coordinate c = coords[ic];
if (env.Contains(c))
{
_dragging = true;
_dragCoord = c;
if (ic == 0)
{
_previousPoint = null;
_nextPoint = coords[1];
}
else if (ic == coords.Count - 1)
{
_previousPoint = coords[coords.Count - 2];
_nextPoint = null;
}
else
{
_previousPoint = coords[ic - 1];
_nextPoint = coords[ic + 1];
}
Map.Invalidate();
return true;
}
}
}
}
}
return false;
}
private void Configure()
{
YieldStyle = YieldStyles.LeftButton | YieldStyles.RightButton;
}
/// <summary>
/// Fires the VertexMoved event.
/// </summary>
/// <param name="e">The event args.</param>
private void OnVertexMoved(VertexMovedEventArgs e)
{
VertextMoved?.Invoke(this, e);
}
/// <summary>
/// Before a shape is selected, moving the mouse over a shape will highlight that shape by changing
/// its appearance. This tests features to determine the first feature to qualify as the highlight.
/// </summary>
/// <param name="e">The GeoMouseArgs parameter contains information about the mouse location and geographic coordinates.</param>
/// <returns>A value indicating whether the shape was successfully highlighted.</returns>
private bool ShapeHighlight(GeoMouseArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e), "e is null.");
Rectangle mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
Extent ext = Map.PixelToProj(mouseRect);
Polygon env = ext.ToEnvelope().ToPolygon();
bool requiresInvalidate = false;
foreach (IFeature feature in _featureSet.Features)
{
if (_featureSet.FeatureType == FeatureType.Point || _featureSet.FeatureType == FeatureType.MultiPoint)
{
if (_layer is MapPointLayer mpl)
{
int w = 3;
int h = 3;
if (mpl.GetCategory(feature) is PointCategory pc)
{
if (pc.Symbolizer.ScaleMode != ScaleMode.Geographic)
{
Size2D size = pc.Symbolizer.GetSize();
w = (int)size.Width;
h = (int)size.Height;
}
}
_imageRect = new Rectangle(e.Location.X - (w / 2), e.Location.Y - (h / 2), w, h);
if (_imageRect.Contains(Map.ProjToPixel(feature.Geometry.Coordinates[0])))
{
_activeFeature = feature;
_oldCategory = mpl.GetCategory(feature);
if (_selectedCategory == null)
{
_selectedCategory = _oldCategory.Copy();
_selectedCategory.SetColor(Color.Red);
_selectedCategory.LegendItemVisible = false;
}
mpl.SetCategory(_activeFeature, _selectedCategory);
}
}
requiresInvalidate = true;
}
else
{
if (feature.Geometry.Intersects(env))
{
_activeFeature = feature;
_oldCategory = _layer.GetCategory(_activeFeature);
if (_featureSet.FeatureType == FeatureType.Polygon)
{
if (!(_activeCategory is IPolygonCategory pc))
{
_activeCategory = new PolygonCategory(Color.FromArgb(55, 255, 0, 0), Color.Red, 1)
{
LegendItemVisible = false
};
}
}
if (_featureSet.FeatureType == FeatureType.Line)
{
if (!(_activeCategory is ILineCategory pc))
{
_activeCategory = new LineCategory(Color.Red, 3)
{
LegendItemVisible = false
};
}
}
_layer.SetCategory(_activeFeature, _activeCategory);
requiresInvalidate = true;
}
}
}
return requiresInvalidate;
}
/// <summary>
/// Highlighting shapes with a mouse over is something that also needs to be undone when the
/// mouse leaves. This test handles changing the colors back to normal when the mouse leaves a shape.
/// </summary>
/// <param name="e">The GeoMouseArgs parameter contains information about the mouse location and geographic coordinates.</param>
/// <returns>Boolean, true if mapframe initialize (or visual change) is necessary.</returns>
private bool ShapeRemoveHighlight(GeoMouseArgs e)
{
// If no shapes have ever been highlighted, this is meaningless.
if (_oldCategory == null)
{
return false;
}
Rectangle mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
Extent ext = Map.PixelToProj(mouseRect);
Polygon env = ext.ToEnvelope().ToPolygon();
bool requiresInvalidate = false;
if (_layer is MapPointLayer mpl)
{
int w = 3;
int h = 3;
if (mpl.GetCategory(_activeFeature) is PointCategory pc)
{
if (pc.Symbolizer.ScaleMode != ScaleMode.Geographic)
{
w = (int)pc.Symbolizer.GetSize().Width;
h = (int)pc.Symbolizer.GetSize().Height;
}
}
Rectangle rect = new Rectangle(e.Location.X - (w / 2), e.Location.Y - (h / 2), w * 2, h * 2);
if (!rect.Contains(Map.ProjToPixel(_activeFeature.Geometry.Coordinates[0])))
{
mpl.SetCategory(_activeFeature, _oldCategory);
_activeFeature = null;
requiresInvalidate = true;
}
}
else
{
if (!_activeFeature.Geometry.Intersects(env))
{
_layer.SetCategory(_activeFeature, _oldCategory);
_activeFeature = null;
requiresInvalidate = true;
}
}
return requiresInvalidate;
}
private void UpdateDragCoordinate(Coordinate loc)
{
// Cannot change selected feature at this time because we are dragging a vertex
_dragCoord.X = loc.X;
_dragCoord.Y = loc.Y;
if (_closedCircleCoord != null)
{
_closedCircleCoord.X = loc.X;
_closedCircleCoord.Y = loc.Y;
}
Map.Invalidate();
}
private void VertexHighlight()
{
// The feature is selected so color vertex that can be moved but don't highlight other shapes.
Rectangle mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
Extent ext = Map.PixelToProj(mouseRect);
if (_activeVertex != null && !ext.Contains(_activeVertex))
{
_activeVertex = null;
Map.Invalidate();
}
foreach (Coordinate c in _selectedFeature.Geometry.Coordinates)
{
if (ext.Contains(c))
{
_activeVertex = c;
Map.Invalidate();
}
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.