context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System.Data.SqlClient
{
// Summary:
// Represents a parameter to a System.Data.SqlClient.SqlCommand and optionally
// its mapping to System.Data.DataSet columns. This class cannot be inherited.
//[TypeConverter(typeof(SqlParameter.SqlParameterConverter))]
public /*sealed*/ class SqlParameter //: DbParameter, IDbDataParameter, IDataParameter, ICloneable
{
// Summary:
// Initializes a new instance of the System.Data.SqlClient.SqlParameter class.
//public SqlParameter();
//
// Summary:
// Initializes a new instance of the System.Data.SqlClient.SqlParameter class
// that uses the parameter name and a value of the new System.Data.SqlClient.SqlParameter.
//
// Parameters:
// parameterName:
// The name of the parameter to map.
//
// value:
// An System.Object that is the value of the System.Data.SqlClient.SqlParameter.
//public SqlParameter(string parameterName, object value);
//
// Summary:
// Initializes a new instance of the System.Data.SqlClient.SqlParameter class
// that uses the parameter name and the data type.
//
// Parameters:
// parameterName:
// The name of the parameter to map.
//
// dbType:
// One of the System.Data.SqlDbType values.
//
// Exceptions:
// System.ArgumentException:
// The value supplied in the dbType parameter is an invalid back-end data type.
//public SqlParameter(string parameterName, SqlDbType dbType);
//
// Summary:
// Initializes a new instance of the System.Data.SqlClient.SqlParameter class
// that uses the parameter name, the System.Data.SqlDbType, and the size.
//
// Parameters:
// parameterName:
// The name of the parameter to map.
//
// dbType:
// One of the System.Data.SqlDbType values.
//
// size:
// The length of the parameter.
//
// Exceptions:
// System.ArgumentException:
// The value supplied in the dbType parameter is an invalid back-end data type.
//public SqlParameter(string parameterName, SqlDbType dbType, int size);
//
// Summary:
// Initializes a new instance of the System.Data.SqlClient.SqlParameter class
// that uses the parameter name, the System.Data.SqlDbType, the size, and the
// source column name.
//
// Parameters:
// parameterName:
// The name of the parameter to map.
//
// dbType:
// One of the System.Data.SqlDbType values.
//
// size:
// The length of the parameter.
//
// sourceColumn:
// The name of the source column.
//
// Exceptions:
// System.ArgumentException:
// The value supplied in the dbType parameter is an invalid back-end data type.
//public SqlParameter(string parameterName, SqlDbType dbType, int size, string sourceColumn);
//
// Summary:
// Initializes a new instance of the System.Data.SqlClient.SqlParameter class
// that uses the parameter name, the type of the parameter, the size of the
// parameter, a System.Data.ParameterDirection, the precision of the parameter,
// the scale of the parameter, the source column, a System.Data.DataRowVersion
// to use, and the value of the parameter.
//
// Parameters:
// parameterName:
// The name of the parameter to map.
//
// dbType:
// One of the System.Data.SqlDbType values.
//
// size:
// The length of the parameter.
//
// direction:
// One of the System.Data.ParameterDirection values.
//
// isNullable:
// true if the value of the field can be null; otherwise false.
//
// precision:
// The total number of digits to the left and right of the decimal point to
// which System.Data.SqlClient.SqlParameter.Value is resolved.
//
// scale:
// The total number of decimal places to which System.Data.SqlClient.SqlParameter.Value
// is resolved.
//
// sourceColumn:
// The name of the source column.
//
// sourceVersion:
// One of the System.Data.DataRowVersion values.
//
// value:
// An System.Object that is the value of the System.Data.SqlClient.SqlParameter.
//
// Exceptions:
// System.ArgumentException:
// The value supplied in the dbType parameter is an invalid back-end data type.
//[EditorBrowsable(EditorBrowsableState.Advanced)]
//public SqlParameter(string parameterName, SqlDbType dbType, int size, ParameterDirection direction, bool isNullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value);
//
// Summary:
// Initializes a new instance of the System.Data.SqlClient.SqlParameter class
// that uses the parameter name, the type of the parameter, the length of the
// parameter the direction, the precision, the scale, the name of the source
// column, one of the System.Data.DataRowVersion values, a Boolean for source
// column mapping, the value of the SqlParameter, the name of the database where
// the schema collection for this XML instance is located, the owning relational
// schema where the schema collection for this XML instance is located, and
// the name of the schema collection for this parameter.
//
// Parameters:
// parameterName:
// The name of the parameter to map.
//
// dbType:
// One of the System.Data.SqlDbType values.
//
// size:
// The length of the parameter.
//
// direction:
// One of the System.Data.ParameterDirection values.
//
// precision:
// The total number of digits to the left and right of the decimal point to
// which System.Data.SqlClient.SqlParameter.Value is resolved.
//
// scale:
// The total number of decimal places to which System.Data.SqlClient.SqlParameter.Value
// is resolved.
//
// sourceColumn:
// The name of the source column.
//
// sourceVersion:
// One of the System.Data.DataRowVersion values.
//
// sourceColumnNullMapping:
// true if the source column is nullable; false if it is not.
//
// value:
// An System.Object that is the value of the System.Data.SqlClient.SqlParameter.
//
// xmlSchemaCollectionDatabase:
// The name of the database where the schema collection for this XML instance
// is located.
//
// xmlSchemaCollectionOwningSchema:
// The owning relational schema where the schema collection for this XML instance
// is located.
//
// xmlSchemaCollectionName:
// The name of the schema collection for this parameter.
//public SqlParameter(string parameterName, SqlDbType dbType, int size, ParameterDirection direction, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, bool sourceColumnNullMapping, object value, string xmlSchemaCollectionDatabase, string xmlSchemaCollectionOwningSchema, string xmlSchemaCollectionName);
// Summary:
// Gets or sets the System.Globalization.CompareInfo object that defines how
// string comparisons should be performed for this parameter.
//
// Returns:
// A System.Globalization.CompareInfo object that defines string comparison
// for this parameter.
//[Browsable(false)]
//public SqlCompareOptions CompareInfo { get; set; }
//
// Summary:
// Gets or sets the System.Data.SqlDbType of the parameter.
//
// Returns:
// One of the System.Data.SqlDbType values. The default is NVarChar.
//public override DbType DbType { get; set; }
//
// Summary:
// Gets or sets a value that indicates whether the parameter is input-only,
// output-only, bidirectional, or a stored procedure return value parameter.
//
// Returns:
// One of the System.Data.ParameterDirection values. The default is Input.
//
// Exceptions:
// System.ArgumentException:
// The property was not set to one of the valid System.Data.ParameterDirection
// values.
//[ResCategory("DataCategory_Data")]
//[RefreshProperties(RefreshProperties.All)]
//[ResDescription("DbParameter_Direction")]
//public override ParameterDirection Direction { get; set; }
//
// Summary:
// Gets or sets a value that indicates whether the parameter accepts null values.
//
// Returns:
// true if null values are accepted; otherwise false. The default is false.
//public override bool IsNullable { get; set; }
//
// Summary:
// Gets or sets the locale identifier that determines conventions and language
// for a particular region.
//
// Returns:
// Returns the locale identifier associated with the parameter.
//[Browsable(false)]
//public int LocaleId { get; set; }
//
// Summary:
// Gets or sets the offset to the System.Data.SqlClient.SqlParameter.Value property.
//
// Returns:
// The offset to the System.Data.SqlClient.SqlParameter.Value. The default is
// 0.
//[ResCategory("DataCategory_Data")]
//[ResDescription("DbParameter_Offset")]
//[Browsable(false)]
//[EditorBrowsable(EditorBrowsableState.Advanced)]
//public int Offset { get; set; }
//
// Summary:
// Gets or sets the name of the System.Data.SqlClient.SqlParameter.
//
// Returns:
// The name of the System.Data.SqlClient.SqlParameter. The default is an empty
// string.
//[ResCategory("DataCategory_Data")]
//[ResDescription("SqlParameter_ParameterName")]
//public override string ParameterName { get; set; }
//
// Summary:
// Gets or sets the maximum number of digits used to represent the System.Data.SqlClient.SqlParameter.Value
// property.
//
// Returns:
// The maximum number of digits used to represent the System.Data.SqlClient.SqlParameter.Value
// property. The default value is 0. This indicates that the data provider sets
// the precision for System.Data.SqlClient.SqlParameter.Value.
//[ResCategory("DataCategory_Data")]
//[ResDescription("DbDataParameter_Precision")]
//[DefaultValue(0)]
public virtual byte Precision
{
get
{
Contract.Ensures(Contract.Result<byte>() >= 0);
return default(byte);
}
//set;
}
//
// Summary:
// Gets or sets the number of decimal places to which System.Data.SqlClient.SqlParameter.Value
// is resolved.
//
// Returns:
// The number of decimal places to which System.Data.SqlClient.SqlParameter.Value
// is resolved. The default is 0.
//[ResDescription("DbDataParameter_Scale")]
//[ResCategory("DataCategory_Data")]
//[DefaultValue(0)]
public virtual byte Scale
{
get
{
Contract.Ensures(Contract.Result<byte>() >= 0);
return default(byte);
}
//set;
}
//
// Summary:
// Gets or sets the maximum size, in bytes, of the data within the column.
//
// Returns:
// The maximum size, in bytes, of the data within the column. The default value
// is inferred from the parameter value.
//[ResDescription("DbParameter_Size")]
//[ResCategory("DataCategory_Data")]
//public override int Size { get; set; }
//
// Summary:
// Gets or sets the name of the source column mapped to the System.Data.DataSet
// and used for loading or returning the System.Data.SqlClient.SqlParameter.Value
//
// Returns:
// The name of the source column mapped to the System.Data.DataSet. The default
// is an empty string.
//[ResDescription("DbParameter_SourceColumn")]
//[ResCategory("DataCategory_Update")]
//public override string SourceColumn { get; set; }
//
// Summary:
// Sets or gets a value which indicates whether the source column is nullable.
// This allows System.Data.SqlClient.SqlCommandBuilder to correctly generate
// Update statements for nullable columns.
//
// Returns:
// true if the source column is nullable; false if it is not.
//public override bool SourceColumnNullMapping { get; set; }
//
// Summary:
// Gets or sets the System.Data.DataRowVersion to use when you load System.Data.SqlClient.SqlParameter.Value
//
// Returns:
// One of the System.Data.DataRowVersion values. The default is Current.
//[ResCategory("DataCategory_Update")]
//[ResDescription("DbParameter_SourceVersion")]
//public override DataRowVersion SourceVersion { get; set; }
//
// Summary:
// Gets or sets the System.Data.SqlDbType of the parameter.
//
// Returns:
// One of the System.Data.SqlDbType values. The default is NVarChar.
//[ResCategory("DataCategory_Data")]
//[ResDescription("SqlParameter_SqlDbType")]
//[RefreshProperties(RefreshProperties.All)]
//[DbProviderSpecificTypeProperty(true)]
//public SqlDbType SqlDbType { get; set; }
//
// Summary:
// Gets or sets the value of the parameter as an SQL type.
//
// Returns:
// An System.Object that is the value of the parameter, using SQL types. The
// default value is null.
//[Browsable(false)]
//[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
//public object SqlValue { get; set; }
//
// Summary:
// Gets or sets the type name for a table-valued parameter.
//
// Returns:
// The type name of the specified table-valued parameter.
//[EditorBrowsable(EditorBrowsableState.Advanced)]
//[Browsable(false)]
public string TypeName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
//set;
}
//
// Summary:
// Gets or sets a string that represents a user-defined type as a parameter.
//
// Returns:
// A string that represents the fully qualified name of a user-defined type.
//[Browsable(false)]
//[EditorBrowsable(EditorBrowsableState.Advanced)]
public string UdtTypeName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
//set;
}
//
// Summary:
// Gets or sets the value of the parameter.
//
// Returns:
// An System.Object that is the value of the parameter. The default value is
// null.
//[TypeConverter(typeof(StringConverter))]
//[ResCategory("DataCategory_Data")]
//[RefreshProperties(RefreshProperties.All)]
//[ResDescription("DbParameter_Value")]
//public override object Value { get; set; }
//
// Summary:
// Gets the name of the database where the schema collection for this XML instance
// is located.
//
// Returns:
// The name of the database where the schema collection for this XML instance
// is located.
//[ResDescription("SqlParameter_XmlSchemaCollectionDatabase")]
//[ResCategory("DataCategory_Xml")]
public string XmlSchemaCollectionDatabase
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
//set;
}
//
// Summary:
// Gets the name of the schema collection for this XML instance.
//
// Returns:
// The name of the schema collection for this XML instance.
//[ResDescription("SqlParameter_XmlSchemaCollectionName")]
//[ResCategory("DataCategory_Xml")]
public string XmlSchemaCollectionName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
//set;
}
//
// Summary:
// The owning relational schema where the schema collection for this XML instance
// is located.
//
// Returns:
// An System.Data.SqlClient.SqlParameter.XmlSchemaCollectionOwningSchema.
//[ResCategory("DataCategory_Xml")]
//[ResDescription("SqlParameter_XmlSchemaCollectionOwningSchema")]
public string XmlSchemaCollectionOwningSchema
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
//set;
}
// Summary:
// Resets the type associated with this System.Data.SqlClient.SqlParameter.
//public override void ResetDbType();
//
// Summary:
// Resets the type associated with this System.Data.SqlClient.SqlParameter.
//public void ResetSqlDbType();
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
{
public class Compiler : ICompiler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// * Uses "LSL2Converter" to convert LSL to C# if necessary.
// * Compiles C#-code into an assembly
// * Returns assembly name ready for AppDomain load.
//
// Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
//
internal enum enumCompileType
{
lsl = 0,
cs = 1,
vb = 2
}
/// <summary>
/// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
/// </summary>
public int LinesToRemoveOnError = 3;
private enumCompileType DefaultCompileLanguage;
private bool WriteScriptSourceToDebugFile;
private bool CompileWithDebugInformation;
private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
private bool m_insertCoopTerminationCalls;
private string FilePrefix;
private string ScriptEnginesPath = null;
// mapping between LSL and C# line/column numbers
private ICodeConverter LSL_Converter;
private List<string> m_warnings = new List<string>();
// private object m_syncy = new object();
private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
// private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files
private static UInt64 scriptCompileCounter = 0; // And a counter
public IScriptEngine m_scriptEngine;
private Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>> m_lineMaps =
new Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>>();
public bool in_startup = true;
public Compiler(IScriptEngine scriptEngine)
{
m_scriptEngine = scriptEngine;
ScriptEnginesPath = scriptEngine.ScriptEnginePath;
ReadConfig();
}
public void ReadConfig()
{
// Get some config
WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", false);
CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true);
bool DeleteScriptsOnStartup = m_scriptEngine.Config.GetBoolean("DeleteScriptsOnStartup", true);
m_insertCoopTerminationCalls = m_scriptEngine.Config.GetString("ScriptStopStrategy", "abort") == "co-op";
// Get file prefix from scriptengine name and make it file system safe:
FilePrefix = "CommonCompiler";
foreach (char c in Path.GetInvalidFileNameChars())
{
FilePrefix = FilePrefix.Replace(c, '_');
}
if (in_startup)
{
in_startup = false;
CheckOrCreateScriptsDirectory();
// First time we start? Delete old files
if (DeleteScriptsOnStartup)
DeleteOldFiles();
}
// Map name and enum type of our supported languages
LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs);
LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb);
LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl);
// Allowed compilers
string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl");
AllowedCompilers.Clear();
#if DEBUG
m_log.Debug("[Compiler]: Allowed languages: " + allowComp);
#endif
foreach (string strl in allowComp.Split(','))
{
string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
if (!LanguageMapping.ContainsKey(strlan))
{
m_log.Error("[Compiler]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
}
else
{
#if DEBUG
//m_log.Debug("[Compiler]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
#endif
}
AllowedCompilers.Add(strlan, true);
}
if (AllowedCompilers.Count == 0)
m_log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
// Default language
string defaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower();
// Is this language recognized at all?
if (!LanguageMapping.ContainsKey(defaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
defaultCompileLanguage = "lsl";
}
// Is this language in allow-list?
if (!AllowedCompilers.ContainsKey(defaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
}
else
{
#if DEBUG
// m_log.Debug("[Compiler]: " +
// "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language.");
#endif
// LANGUAGE IS IN ALLOW-LIST
DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage];
}
// We now have an allow-list, a mapping list, and a default language
}
/// <summary>
/// Create the directory where compiled scripts are stored if it does not already exist.
/// </summary>
private void CheckOrCreateScriptsDirectory()
{
if (!Directory.Exists(ScriptEnginesPath))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString());
}
}
if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString())))
{
try
{
Directory.CreateDirectory(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()));
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()) + "\": " + ex.ToString());
}
}
}
/// <summary>
/// Delete old script files
/// </summary>
private void DeleteOldFiles()
{
foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_compiled*"))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
}
}
foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_source*"))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
}
}
}
////private ICodeCompiler icc = codeProvider.CreateCompiler();
//public string CompileFromFile(string LSOFileName)
//{
// switch (Path.GetExtension(LSOFileName).ToLower())
// {
// case ".txt":
// case ".lsl":
// Common.ScriptEngineBase.Shared.SendToDebug("Source code is LSL, converting to CS");
// return CompileFromLSLText(File.ReadAllText(LSOFileName));
// case ".cs":
// Common.ScriptEngineBase.Shared.SendToDebug("Source code is CS");
// return CompileFromCSText(File.ReadAllText(LSOFileName));
// default:
// throw new Exception("Unknown script type.");
// }
//}
public string GetCompilerOutput(string assetID)
{
/* automatically declutter the folder */
if(File.Exists(Path.Combine(ScriptEnginesPath, Path.Combine(
m_scriptEngine.World.RegionInfo.RegionID.ToString(),
FilePrefix + "_compiled_" + assetID + ".dll"))))
{
File.Delete(Path.Combine(ScriptEnginesPath, Path.Combine(
m_scriptEngine.World.RegionInfo.RegionID.ToString(),
FilePrefix + "_compiled_" + assetID + ".dll")));
}
return Path.Combine(ScriptEnginesPath, Path.Combine(
m_scriptEngine.World.RegionInfo.RegionID.ToString(),
FilePrefix + "_compiled_arriba_" + assetID + ".dll"));
}
public string GetCompilerOutput(UUID assetID)
{
return GetCompilerOutput(assetID.ToString());
}
/// <summary>
/// Converts script from LSL to CS and calls CompileFromCSText
/// </summary>
/// <param name="source">LSL script</param>
/// <returns>Filename to .dll assembly</returns>
public void PerformScriptCompile(string source, string asset, UUID ownerUUID,
out string assembly, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
{
// m_log.DebugFormat("[Compiler]: Compiling script\n{0}", Script);
IScriptModuleComms comms = m_scriptEngine.World.RequestModuleInterface<IScriptModuleComms>();
linemap = null;
m_warnings.Clear();
assembly = GetCompilerOutput(asset);
if (!Directory.Exists(ScriptEnginesPath))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception)
{
}
}
if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString())))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception)
{
}
}
// Don't recompile if we already have it
// Performing 3 file exists tests for every script can still be slow
if (File.Exists(assembly) && File.Exists(assembly + ".text") && File.Exists(assembly + ".map"))
{
// If we have already read this linemap file, then it will be in our dictionary.
// Don't build another copy of the dictionary (saves memory) and certainly
// don't keep reading the same file from disk multiple times.
if (!m_lineMaps.ContainsKey(assembly))
m_lineMaps[assembly] = ReadMapFile(assembly + ".map");
linemap = m_lineMaps[assembly];
return;
}
if (source == String.Empty)
{
throw new Exception("Cannot find script assembly and no script text present");
}
enumCompileType language = DefaultCompileLanguage;
if (source.StartsWith("//c#", true, CultureInfo.InvariantCulture))
language = enumCompileType.cs;
if (source.StartsWith("//vb", true, CultureInfo.InvariantCulture))
{
language = enumCompileType.vb;
// We need to remove //vb, it won't compile with that
source = source.Substring(4, source.Length - 4);
}
if (source.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
language = enumCompileType.lsl;
// m_log.DebugFormat("[Compiler]: Compile language is {0}", language);
if (!AllowedCompilers.ContainsKey(language.ToString()))
{
// Not allowed to compile to this language!
string errtext = String.Empty;
errtext += "The compiler for language \"" + language.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
throw new Exception(errtext);
}
if (m_scriptEngine.World.Permissions.CanCompileScript(ownerUUID, (int)language) == false)
{
// Not allowed to compile to this language!
string errtext = String.Empty;
errtext += ownerUUID + " is not in list of allowed users for this scripting language. Script will not be executed!";
throw new Exception(errtext);
}
string compileScript = source;
if (language == enumCompileType.lsl)
{
// Its LSL, convert it to C#
LSL_Converter = (ICodeConverter)new CSCodeGenerator(comms, m_insertCoopTerminationCalls);
compileScript = LSL_Converter.Convert(source);
// copy converter warnings into our warnings.
foreach (string warning in LSL_Converter.GetWarnings())
{
AddWarning(warning);
}
linemap = ((CSCodeGenerator)LSL_Converter).PositionMap;
// Write the linemap to a file and save it in our dictionary for next time.
m_lineMaps[assembly] = linemap;
WriteMapFile(assembly + ".map", linemap);
}
switch (language)
{
case enumCompileType.cs:
case enumCompileType.lsl:
compileScript = CreateCSCompilerScript(
compileScript,
m_scriptEngine.ScriptClassName,
m_scriptEngine.ScriptBaseClassName,
m_scriptEngine.ScriptBaseClassParameters);
break;
case enumCompileType.vb:
compileScript = CreateVBCompilerScript(
compileScript, m_scriptEngine.ScriptClassName, m_scriptEngine.ScriptBaseClassName);
break;
}
assembly = CompileFromDotNetText(compileScript, language, asset, assembly);
}
public string[] GetWarnings()
{
return m_warnings.ToArray();
}
private void AddWarning(string warning)
{
if (!m_warnings.Contains(warning))
{
m_warnings.Add(warning);
}
}
private static string CreateCSCompilerScript(
string compileScript, string className, string baseClassName, ParameterInfo[] constructorParameters)
{
compileScript = string.Format(
@"using OpenSim.Region.ScriptEngine.Shared;
using System.Collections.Generic;
namespace SecondLife
{{
public class {0} : {1}
{{
public {0}({2}) : base({3}) {{}}
{4}
}}
}}",
className,
baseClassName,
constructorParameters != null
? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.ToString()))
: "",
constructorParameters != null
? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.Name))
: "",
compileScript);
return compileScript;
}
private static string CreateVBCompilerScript(string compileScript, string className, string baseClassName)
{
compileScript = String.Empty +
"Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " +
String.Empty + "NameSpace SecondLife:" +
String.Empty + "Public Class " + className + ": Inherits " + baseClassName +
"\r\nPublic Sub New()\r\nEnd Sub: " +
compileScript +
":End Class :End Namespace\r\n";
return compileScript;
}
/// <summary>
/// Compile .NET script to .Net assembly (.dll)
/// </summary>
/// <param name="Script">CS script</param>
/// <returns>Filename to .dll assembly</returns>
internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset, string assembly)
{
// m_log.DebugFormat("[Compiler]: Compiling to assembly\n{0}", Script);
string ext = "." + lang.ToString();
// Output assembly name
scriptCompileCounter++;
try
{
File.Delete(assembly);
}
catch (Exception e) // NOTLEGIT - Should be just FileIOException
{
throw new Exception("Unable to delete old existing " +
"script-file before writing new. Compile aborted: " +
e.ToString());
}
// DEBUG - write source to disk
if (WriteScriptSourceToDebugFile)
{
string srcFileName = FilePrefix + "_source_" +
Path.GetFileNameWithoutExtension(assembly) + ext;
try
{
File.WriteAllText(Path.Combine(Path.Combine(
ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()),
srcFileName), Script);
}
catch (Exception ex) //NOTLEGIT - Should be just FileIOException
{
m_log.Error("[Compiler]: Exception while " +
"trying to write script source to file \"" +
srcFileName + "\": " + ex.ToString());
}
}
// Do actual compile
CompilerParameters parameters = new CompilerParameters();
parameters.IncludeDebugInformation = true;
string rootPath = AppDomain.CurrentDomain.BaseDirectory;
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenMetaverseTypes.dll"));
if (m_scriptEngine.ScriptReferencedAssemblies != null)
Array.ForEach<string>(
m_scriptEngine.ScriptReferencedAssemblies,
a => parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, a)));
parameters.GenerateExecutable = false;
parameters.OutputAssembly = assembly;
parameters.IncludeDebugInformation = CompileWithDebugInformation;
//parameters.WarningLevel = 1; // Should be 4?
parameters.TreatWarningsAsErrors = false;
CompilerResults results;
switch (lang)
{
case enumCompileType.vb:
results = VBcodeProvider.CompileAssemblyFromSource(
parameters, Script);
break;
case enumCompileType.cs:
case enumCompileType.lsl:
bool complete = false;
bool retried = false;
do
{
results = CScodeProvider.CompileAssemblyFromSource(
parameters, Script);
// Deal with an occasional segv in the compiler.
// Rarely, if ever, occurs twice in succession.
// Line # == 0 and no file name are indications that
// this is a native stack trace rather than a normal
// error log.
if (results.Errors.Count > 0)
{
if (!retried && string.IsNullOrEmpty(results.Errors[0].FileName) &&
results.Errors[0].Line == 0)
{
// System.Console.WriteLine("retrying failed compilation");
retried = true;
}
else
{
complete = true;
}
}
else
{
complete = true;
}
} while (!complete);
break;
default:
throw new Exception("Compiler is not able to recognize " +
"language type \"" + lang.ToString() + "\"");
}
// foreach (Type type in results.CompiledAssembly.GetTypes())
// {
// foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))
// {
// m_log.DebugFormat("[COMPILER]: {0}.{1}", type.FullName, method.Name);
// }
// }
//
// WARNINGS AND ERRORS
//
bool hadErrors = false;
string errtext = String.Empty;
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
string severity = CompErr.IsWarning ? "Warning" : "Error";
KeyValuePair<int, int> errorPos;
// Show 5 errors max, but check entire list for errors
if (severity == "Error")
{
// C# scripts will not have a linemap since theres no line translation involved.
if (!m_lineMaps.ContainsKey(assembly))
errorPos = new KeyValuePair<int, int>(CompErr.Line, CompErr.Column);
else
errorPos = FindErrorPosition(CompErr.Line, CompErr.Column, m_lineMaps[assembly]);
string text = CompErr.ErrorText;
// Use LSL type names
if (lang == enumCompileType.lsl)
text = ReplaceTypes(CompErr.ErrorText);
// The Second Life viewer's script editor begins
// countingn lines and columns at 0, so we subtract 1.
errtext += String.Format("({0},{1}): {4} {2}: {3}\n",
errorPos.Key - 1, errorPos.Value - 1,
CompErr.ErrorNumber, text, severity);
hadErrors = true;
}
}
}
if (hadErrors)
{
throw new Exception(errtext);
}
// On today's highly asynchronous systems, the result of
// the compile may not be immediately apparent. Wait a
// reasonable amount of time before giving up on it.
if (!File.Exists(assembly))
{
for (int i = 0; i < 20 && !File.Exists(assembly); i++)
{
System.Threading.Thread.Sleep(250);
}
// One final chance...
if (!File.Exists(assembly))
{
errtext = String.Empty;
errtext += "No compile error. But not able to locate compiled file.";
throw new Exception(errtext);
}
}
// m_log.DebugFormat("[Compiler] Compiled new assembly "+
// "for {0}", asset);
// Because windows likes to perform exclusive locks, we simply
// write out a textual representation of the file here
//
// Read the binary file into a buffer
//
FileInfo fi = new FileInfo(assembly);
if (fi == null)
{
errtext = String.Empty;
errtext += "No compile error. But not able to stat file.";
throw new Exception(errtext);
}
Byte[] data = new Byte[fi.Length];
try
{
FileStream fs = File.Open(assembly, FileMode.Open, FileAccess.Read);
fs.Read(data, 0, data.Length);
fs.Close();
}
catch (Exception)
{
errtext = String.Empty;
errtext += "No compile error. But not able to open file.";
throw new Exception(errtext);
}
// Convert to base64
//
string filetext = System.Convert.ToBase64String(data);
Byte[] buf = Encoding.ASCII.GetBytes(filetext);
FileStream sfs = File.Create(assembly + ".text");
sfs.Write(buf, 0, buf.Length);
sfs.Close();
return assembly;
}
private class kvpSorter : IComparer<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>>
{
public int Compare(KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> a,
KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> b)
{
int kc = a.Key.Key.CompareTo(b.Key.Key);
return (kc != 0) ? kc : a.Key.Value.CompareTo(b.Key.Value);
}
}
public static KeyValuePair<int, int> FindErrorPosition(int line,
int col, Dictionary<KeyValuePair<int, int>,
KeyValuePair<int, int>> positionMap)
{
if (positionMap == null || positionMap.Count == 0)
return new KeyValuePair<int, int>(line, col);
KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
out ret))
return ret;
List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>> sorted = new List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>>(positionMap);
sorted.Sort(new kvpSorter());
int l = 1;
int c = 1;
int pl = 1;
foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> posmap in sorted)
{
//m_log.DebugFormat("[Compiler]: Scanning line map {0},{1} --> {2},{3}", posmap.Key.Key, posmap.Key.Value, posmap.Value.Key, posmap.Value.Value);
int nl = posmap.Value.Key + line - posmap.Key.Key; // New, translated LSL line and column.
int nc = posmap.Value.Value + col - posmap.Key.Value;
// Keep going until we find the first point passed line,col.
if (posmap.Key.Key > line)
{
//m_log.DebugFormat("[Compiler]: Line is larger than requested {0},{1}, returning {2},{3}", line, col, l, c);
if (pl < line)
{
//m_log.DebugFormat("[Compiler]: Previous line ({0}) is less than requested line ({1}), setting column to 1.", pl, line);
c = 1;
}
break;
}
if (posmap.Key.Key == line && posmap.Key.Value > col)
{
// Never move l,c backwards.
if (nl > l || (nl == l && nc > c))
{
//m_log.DebugFormat("[Compiler]: Using offset relative to this: {0} + {1} - {2}, {3} + {4} - {5} = {6}, {7}",
// posmap.Value.Key, line, posmap.Key.Key, posmap.Value.Value, col, posmap.Key.Value, nl, nc);
l = nl;
c = nc;
}
//m_log.DebugFormat("[Compiler]: Column is larger than requested {0},{1}, returning {2},{3}", line, col, l, c);
break;
}
pl = posmap.Key.Key;
l = posmap.Value.Key;
c = posmap.Value.Value;
}
return new KeyValuePair<int, int>(l, c);
}
string ReplaceTypes(string message)
{
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
"string");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
"integer");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
"float");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
"list");
return message;
}
private static void WriteMapFile(string filename, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
{
string mapstring = String.Empty;
foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in linemap)
{
KeyValuePair<int, int> k = kvp.Key;
KeyValuePair<int, int> v = kvp.Value;
mapstring += String.Format("{0},{1},{2},{3}\n", k.Key, k.Value, v.Key, v.Value);
}
Byte[] mapbytes = Encoding.ASCII.GetBytes(mapstring);
FileStream mfs = File.Create(filename);
mfs.Write(mapbytes, 0, mapbytes.Length);
mfs.Close();
}
private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ReadMapFile(string filename)
{
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
try
{
StreamReader r = File.OpenText(filename);
linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
string line;
while ((line = r.ReadLine()) != null)
{
String[] parts = line.Split(new Char[] { ',' });
int kk = System.Convert.ToInt32(parts[0]);
int kv = System.Convert.ToInt32(parts[1]);
int vk = System.Convert.ToInt32(parts[2]);
int vv = System.Convert.ToInt32(parts[3]);
KeyValuePair<int, int> k = new KeyValuePair<int, int>(kk, kv);
KeyValuePair<int, int> v = new KeyValuePair<int, int>(vk, vv);
linemap[k] = v;
}
}
catch
{
linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
}
return linemap;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: main/java/com/ruletechgames/proto/characterManage.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Com.Ruletechgames.Proto {
/// <summary>Holder for reflection information generated from main/java/com/ruletechgames/proto/characterManage.proto</summary>
public static partial class CharacterManageReflection {
#region Descriptor
/// <summary>File descriptor for main/java/com/ruletechgames/proto/characterManage.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CharacterManageReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjdtYWluL2phdmEvY29tL3J1bGV0ZWNoZ2FtZXMvcHJvdG8vY2hhcmFjdGVy",
"TWFuYWdlLnByb3RvEhdjb20ucnVsZXRlY2hnYW1lcy5wcm90byKqAgoRY2hh",
"cmFjdGVyQ3JlYXRpb24SDAoETmFtZRgBIAEoCRIvCgRyYWNlGAIgASgOMiEu",
"Y29tLnJ1bGV0ZWNoZ2FtZXMucHJvdG8uY2hhclR5cGUSDQoFbGV2ZWwYAyAB",
"KAUSDgoGZ2VuZGVyGAQgASgJEg0KBVRpdGxlGAUgASgJEjMKC2F2YXRhckNs",
"YXNzGAYgASgOMh4uY29tLnJ1bGV0ZWNoZ2FtZXMucHJvdG8uQ2xhc3MSDgoG",
"aGVpZ2h0GAcgASgFEjAKBWJUeXBlGAggASgOMiEuY29tLnJ1bGV0ZWNoZ2Ft",
"ZXMucHJvdG8uQm9keVR5cGUSMQoFY29sb3IYCSABKA4yIi5jb20ucnVsZXRl",
"Y2hnYW1lcy5wcm90by5Ta2luQ29sb3IqPQoIY2hhclR5cGUSCQoFSHVtYW4Q",
"ABIMCghZaWxhdmVpbhABEgwKCERlbW9yaWFuEAISCgoGWGVwaGlsEAMqHgoG",
"R2VuZGVyEggKBE1hbGUQABIKCgZGZW1hbGUQASpICgVDbGFzcxIICgRNYWdl",
"EAASCwoHV2FycmlrYRABEgwKCEFuY2llbnRzEAISCgoGQXJjaGVyEAMSDgoK",
"QXVyYU1hc3RlchAEKigKCEJvZHlUeXBlEggKBFNsaW0QABIJCgVIZWF2eRAB",
"EgcKA0ZhdBACKlgKCVNraW5Db2xvchINCglQYWxlV2hpdGUQABIJCgVXaGl0",
"ZRABEg8KC1RhbmlzaFdoaXRlEAISBwoDVGFuEAMSCQoFQnJvd24QBBIMCghU",
"YW5Ccm93bhAFQi4KF2NvbS5ydWxldGVjaGdhbWVzLnByb3RvQhNjaGFyYWN0",
"ZXJNYW5hZ2VCYXNlYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Com.Ruletechgames.Proto.charType), typeof(global::Com.Ruletechgames.Proto.Gender), typeof(global::Com.Ruletechgames.Proto.Class), typeof(global::Com.Ruletechgames.Proto.BodyType), typeof(global::Com.Ruletechgames.Proto.SkinColor), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Com.Ruletechgames.Proto.characterCreation), global::Com.Ruletechgames.Proto.characterCreation.Parser, new[]{ "Name", "Race", "Level", "Gender", "Title", "AvatarClass", "Height", "BType", "Color" }, null, null, null)
}));
}
#endregion
}
#region Enums
public enum charType {
[pbr::OriginalName("Human")] Human = 0,
[pbr::OriginalName("Yilavein")] Yilavein = 1,
[pbr::OriginalName("Demorian")] Demorian = 2,
[pbr::OriginalName("Xephil")] Xephil = 3,
}
public enum Gender {
[pbr::OriginalName("Male")] Male = 0,
[pbr::OriginalName("Female")] Female = 1,
}
public enum Class {
[pbr::OriginalName("Mage")] Mage = 0,
[pbr::OriginalName("Warrika")] Warrika = 1,
[pbr::OriginalName("Ancients")] Ancients = 2,
[pbr::OriginalName("Archer")] Archer = 3,
[pbr::OriginalName("AuraMaster")] AuraMaster = 4,
}
public enum BodyType {
[pbr::OriginalName("Slim")] Slim = 0,
[pbr::OriginalName("Heavy")] Heavy = 1,
[pbr::OriginalName("Fat")] Fat = 2,
}
public enum SkinColor {
[pbr::OriginalName("PaleWhite")] PaleWhite = 0,
[pbr::OriginalName("White")] White = 1,
[pbr::OriginalName("TanishWhite")] TanishWhite = 2,
[pbr::OriginalName("Tan")] Tan = 3,
[pbr::OriginalName("Brown")] Brown = 4,
[pbr::OriginalName("TanBrown")] TanBrown = 5,
}
#endregion
#region Messages
public sealed partial class characterCreation : pb::IMessage<characterCreation> {
private static readonly pb::MessageParser<characterCreation> _parser = new pb::MessageParser<characterCreation>(() => new characterCreation());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<characterCreation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Com.Ruletechgames.Proto.CharacterManageReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public characterCreation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public characterCreation(characterCreation other) : this() {
name_ = other.name_;
race_ = other.race_;
level_ = other.level_;
gender_ = other.gender_;
title_ = other.title_;
avatarClass_ = other.avatarClass_;
height_ = other.height_;
bType_ = other.bType_;
color_ = other.color_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public characterCreation Clone() {
return new characterCreation(this);
}
/// <summary>Field number for the "Name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "race" field.</summary>
public const int RaceFieldNumber = 2;
private global::Com.Ruletechgames.Proto.charType race_ = 0;
/// <summary>
/// Possible Enum?
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Com.Ruletechgames.Proto.charType Race {
get { return race_; }
set {
race_ = value;
}
}
/// <summary>Field number for the "level" field.</summary>
public const int LevelFieldNumber = 3;
private int level_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Level {
get { return level_; }
set {
level_ = value;
}
}
/// <summary>Field number for the "gender" field.</summary>
public const int GenderFieldNumber = 4;
private string gender_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Gender {
get { return gender_; }
set {
gender_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Title" field.</summary>
public const int TitleFieldNumber = 5;
private string title_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Title {
get { return title_; }
set {
title_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "avatarClass" field.</summary>
public const int AvatarClassFieldNumber = 6;
private global::Com.Ruletechgames.Proto.Class avatarClass_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Com.Ruletechgames.Proto.Class AvatarClass {
get { return avatarClass_; }
set {
avatarClass_ = value;
}
}
/// <summary>Field number for the "height" field.</summary>
public const int HeightFieldNumber = 7;
private int height_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Height {
get { return height_; }
set {
height_ = value;
}
}
/// <summary>Field number for the "bType" field.</summary>
public const int BTypeFieldNumber = 8;
private global::Com.Ruletechgames.Proto.BodyType bType_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Com.Ruletechgames.Proto.BodyType BType {
get { return bType_; }
set {
bType_ = value;
}
}
/// <summary>Field number for the "color" field.</summary>
public const int ColorFieldNumber = 9;
private global::Com.Ruletechgames.Proto.SkinColor color_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Com.Ruletechgames.Proto.SkinColor Color {
get { return color_; }
set {
color_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as characterCreation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(characterCreation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Race != other.Race) return false;
if (Level != other.Level) return false;
if (Gender != other.Gender) return false;
if (Title != other.Title) return false;
if (AvatarClass != other.AvatarClass) return false;
if (Height != other.Height) return false;
if (BType != other.BType) return false;
if (Color != other.Color) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Race != 0) hash ^= Race.GetHashCode();
if (Level != 0) hash ^= Level.GetHashCode();
if (Gender.Length != 0) hash ^= Gender.GetHashCode();
if (Title.Length != 0) hash ^= Title.GetHashCode();
if (AvatarClass != 0) hash ^= AvatarClass.GetHashCode();
if (Height != 0) hash ^= Height.GetHashCode();
if (BType != 0) hash ^= BType.GetHashCode();
if (Color != 0) hash ^= Color.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Race != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) Race);
}
if (Level != 0) {
output.WriteRawTag(24);
output.WriteInt32(Level);
}
if (Gender.Length != 0) {
output.WriteRawTag(34);
output.WriteString(Gender);
}
if (Title.Length != 0) {
output.WriteRawTag(42);
output.WriteString(Title);
}
if (AvatarClass != 0) {
output.WriteRawTag(48);
output.WriteEnum((int) AvatarClass);
}
if (Height != 0) {
output.WriteRawTag(56);
output.WriteInt32(Height);
}
if (BType != 0) {
output.WriteRawTag(64);
output.WriteEnum((int) BType);
}
if (Color != 0) {
output.WriteRawTag(72);
output.WriteEnum((int) Color);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Race != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Race);
}
if (Level != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Level);
}
if (Gender.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Gender);
}
if (Title.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Title);
}
if (AvatarClass != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) AvatarClass);
}
if (Height != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Height);
}
if (BType != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) BType);
}
if (Color != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Color);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(characterCreation other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Race != 0) {
Race = other.Race;
}
if (other.Level != 0) {
Level = other.Level;
}
if (other.Gender.Length != 0) {
Gender = other.Gender;
}
if (other.Title.Length != 0) {
Title = other.Title;
}
if (other.AvatarClass != 0) {
AvatarClass = other.AvatarClass;
}
if (other.Height != 0) {
Height = other.Height;
}
if (other.BType != 0) {
BType = other.BType;
}
if (other.Color != 0) {
Color = other.Color;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 16: {
race_ = (global::Com.Ruletechgames.Proto.charType) input.ReadEnum();
break;
}
case 24: {
Level = input.ReadInt32();
break;
}
case 34: {
Gender = input.ReadString();
break;
}
case 42: {
Title = input.ReadString();
break;
}
case 48: {
avatarClass_ = (global::Com.Ruletechgames.Proto.Class) input.ReadEnum();
break;
}
case 56: {
Height = input.ReadInt32();
break;
}
case 64: {
bType_ = (global::Com.Ruletechgames.Proto.BodyType) input.ReadEnum();
break;
}
case 72: {
color_ = (global::Com.Ruletechgames.Proto.SkinColor) input.ReadEnum();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators.CSharp;
using Type = CppSharp.AST.Type;
namespace CppSharp.Generators.CLI
{
/// <summary>
/// Generates C++/CLI source files.
/// </summary>
public class CLISources : CLITemplate
{
public CLISources(BindingContext context, IEnumerable<TranslationUnit> units)
: base(context, units)
{
}
public override string FileExtension { get { return "cpp"; } }
public override void Process()
{
GenerateFilePreamble(CommentKind.BCPL);
var file = Path.GetFileNameWithoutExtension(TranslationUnit.FileName)
.Replace('\\', '/');
if (Context.Options.GenerateName != null)
file = Context.Options.GenerateName(TranslationUnit);
PushBlock(BlockKind.Includes);
WriteLine("#include \"{0}.h\"", file);
GenerateForwardReferenceHeaders();
NewLine();
PopBlock();
PushBlock(BlockKind.Usings);
WriteLine("using namespace System;");
WriteLine("using namespace System::Runtime::InteropServices;");
foreach (var customUsingStatement in Options.DependentNameSpaces)
{
WriteLine(string.Format("using namespace {0};", customUsingStatement)); ;
}
NewLine();
PopBlock();
GenerateDeclContext(TranslationUnit);
PushBlock(BlockKind.Footer);
PopBlock();
}
public void GenerateForwardReferenceHeaders()
{
PushBlock(BlockKind.IncludesForwardReferences);
var typeReferenceCollector = new CLITypeReferenceCollector(Context.TypeMaps, Context.Options);
typeReferenceCollector.Process(TranslationUnit, filterNamespaces: false);
var includes = new SortedSet<string>(StringComparer.InvariantCulture);
foreach (var typeRef in typeReferenceCollector.TypeReferences)
{
if (typeRef.Include.File == TranslationUnit.FileName)
continue;
var include = typeRef.Include;
if(!string.IsNullOrEmpty(include.File) && !include.InHeader)
includes.Add(include.ToString());
}
foreach (var include in includes)
WriteLine(include);
PopBlock();
}
private void GenerateDeclContext(DeclarationContext @namespace)
{
PushBlock(BlockKind.Namespace);
foreach (var @class in @namespace.Classes)
{
if ([email protected] || @class.IsDependent)
continue;
if (@class.IsOpaque || @class.IsIncomplete)
continue;
GenerateClass(@class);
}
// Generate all the function declarations for the module.
foreach (var function in @namespace.Functions.Where(f => f.IsGenerated))
{
GenerateFunction(function, @namespace);
NewLine();
}
if (Options.GenerateFunctionTemplates)
{
foreach (var template in @namespace.Templates)
{
if (!template.IsGenerated) continue;
var functionTemplate = template as FunctionTemplate;
if (functionTemplate == null) continue;
if (!functionTemplate.IsGenerated)
continue;
GenerateFunctionTemplate(functionTemplate);
}
}
foreach(var childNamespace in @namespace.Namespaces)
GenerateDeclContext(childNamespace);
PopBlock();
}
public void GenerateClass(Class @class)
{
PushBlock(BlockKind.Class);
GenerateDeclContext(@class);
GenerateClassConstructors(@class);
GenerateClassMethods(@class, @class);
if (CLIGenerator.ShouldGenerateClassNativeField(@class))
{
var qualifiedIdentifier = QualifiedIdentifier(@class);
PushBlock(BlockKind.Method);
WriteLine("System::IntPtr {0}::{1}::get()",
qualifiedIdentifier, Helpers.InstanceIdentifier);
WriteStartBraceIndent();
WriteLine("return System::IntPtr(NativePtr);");
WriteCloseBraceIndent();
PopBlock(NewLineKind.BeforeNextBlock);
PushBlock(BlockKind.Method);
WriteLine("void {0}::{1}::set(System::IntPtr object)",
qualifiedIdentifier, Helpers.InstanceIdentifier);
WriteStartBraceIndent();
var nativeType = string.Format("::{0}*", @class.QualifiedOriginalName);
WriteLine("NativePtr = ({0})object.ToPointer();", nativeType);
WriteCloseBraceIndent();
PopBlock(NewLineKind.BeforeNextBlock);
}
GenerateClassProperties(@class, @class);
foreach (var @event in @class.Events)
{
if ([email protected])
continue;
GenerateDeclarationCommon(@event);
GenerateEvent(@event, @class);
}
foreach (var variable in @class.Variables)
{
if (!variable.IsGenerated)
continue;
if (variable.Access != AccessSpecifier.Public)
continue;
GenerateDeclarationCommon(variable);
GenerateVariable(variable, @class);
}
PopBlock();
}
private void GenerateClassConstructors(Class @class)
{
if (@class.IsStatic)
return;
// Output a default constructor that takes the native pointer.
GenerateClassConstructor(@class);
if (@class.IsRefType)
{
var destructor = @class.Destructors
.FirstOrDefault(d => d.Parameters.Count == 0 && d.Access == AccessSpecifier.Public);
if (destructor != null)
{
GenerateClassDestructor(@class);
if (Options.GenerateFinalizers)
GenerateClassFinalizer(@class);
}
}
}
private void GenerateClassMethods(Class @class, Class realOwner)
{
if (@class.IsValueType)
foreach (var @base in @class.Bases.Where(b => b.IsClass && !b.Class.Ignore))
GenerateClassMethods(@base.Class, realOwner);
foreach (var method in @class.Methods.Where(m => @class == realOwner || !m.IsOperator))
{
if (ASTUtils.CheckIgnoreMethod(method) || CLIHeaders.FunctionIgnored(method))
continue;
// C++/CLI does not allow special member funtions for value types.
if (@class.IsValueType && method.IsCopyConstructor)
continue;
// Do not generate constructors or destructors from base classes.
var declaringClass = method.Namespace as Class;
if (declaringClass != realOwner && (method.IsConstructor || method.IsDestructor))
continue;
GenerateMethod(method, realOwner);
}
}
private void GenerateClassProperties(Class @class, Class realOwner)
{
if (@class.IsValueType)
{
foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared))
{
GenerateClassProperties(@base.Class, realOwner);
}
}
foreach (var property in @class.Properties.Where(
p => !ASTUtils.CheckIgnoreProperty(p) && !p.IsInRefTypeAndBackedByValueClassField() &&
!CLIHeaders.TypeIgnored(p.Type)))
GenerateProperty(property, realOwner);
}
private void GenerateClassDestructor(Class @class)
{
PushBlock(BlockKind.Destructor);
WriteLine("{0}::~{1}()", QualifiedIdentifier(@class), @class.Name);
WriteStartBraceIndent();
if (CLIGenerator.ShouldGenerateClassNativeField(@class))
{
WriteLine("delete NativePtr;");
}
else if (@class.HasNonTrivialDestructor)
{
WriteLine("if (NativePtr)");
WriteStartBraceIndent();
WriteLine("auto __nativePtr = NativePtr;");
WriteLine("NativePtr = 0;");
WriteLine("delete (::{0}*) __nativePtr;", @class.QualifiedOriginalName);
WriteCloseBraceIndent();
}
WriteCloseBraceIndent();
PopBlock(NewLineKind.BeforeNextBlock);
}
private void GenerateClassFinalizer(Class @class)
{
PushBlock(BlockKind.Finalizer);
WriteLine("{0}::!{1}()", QualifiedIdentifier(@class), @class.Name);
WriteStartBraceIndent();
if (CLIGenerator.ShouldGenerateClassNativeField(@class))
WriteLine("delete NativePtr;");
WriteCloseBraceIndent();
PopBlock(NewLineKind.BeforeNextBlock);
}
private void GenerateFunctionTemplate(FunctionTemplate template)
{
PushBlock(BlockKind.Template);
var function = template.TemplatedFunction;
var typePrinter = new CLITypePrinter(Context)
{
Declaration = template
};
typePrinter.PushContext(TypePrinterContextKind.Template);
var retType = function.ReturnType.Visit(typePrinter);
var typeNames = "";
var paramNames = template.Parameters.Select(param => param.Name).ToList();
if (paramNames.Any())
typeNames = "typename " + string.Join(", typename ", paramNames);
WriteLine("generic<{0}>", typeNames);
WriteLine("{0} {1}::{2}({3})", retType,
QualifiedIdentifier(function.Namespace), function.Name,
GenerateParametersList(function.Parameters));
WriteStartBraceIndent();
var @class = function.Namespace as Class;
GenerateFunctionCall(function, @class);
WriteCloseBraceIndent();
NewLine();
PopBlock(NewLineKind.BeforeNextBlock);
}
private void GenerateProperty(Property property, Class realOwner)
{
PushBlock(BlockKind.Property);
if (property.Field != null)
{
if (property.HasGetter)
GeneratePropertyGetter(property.Field, realOwner, property.Name,
property.Type);
if (property.HasSetter)
GeneratePropertySetter(property.Field, realOwner, property.Name,
property.Type);
}
else
{
if (property.HasGetter)
GeneratePropertyGetter(property.GetMethod, realOwner, property.Name,
property.Type);
if (property.HasSetter)
if (property.IsIndexer)
GeneratePropertySetter(property.SetMethod, realOwner, property.Name,
property.Type, property.GetMethod.Parameters[0]);
else
GeneratePropertySetter(property.SetMethod, realOwner, property.Name,
property.Type);
}
PopBlock();
}
private void GeneratePropertySetter<T>(T decl, Class @class, string name, Type type, Parameter indexParameter = null)
where T : Declaration, ITypedDecl
{
if (decl == null)
return;
var args = new List<string>();
var isIndexer = indexParameter != null;
if (isIndexer)
args.Add(string.Format("{0} {1}", indexParameter.Type, indexParameter.Name));
var function = decl as Function;
var argName = function != null && !isIndexer ? function.Parameters[0].Name : "value";
args.Add(string.Format("{0} {1}", type, argName));
WriteLine("void {0}::{1}::set({2})", QualifiedIdentifier(@class),
name, string.Join(", ", args));
WriteStartBraceIndent();
if (decl is Function && !isIndexer)
{
var func = decl as Function;
GenerateFunctionCall(func, @class);
}
else
{
if (@class.IsValueType && decl is Field)
{
WriteLine("{0} = value;", decl.Name);
WriteCloseBraceIndent();
NewLine();
return;
}
var param = new Parameter
{
Name = "value",
QualifiedType = new QualifiedType(type)
};
string variable;
if (decl is Variable)
variable = string.Format("::{0}::{1}",
@class.QualifiedOriginalName, decl.OriginalName);
else
variable = string.Format("((::{0}*)NativePtr)->{1}",
@class.QualifiedOriginalName, decl.OriginalName);
var ctx = new MarshalContext(Context)
{
Parameter = param,
ArgName = param.Name,
ReturnVarName = variable
};
var marshal = new CLIMarshalManagedToNativePrinter(ctx);
param.Visit(marshal);
if (isIndexer)
{
var ctx2 = new MarshalContext(Context)
{
Parameter = indexParameter,
ArgName = indexParameter.Name
};
var marshal2 = new CLIMarshalManagedToNativePrinter(ctx2);
indexParameter.Visit(marshal2);
variable += string.Format("({0})", marshal2.Context.Return);
}
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
if (marshal.Context.Return.StringBuilder.Length > 0)
{
if (isIndexer && decl.Type.IsPointer())
WriteLine("*({0}) = {1};", variable, marshal.Context.Return);
else
WriteLine("{0} = {1};", variable, marshal.Context.Return);
}
}
WriteCloseBraceIndent();
NewLine();
}
private void GeneratePropertyGetter<T>(T decl, Class @class, string name, Type type)
where T : Declaration, ITypedDecl
{
if (decl == null)
return;
var method = decl as Method;
var isIndexer = method != null &&
method.OperatorKind == CXXOperatorKind.Subscript;
var args = new List<string>();
if (isIndexer)
{
var indexParameter = method.Parameters[0];
args.Add(string.Format("{0} {1}", indexParameter.Type, indexParameter.Name));
}
WriteLine("{0} {1}::{2}::get({3})", type, QualifiedIdentifier(@class),
name, string.Join(", ", args));
WriteStartBraceIndent();
if (decl is Function)
{
var func = decl as Function;
if (isIndexer && func.Type.IsAddress())
GenerateFunctionCall(func, @class, type);
else
GenerateFunctionCall(func, @class);
}
else
{
if (@class.IsValueType && decl is Field)
{
WriteLine("return {0};", decl.Name);
WriteCloseBraceIndent();
NewLine();
return;
}
string variable;
if (decl is Variable)
variable = string.Format("::{0}::{1}",
@class.QualifiedOriginalName, decl.OriginalName);
else
variable = string.Format("((::{0}*)NativePtr)->{1}",
@class.QualifiedOriginalName, decl.OriginalName);
var ctx = new MarshalContext(Context)
{
Declaration = decl,
ArgName = decl.Name,
ReturnVarName = variable,
ReturnType = decl.QualifiedType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
decl.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("return {0};", marshal.Context.Return);
}
WriteCloseBraceIndent();
NewLine();
}
private void GenerateEvent(Event @event, Class @class)
{
GenerateEventAdd(@event, @class);
NewLine();
GenerateEventRemove(@event, @class);
NewLine();
GenerateEventRaise(@event, @class);
NewLine();
GenerateEventRaiseWrapper(@event, @class);
NewLine();
}
private void GenerateEventAdd(Event @event, Class @class)
{
WriteLine("void {0}::{1}::add({2} evt)", QualifiedIdentifier(@class),
@event.Name, @event.Type);
WriteStartBraceIndent();
var delegateName = string.Format("_{0}Delegate", @event.Name);
WriteLine("if (!{0}Instance)", delegateName);
WriteStartBraceIndent();
var typePrinter = new CppTypePrinter();
var args = typePrinter.VisitParameters(@event.Parameters, hasNames: false);
WriteLine("{0}Instance = gcnew {0}(this, &{1}::_{2}Raise);",
delegateName, QualifiedIdentifier(@class), @event.Name);
WriteLine("auto _fptr = (void (*)({0}))Marshal::GetFunctionPointerForDelegate({1}Instance).ToPointer();",
args, delegateName);
WriteLine("((::{0}*)NativePtr)->{1}.Connect(_fptr);", @class.QualifiedOriginalName,
@event.OriginalName);
WriteCloseBraceIndent();
WriteLine("_{0} = static_cast<{1}>(System::Delegate::Combine(_{0}, evt));",
@event.Name, @event.Type);
WriteCloseBraceIndent();
}
private void GenerateEventRemove(Event @event, Class @class)
{
WriteLine("void {0}::{1}::remove({2} evt)", QualifiedIdentifier(@class),
@event.Name, @event.Type);
WriteStartBraceIndent();
WriteLine("_{0} = static_cast<{1}>(System::Delegate::Remove(_{0}, evt));",
@event.Name, @event.Type);
WriteCloseBraceIndent();
}
private void GenerateEventRaise(Event @event, Class @class)
{
var typePrinter = new CLITypePrinter(Context);
var args = typePrinter.VisitParameters(@event.Parameters, hasNames: true);
WriteLine("void {0}::{1}::raise({2})", QualifiedIdentifier(@class),
@event.Name, args);
WriteStartBraceIndent();
var paramNames = @event.Parameters.Select(param => param.Name).ToList();
WriteLine("_{0}({1});", @event.Name, string.Join(", ", paramNames));
WriteCloseBraceIndent();
}
private void GenerateEventRaiseWrapper(Event @event, Class @class)
{
var typePrinter = new CppTypePrinter();
var args = typePrinter.VisitParameters(@event.Parameters, hasNames: true);
WriteLine("void {0}::_{1}Raise({2})", QualifiedIdentifier(@class),
@event.Name, args);
WriteStartBraceIndent();
var returns = new List<string>();
foreach (var param in @event.Parameters)
{
var ctx = new MarshalContext(Context)
{
ReturnVarName = param.Name,
ReturnType = param.QualifiedType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
param.Visit(marshal);
returns.Add(marshal.Context.Return);
}
Write("{0}::raise(", @event.Name);
Write("{0}", string.Join(", ", returns));
WriteLine(");");
WriteCloseBraceIndent();
}
private void GenerateVariable(Variable variable, Class @class)
{
GeneratePropertyGetter(variable, @class, variable.Name, variable.Type);
var arrayType = variable.Type as ArrayType;
var qualifiedType = arrayType != null ? arrayType.QualifiedType : variable.QualifiedType;
if (!qualifiedType.Qualifiers.IsConst)
GeneratePropertySetter(variable, @class, variable.Name, variable.Type);
}
private void GenerateClassConstructor(Class @class)
{
string qualifiedIdentifier = QualifiedIdentifier(@class);
Write("{0}::{1}(", qualifiedIdentifier, @class.Name);
var nativeType = string.Format("::{0}*", @class.QualifiedOriginalName);
WriteLine("{0} native)", nativeType);
var hasBase = GenerateClassConstructorBase(@class);
if (CLIGenerator.ShouldGenerateClassNativeField(@class))
{
PushIndent();
Write(hasBase ? "," : ":");
PopIndent();
WriteLine(" {0}(false)", Helpers.OwnsNativeInstanceIdentifier);
}
WriteStartBraceIndent();
const string nativePtr = "native";
if (@class.IsRefType)
{
if (!hasBase)
{
WriteLine("NativePtr = {0};", nativePtr);
}
}
else
{
GenerateStructMarshaling(@class, nativePtr + "->");
}
WriteCloseBraceIndent();
NewLine();
WriteLine("{0}^ {0}::{1}(::System::IntPtr native)", qualifiedIdentifier, Helpers.CreateInstanceIdentifier);
WriteStartBraceIndent();
WriteLine("return gcnew ::{0}(({1}) native.ToPointer());", qualifiedIdentifier, nativeType);
WriteCloseBraceIndent();
NewLine();
}
private void GenerateStructMarshaling(Class @class, string nativeVar)
{
foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared))
{
GenerateStructMarshaling(@base.Class, nativeVar);
}
int paramIndex = 0;
foreach (var property in @class.Properties.Where(
p => !ASTUtils.CheckIgnoreProperty(p) && !CLIHeaders.TypeIgnored(p.Type)))
{
if (property.Field == null)
continue;
var nativeField = string.Format("{0}{1}",
nativeVar, property.Field.OriginalName);
var ctx = new MarshalContext(Context)
{
ArgName = property.Name,
ReturnVarName = nativeField,
ReturnType = property.QualifiedType,
Declaration = property.Field,
ParameterIndex = paramIndex++
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
property.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("{0} = {1};", property.Field.Name, marshal.Context.Return);
}
}
private bool GenerateClassConstructorBase(Class @class, Method method = null)
{
var hasBase = @class.HasBase && @class.Bases[0].IsClass && @class.Bases[0].Class.IsDeclared;
if (!hasBase)
return false;
if ([email protected])
{
PushIndent();
var baseClass = @class.Bases[0].Class;
Write(": {0}(", QualifiedIdentifier(baseClass));
// We cast the value to the base clas type since otherwise there
// could be ambiguous call to overloaded constructors.
var cppTypePrinter = new CppTypePrinter();
var nativeTypeName = baseClass.Visit(cppTypePrinter);
Write("({0}*)", nativeTypeName);
WriteLine("{0})", method != null ? "nullptr" : "native");
PopIndent();
}
return true;
}
public void GenerateMethod(Method method, Class @class)
{
if (CLIHeaders.FunctionIgnored(method))
return;
PushBlock(BlockKind.Method, method);
if (method.IsConstructor || method.IsDestructor ||
method.OperatorKind == CXXOperatorKind.Conversion ||
method.OperatorKind == CXXOperatorKind.ExplicitConversion)
Write("{0}::{1}(", QualifiedIdentifier(@class), GetMethodName(method));
else
Write("{0} {1}::{2}(", method.ReturnType, QualifiedIdentifier(@class),
method.Name);
GenerateMethodParameters(method);
WriteLine(")");
if (method.IsConstructor)
GenerateClassConstructorBase(@class, method: method);
WriteStartBraceIndent();
PushBlock(BlockKind.MethodBody, method);
if (method.IsConstructor && @class.IsRefType)
WriteLine("{0} = true;", Helpers.OwnsNativeInstanceIdentifier);
if (method.IsProxy)
goto SkipImpl;
if (@class.IsRefType)
{
if (method.IsConstructor)
{
if ([email protected])
{
var @params = GenerateFunctionParamsMarshal(method.Parameters, method);
Write("NativePtr = new ::{0}(", method.Namespace.QualifiedOriginalName);
GenerateFunctionParams(@params);
WriteLine(");");
}
}
else
{
GenerateFunctionCall(method, @class);
}
}
else if (@class.IsValueType)
{
if (!method.IsConstructor)
GenerateFunctionCall(method, @class);
else
GenerateValueTypeConstructorCall(method, @class);
}
SkipImpl:
PopBlock();
WriteCloseBraceIndent();
if (method.OperatorKind == CXXOperatorKind.EqualEqual)
{
GenerateEquals(method, @class);
}
PopBlock(NewLineKind.Always);
}
private void GenerateEquals(Function method, Class @class)
{
Class leftHandSide;
Class rightHandSide;
if (method.Parameters[0].Type.SkipPointerRefs().TryGetClass(out leftHandSide) &&
leftHandSide.OriginalPtr == @class.OriginalPtr &&
method.Parameters[1].Type.SkipPointerRefs().TryGetClass(out rightHandSide) &&
rightHandSide.OriginalPtr == @class.OriginalPtr)
{
NewLine();
var qualifiedIdentifier = QualifiedIdentifier(@class);
WriteLine("bool {0}::Equals(::System::Object^ obj)", qualifiedIdentifier);
WriteStartBraceIndent();
if (@class.IsRefType)
{
WriteLine("return this == safe_cast<{0}^>(obj);", qualifiedIdentifier);
}
else
{
WriteLine("return *this == safe_cast<{0}>(obj);", qualifiedIdentifier);
}
WriteCloseBraceIndent();
}
}
private void GenerateValueTypeConstructorCall(Method method, Class @class)
{
var names = new List<string>();
var paramIndex = 0;
foreach (var param in method.Parameters)
{
var ctx = new MarshalContext(Context)
{
Function = method,
Parameter = param,
ArgName = param.Name,
ParameterIndex = paramIndex++
};
var marshal = new CLIMarshalManagedToNativePrinter(ctx);
param.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
names.Add(marshal.Context.Return);
}
WriteLine("::{0} _native({1});", @class.QualifiedOriginalName,
string.Join(", ", names));
GenerateValueTypeConstructorCallProperties(@class);
}
private void GenerateValueTypeConstructorCallProperties(Class @class)
{
foreach (var @base in @class.Bases.Where(b => b.IsClass && b.Class.IsDeclared))
{
GenerateValueTypeConstructorCallProperties(@base.Class);
}
foreach (var property in @class.Properties)
{
if (!property.IsDeclared || property.Field == null) continue;
var varName = string.Format("_native.{0}", property.Field.OriginalName);
var ctx = new MarshalContext(Context)
{
ReturnVarName = varName,
ReturnType = property.QualifiedType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
property.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("this->{0} = {1};", property.Name, marshal.Context.Return);
}
}
public void GenerateFunction(Function function, DeclarationContext @namespace)
{
if (!function.IsGenerated || CLIHeaders.FunctionIgnored(function))
return;
GenerateDeclarationCommon(function);
var classSig = string.Format("{0}::{1}", QualifiedIdentifier(@namespace),
TranslationUnit.FileNameWithoutExtension);
Write("{0} {1}::{2}(", function.ReturnType, classSig,
function.Name);
for (var i = 0; i < function.Parameters.Count; ++i)
{
var param = function.Parameters[i];
Write("{0}", TypePrinter.VisitParameter(param));
if (i < function.Parameters.Count - 1)
Write(", ");
}
WriteLine(")");
WriteStartBraceIndent();
GenerateFunctionCall(function);
WriteCloseBraceIndent();
}
public void GenerateFunctionCall(Function function, Class @class = null, Type publicRetType = null)
{
CheckArgumentRange(function);
if (function.OperatorKind == CXXOperatorKind.EqualEqual ||
function.OperatorKind == CXXOperatorKind.ExclaimEqual)
{
WriteLine("bool {0}Null = ReferenceEquals({0}, nullptr);",
function.Parameters[0].Name);
WriteLine("bool {0}Null = ReferenceEquals({0}, nullptr);",
function.Parameters[1].Name);
WriteLine("if ({0}Null || {1}Null)",
function.Parameters[0].Name, function.Parameters[1].Name);
WriteLineIndent("return {0}{1}Null && {2}Null{3};",
function.OperatorKind == CXXOperatorKind.EqualEqual ? string.Empty : "!(",
function.Parameters[0].Name, function.Parameters[1].Name,
function.OperatorKind == CXXOperatorKind.EqualEqual ? string.Empty : ")");
}
var retType = function.ReturnType;
if (publicRetType == null)
publicRetType = retType.Type;
var needsReturn = !retType.Type.IsPrimitiveType(PrimitiveType.Void);
const string valueMarshalName = "_this0";
var isValueType = @class != null && @class.IsValueType;
if (isValueType && !IsNativeFunctionOrStaticMethod(function))
{
WriteLine("auto {0} = ::{1}();", valueMarshalName, @class.QualifiedOriginalName);
var param = new Parameter { Name = "(*this)" , Namespace = function.Namespace };
var ctx = new MarshalContext(Context)
{
MarshalVarPrefix = valueMarshalName,
Parameter = param
};
var marshal = new CLIMarshalManagedToNativePrinter(ctx);
marshal.MarshalValueClassProperties(@class, valueMarshalName);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
}
var @params = GenerateFunctionParamsMarshal(function.Parameters, function);
var returnIdentifier = Helpers.ReturnIdentifier;
if (needsReturn)
if (retType.Type.IsReference())
Write("auto &{0} = ", returnIdentifier);
else
Write("auto {0} = ", returnIdentifier);
if (function.OperatorKind == CXXOperatorKind.Conversion ||
function.OperatorKind == CXXOperatorKind.ExplicitConversion)
{
var method = function as Method;
var typePrinter = new CppTypePrinter();
var typeName = method.ConversionType.Visit(typePrinter);
WriteLine("({0}) {1};", typeName, @params[0].Name);
}
else if (function.IsOperator &&
function.OperatorKind != CXXOperatorKind.Subscript)
{
var opName = function.Name.Replace("operator", "").Trim();
switch (Operators.ClassifyOperator(function))
{
case CXXOperatorArity.Unary:
WriteLine("{0} {1};", opName, @params[0].Name);
break;
case CXXOperatorArity.Binary:
WriteLine("{0} {1} {2};", @params[0].Name, opName, @params[1].Name);
break;
}
}
else
{
if (IsNativeFunctionOrStaticMethod(function))
{
Write("::{0}(", function.QualifiedOriginalName);
}
else
{
if (isValueType)
Write("{0}.", valueMarshalName);
else if (IsNativeMethod(function))
Write("((::{0}*)NativePtr)->", @class.QualifiedOriginalName);
Write("{0}(", function.OriginalName);
}
GenerateFunctionParams(@params);
WriteLine(");");
}
foreach(var paramInfo in @params)
{
var param = paramInfo.Param;
if(param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut)
continue;
if (param.Type.IsPointer() && !param.Type.GetFinalPointee().IsPrimitiveType())
param.QualifiedType = new QualifiedType(param.Type.GetFinalPointee());
var nativeVarName = paramInfo.Name;
var ctx = new MarshalContext(Context)
{
ArgName = nativeVarName,
ReturnVarName = nativeVarName,
ReturnType = param.QualifiedType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
param.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("{0} = {1};",param.Name,marshal.Context.Return);
}
if (isValueType && !IsNativeFunctionOrStaticMethod(function))
{
GenerateStructMarshaling(@class, valueMarshalName + ".");
}
if (needsReturn)
{
var retTypeName = retType.Visit(TypePrinter).ToString();
var isIntPtr = retTypeName.Contains("IntPtr");
if (retType.Type.IsPointer() && (isIntPtr || retTypeName.EndsWith("^", StringComparison.Ordinal)))
{
WriteLine("if ({0} == nullptr) return {1};",
returnIdentifier,
isIntPtr ? "System::IntPtr()" : "nullptr");
}
var ctx = new MarshalContext(Context)
{
ArgName = returnIdentifier,
ReturnVarName = returnIdentifier,
ReturnType = retType
};
var marshal = new CLIMarshalNativeToManagedPrinter(ctx);
retType.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
// Special case for indexer - needs to dereference if the internal
// function is a pointer type and the property is not.
if (retType.Type.IsPointer() &&
retType.Type.GetPointee().Equals(publicRetType) &&
publicRetType.IsPrimitiveType())
WriteLine("return *({0});", marshal.Context.Return);
else if (retType.Type.IsReference() && publicRetType.IsReference())
WriteLine("return ({0})({1});", publicRetType, marshal.Context.Return);
else
WriteLine("return {0};", marshal.Context.Return);
}
}
private void CheckArgumentRange(Function method)
{
if (Context.Options.MarshalCharAsManagedChar)
{
foreach (var param in method.Parameters.Where(
p => p.Type.IsPrimitiveType(PrimitiveType.Char)))
{
WriteLine("if ({0} < System::Char::MinValue || {0} > System::SByte::MaxValue)", param.Name);
// C++/CLI can actually handle char -> sbyte in all case, this is for compatibility with the C# generator
WriteLineIndent(
"throw gcnew System::OverflowException(\"{0} must be in the range {1} - {2}.\");",
param.Name, (int) char.MinValue, sbyte.MaxValue);
}
}
}
private static bool IsNativeMethod(Function function)
{
var method = function as Method;
if (method == null)
return false;
return method.Conversion == MethodConversionKind.None;
}
private static bool IsNativeFunctionOrStaticMethod(Function function)
{
var method = function as Method;
if (method == null)
return true;
if (method.IsOperator && Operators.IsBuiltinOperator(method.OperatorKind))
return true;
return method.IsStatic || method.Conversion != MethodConversionKind.None;
}
public struct ParamMarshal
{
public string Name;
public string Prefix;
public Parameter Param;
}
public List<ParamMarshal> GenerateFunctionParamsMarshal(IEnumerable<Parameter> @params,
Function function = null)
{
var marshals = new List<ParamMarshal>();
var paramIndex = 0;
foreach (var param in @params)
{
marshals.Add(GenerateFunctionParamMarshal(param, paramIndex, function));
paramIndex++;
}
return marshals;
}
private ParamMarshal GenerateFunctionParamMarshal(Parameter param, int paramIndex,
Function function = null)
{
var paramMarshal = new ParamMarshal { Name = param.Name, Param = param };
if (param.Type is BuiltinType)
return paramMarshal;
var argName = Generator.GeneratedIdentifier("arg") + paramIndex.ToString(CultureInfo.InvariantCulture);
var isRef = param.IsOut || param.IsInOut;
// Since both pointers and references to types are wrapped as CLI
// tracking references when using in/out, we normalize them here to be able
// to use the same code for marshaling.
var paramType = param.Type;
if (paramType is PointerType && isRef)
{
if (!paramType.IsReference())
paramMarshal.Prefix = "&";
paramType = (paramType as PointerType).Pointee;
}
var effectiveParam = new Parameter(param)
{
QualifiedType = new QualifiedType(paramType)
};
var ctx = new MarshalContext(Context)
{
Parameter = effectiveParam,
ParameterIndex = paramIndex,
ArgName = argName,
Function = function
};
var marshal = new CLIMarshalManagedToNativePrinter(ctx);
effectiveParam.Visit(marshal);
if (string.IsNullOrEmpty(marshal.Context.Return))
throw new Exception(string.Format("Cannot marshal argument of function '{0}'",
function.QualifiedOriginalName));
if (isRef)
{
var typePrinter = new CppTypePrinter();
var type = paramType.Visit(typePrinter);
if (param.IsInOut)
{
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("{0} {1} = {2};", type, argName, marshal.Context.Return);
}
else
WriteLine("{0} {1};", type, argName);
}
else
{
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
Write(marshal.Context.Before);
WriteLine("auto {0}{1} = {2};", marshal.VarPrefix, argName,
marshal.Context.Return);
paramMarshal.Prefix = marshal.ArgumentPrefix;
}
paramMarshal.Name = argName;
return paramMarshal;
}
public void GenerateFunctionParams(List<ParamMarshal> @params)
{
var names = @params.Select(param =>
{
if (!string.IsNullOrWhiteSpace(param.Prefix))
return param.Prefix + param.Name;
return param.Name;
}).ToList();
Write(string.Join(", ", names));
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="EdmFunction.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Class for representing a function
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
public sealed class EdmFunction : EdmType
{
#region Constructors
internal EdmFunction(string name, string namespaceName, DataSpace dataSpace, EdmFunctionPayload payload)
: base(name, namespaceName, dataSpace)
{
//---- name of the 'schema'
//---- this is used by the SQL Gen utility and update pipeline to support generation of the correct function name in the store
_schemaName = payload.Schema;
_fullName = this.NamespaceName + "." + this.Name;
FunctionParameter[] returnParameters = payload.ReturnParameters;
Debug.Assert(returnParameters.All((returnParameter) => returnParameter != null), "All return parameters must be non-null");
Debug.Assert(returnParameters.All((returnParameter) => returnParameter.Mode == ParameterMode.ReturnValue), "Return parameter in a function must have the ParameterMode equal to ReturnValue.");
_returnParameters = new ReadOnlyMetadataCollection<FunctionParameter>(
returnParameters
.Select((returnParameter) => SafeLink<EdmFunction>.BindChild<FunctionParameter>(this, FunctionParameter.DeclaringFunctionLinker, returnParameter))
.ToList());
if (payload.IsAggregate.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.Aggregate, payload.IsAggregate.Value);
if (payload.IsBuiltIn.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.BuiltIn, payload.IsBuiltIn.Value);
if (payload.IsNiladic.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.NiladicFunction, payload.IsNiladic.Value);
if (payload.IsComposable.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.IsComposable, payload.IsComposable.Value);
if (payload.IsFromProviderManifest.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.IsFromProviderManifest, payload.IsFromProviderManifest.Value);
if (payload.IsCachedStoreFunction.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.IsCachedStoreFunction, payload.IsCachedStoreFunction.Value);
if (payload.IsFunctionImport.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.IsFunctionImport, payload.IsFunctionImport.Value);
if (payload.ParameterTypeSemantics.HasValue)
{
_parameterTypeSemantics = payload.ParameterTypeSemantics.Value;
}
if (payload.StoreFunctionName != null)
{
_storeFunctionNameAttribute = payload.StoreFunctionName;
}
if (payload.EntitySets != null)
{
Debug.Assert(_returnParameters.Count == payload.EntitySets.Length, "The number of entity sets should match the number of return parameters");
_entitySets = new ReadOnlyMetadataCollection<EntitySet>(payload.EntitySets);
}
else
{
var list = new List<EntitySet>();
if (_returnParameters.Count != 0)
{
Debug.Assert(_returnParameters.Count == 1, "If there was more than one result set payload.EntitySets should not have been null");
list.Add(null);
}
_entitySets = new ReadOnlyMetadataCollection<EntitySet>(list);
}
if (payload.CommandText != null)
{
_commandTextAttribute = payload.CommandText;
}
if (payload.Parameters != null)
{
// validate the parameters
foreach (FunctionParameter parameter in payload.Parameters)
{
if (parameter == null)
{
throw EntityUtil.CollectionParameterElementIsNull("parameters");
}
Debug.Assert(parameter.Mode != ParameterMode.ReturnValue, "No function parameter can have ParameterMode equal to ReturnValue.");
}
// Populate the parameters
_parameters = new SafeLinkCollection<EdmFunction, FunctionParameter>(this, FunctionParameter.DeclaringFunctionLinker, new MetadataCollection<FunctionParameter>(payload.Parameters));
}
else
{
_parameters = new ReadOnlyMetadataCollection<FunctionParameter>(new MetadataCollection<FunctionParameter>());
}
}
#endregion
#region Fields
private readonly ReadOnlyMetadataCollection<FunctionParameter> _returnParameters;
private readonly ReadOnlyMetadataCollection<FunctionParameter> _parameters;
private readonly FunctionAttributes _functionAttributes = FunctionAttributes.Default;
private readonly string _storeFunctionNameAttribute;
private readonly ParameterTypeSemantics _parameterTypeSemantics;
private readonly string _commandTextAttribute;
private readonly string _schemaName;
private readonly ReadOnlyMetadataCollection<EntitySet> _entitySets;
private readonly string _fullName;
#endregion
#region Properties
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.EdmFunction; } }
/// <summary>
/// Returns the full name of this type, which is namespace + "." + name.
/// </summary>
public override string FullName
{
get
{
return _fullName;
}
}
/// <summary>
/// Gets the collection of parameters
/// </summary>
public ReadOnlyMetadataCollection<FunctionParameter> Parameters
{
get
{
return _parameters;
}
}
/// <summary>
/// Returns true if this is a C-space function and it has an eSQL body defined as DefiningExpression.
/// </summary>
internal bool HasUserDefinedBody
{
get
{
return this.IsModelDefinedFunction && !String.IsNullOrEmpty(this.CommandTextAttribute);
}
}
/// <summary>
/// For function imports, optionally indicates the entity set to which the result is bound.
/// If the function import has multiple result sets, returns the entity set to which the first result is bound
/// </summary>
[MetadataProperty(BuiltInTypeKind.EntitySet, false)]
internal EntitySet EntitySet
{
get
{
return _entitySets.Count != 0 ? _entitySets[0] : null;
}
}
/// <summary>
/// For function imports, indicates the entity sets to which the return parameters are bound.
/// The number of elements in the collection matches the number of return parameters.
/// A null element in the collection indicates that the corresponding are not bound to an entity set.
/// </summary>
[MetadataProperty(BuiltInTypeKind.EntitySet, true)]
internal ReadOnlyMetadataCollection<EntitySet> EntitySets
{
get
{
return _entitySets;
}
}
/// <summary>
/// Gets the return parameter of this function
/// </summary>
[MetadataProperty(BuiltInTypeKind.FunctionParameter, false)]
public FunctionParameter ReturnParameter
{
get
{
return _returnParameters.FirstOrDefault();
}
}
/// <summary>
/// Gets the return parameters of this function
/// </summary>
[MetadataProperty(BuiltInTypeKind.FunctionParameter, true)]
public ReadOnlyMetadataCollection<FunctionParameter> ReturnParameters
{
get
{
return _returnParameters;
}
}
[MetadataProperty(PrimitiveTypeKind.String, false)]
internal string StoreFunctionNameAttribute
{
get { return _storeFunctionNameAttribute; }
}
[MetadataProperty(typeof(ParameterTypeSemantics), false)]
internal ParameterTypeSemantics ParameterTypeSemanticsAttribute
{
get { return _parameterTypeSemantics; }
}
// Function attribute parameters
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
internal bool AggregateAttribute
{
get
{
return GetFunctionAttribute(FunctionAttributes.Aggregate);
}
}
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
internal bool BuiltInAttribute
{
get
{
return GetFunctionAttribute(FunctionAttributes.BuiltIn);
}
}
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
internal bool IsFromProviderManifest
{
get
{
return GetFunctionAttribute(FunctionAttributes.IsFromProviderManifest);
}
}
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
internal bool NiladicFunctionAttribute
{
get
{
return GetFunctionAttribute(FunctionAttributes.NiladicFunction);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Composable")]
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
public bool IsComposableAttribute
{
get
{
return GetFunctionAttribute(FunctionAttributes.IsComposable);
}
}
[MetadataProperty(PrimitiveTypeKind.String, false)]
public string CommandTextAttribute
{
get
{
return _commandTextAttribute;
}
}
internal bool IsCachedStoreFunction
{
get
{
return GetFunctionAttribute(FunctionAttributes.IsCachedStoreFunction);
}
}
internal bool IsModelDefinedFunction
{
get
{
return this.DataSpace == DataSpace.CSpace && !IsCachedStoreFunction && !IsFromProviderManifest && !IsFunctionImport;
}
}
internal bool IsFunctionImport
{
get
{
return GetFunctionAttribute(FunctionAttributes.IsFunctionImport);
}
}
[MetadataProperty(PrimitiveTypeKind.String, false)]
internal string Schema
{
get
{
return _schemaName;
}
}
#endregion
#region Methods
/// <summary>
/// Sets this item to be readonly, once this is set, the item will never be writable again.
/// </summary>
internal override void SetReadOnly()
{
if (!IsReadOnly)
{
base.SetReadOnly();
this.Parameters.Source.SetReadOnly();
foreach (FunctionParameter returnParameter in ReturnParameters)
{
returnParameter.SetReadOnly();
}
}
}
/// <summary>
/// Builds function identity string in the form of "functionName (param1, param2, ... paramN)".
/// </summary>
internal override void BuildIdentity(StringBuilder builder)
{
// If we've already cached the identity, simply append it
if (null != CacheIdentity)
{
builder.Append(CacheIdentity);
return;
}
EdmFunction.BuildIdentity(
builder,
FullName,
Parameters,
(param) => param.TypeUsage,
(param) => param.Mode);
}
/// <summary>
/// Builds identity based on the functionName and parameter types. All parameters are assumed to be <see cref="ParameterMode.In"/>.
/// Returns string in the form of "functionName (param1, param2, ... paramN)".
/// </summary>
internal static string BuildIdentity(string functionName, IEnumerable<TypeUsage> functionParameters)
{
StringBuilder identity = new StringBuilder();
BuildIdentity(
identity,
functionName,
functionParameters,
(param) => param,
(param) => ParameterMode.In);
return identity.ToString();
}
/// <summary>
/// Builds identity based on the functionName and parameters metadata.
/// Returns string in the form of "functionName (param1, param2, ... paramN)".
/// </summary>
internal static void BuildIdentity<TParameterMetadata>(StringBuilder builder,
string functionName,
IEnumerable<TParameterMetadata> functionParameters,
Func<TParameterMetadata, TypeUsage> getParameterTypeUsage,
Func<TParameterMetadata, ParameterMode> getParameterMode)
{
//
// Note: some callers depend on the format of the returned identity string.
//
// Start with the function name
builder.Append(functionName);
// Then add the string representing the list of parameters
builder.Append('(');
bool first = true;
foreach (TParameterMetadata parameter in functionParameters)
{
if (first) { first = false; }
else { builder.Append(","); }
builder.Append(Helper.ToString(getParameterMode(parameter)));
builder.Append(' ');
getParameterTypeUsage(parameter).BuildIdentity(builder);
}
builder.Append(')');
}
private bool GetFunctionAttribute(FunctionAttributes attribute)
{
return attribute == (attribute & _functionAttributes);
}
private static void SetFunctionAttribute(ref FunctionAttributes field, FunctionAttributes attribute, bool isSet)
{
if (isSet)
{
// make sure that attribute bits are set to 1
field |= attribute;
}
else
{
// make sure that attribute bits are set to 0
field ^= field & attribute;
}
}
#endregion
#region Nested types
[Flags]
private enum FunctionAttributes : byte
{
None = 0,
Aggregate = 1,
BuiltIn = 2,
NiladicFunction = 4,
IsComposable = 8,
IsFromProviderManifest = 16,
IsCachedStoreFunction = 32,
IsFunctionImport = 64,
Default = IsComposable,
}
#endregion
}
internal struct EdmFunctionPayload
{
public string Name;
public string NamespaceName;
public string Schema;
public string StoreFunctionName;
public string CommandText;
public EntitySet[] EntitySets;
public bool? IsAggregate;
public bool? IsBuiltIn;
public bool? IsNiladic;
public bool? IsComposable;
public bool? IsFromProviderManifest;
public bool? IsCachedStoreFunction;
public bool? IsFunctionImport;
public FunctionParameter[] ReturnParameters;
public ParameterTypeSemantics? ParameterTypeSemantics;
public FunctionParameter[] Parameters;
public DataSpace DataSpace;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.Its.Domain.Authorization;
using Its.Validation;
using Its.Validation.Configuration;
using Newtonsoft.Json;
namespace Microsoft.Its.Domain
{
/// <summary>
/// A command that can be applied to an target to trigger some action and record an applicable state change.
/// </summary>
/// <typeparam name="TTarget">The type of the target.</typeparam>
[DebuggerStepThrough]
[DebuggerDisplay("{ToString()}")]
public abstract class Command<TTarget> : Command, ICommand<TTarget>
where TTarget : class
{
private static readonly ConcurrentDictionary<string, Type> knownTypesByName = new ConcurrentDictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
private static readonly ConcurrentDictionary<string, Type> handlerTypesByName = new ConcurrentDictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
private static readonly Type[] knownTypes = Discover.ConcreteTypesDerivedFrom(typeof (ICommand<TTarget>)).ToArray();
/// <summary>
/// The default authorization method used by all commands for <typeparamref name="TTarget" />.
/// </summary>
public static Func<TTarget, Command<TTarget>, bool> AuthorizeDefault = (target, command) => command.Principal.IsAuthorizedTo(command, target);
private dynamic handler;
protected Command(string etag = null) : base(etag)
{
}
/// <summary>
/// Performs the action of the command upon the target.
/// </summary>
/// <param name="target">The target to which to apply the command.</param>
/// <exception cref="CommandValidationException">
/// If the command cannot be applied due its state or the state of the target, it should throw a
/// <see
/// cref="CommandValidationException" />
/// indicating the specifics of the failure.
/// </exception>
public virtual void ApplyTo(TTarget target)
{
if (target == null)
{
throw new ArgumentNullException("target");
}
if (!string.IsNullOrWhiteSpace(ETag))
{
var eventSourced = target as IEventSourced;
if (eventSourced.HasETag(ETag))
{
return;
}
}
// validate that the command's state is valid in and of itself
var validationReport = RunAllValidations(target, false);
using (CommandContext.Establish(this))
{
if (validationReport.HasFailures)
{
HandleCommandValidationFailure(target, validationReport);
}
else
{
EnactCommand(target);
}
}
}
/// <summary>
/// Performs the action of the command upon the target.
/// </summary>
/// <param name="target">The target to which to apply the command.</param>
/// <exception cref="CommandValidationException">
/// If the command cannot be applied due its state or the state of the target, it should throw a
/// <see
/// cref="CommandValidationException" />
/// indicating the specifics of the failure.
/// </exception>
public virtual async Task ApplyToAsync(TTarget target)
{
if (target == null)
{
throw new ArgumentNullException("target");
}
if (!string.IsNullOrWhiteSpace(ETag))
{
var eventSourced = target as IEventSourced;
if (eventSourced != null && eventSourced.HasETag(ETag))
{
return;
}
}
var validationReport = RunAllValidations(target, false);
using (CommandContext.Establish(this))
{
if (validationReport.HasFailures)
{
HandleCommandValidationFailure(target, validationReport);
}
else
{
await EnactCommandAsync(target);
}
}
}
/// <summary>
/// Enacts the command once authorizations and validations have succeeded.
/// </summary>
/// <param name="target">The target upon which to enact the command.</param>
protected virtual void EnactCommand(TTarget target)
{
Task.Run(() => EnactCommandAsync(target)).Wait();
}
/// <summary>
/// Enacts the command once authorizations and validations have succeeded.
/// </summary>
/// <param name="target">The target upon which to enact the command.</param>
protected virtual async Task EnactCommandAsync(TTarget target)
{
if (Handler == null)
{
Action enactCommand = () => ((dynamic) target).EnactCommand((dynamic) this);
await Task.Run(enactCommand);
}
else
{
await (Task) Handler.EnactCommand((dynamic) target, (dynamic) this);
}
}
private bool CommandHandlerIsRegistered()
{
return handlerTypesByName.GetOrAdd(CommandName, name =>
{
var handlerType = CommandHandler.Type(typeof (TTarget), GetType());
var handlerTypes = CommandHandler.KnownTypes.DerivedFrom(handlerType).ToArray();
var numberOfHandlerTypes = handlerTypes.Length;
if (numberOfHandlerTypes == 1)
{
return handlerTypes.Single();
}
if (numberOfHandlerTypes > 1)
{
throw new DomainConfigurationException(
string.Format("Multiple handler implementations were found for {0}: {1}. This might be a mistake. If not, you must register one explicitly using Configuration.UseDependency.",
handlerType.FullName,
handlerTypes.Select(t => t.FullName).ToDelimitedString(", ")));
}
return null;
}) != null;
}
protected virtual void HandleCommandValidationFailure(TTarget target, ValidationReport validationReport)
{
if (target is EventSourcedAggregate)
{
((dynamic) target).HandleCommandValidationFailure((dynamic) this,
validationReport);
}
else
{
throw new CommandValidationException(
string.Format("Validation error while applying {0} to a {1}.",
CommandName,
target.GetType().Name),
validationReport);
}
}
internal dynamic Handler
{
get
{
if (handler == null && CommandHandlerIsRegistered())
{
handler = Configuration.Current.Container.Resolve(handlerTypesByName[CommandName]);
}
return handler;
}
}
internal void AuthorizeOrThrow(TTarget target)
{
if (!Authorize(target))
{
throw new CommandAuthorizationException("Unauthorized");
}
}
internal ValidationReport RunAllValidations(TTarget target, bool throwOnValidationFailure = false)
{
AuthorizeOrThrow(target);
if (AppliesToVersion != null)
{
var eventSourced = target as IEventSourced;
if (eventSourced != null && AppliesToVersion != eventSourced.Version)
{
throw new ConcurrencyException(
string.Format("The command's AppliesToVersion value ({0}) does not match the aggregate's version ({1})",
AppliesToVersion,
eventSourced.Version));
}
}
// first validate the command's validity in and of itself
ValidationReport validationReport;
try
{
validationReport = ExecutePreparedCommandValidator();
}
catch (RuntimeBinderException ex)
{
throw new InvalidOperationException(string.Format(
"Property CommandValidator returned a validator of the wrong type. It should return a {0}, but returned a {1}",
typeof (IValidationRule<>).MakeGenericType(GetType()),
CommandValidator.GetType()), ex);
}
if (validationReport.HasFailures)
{
if (throwOnValidationFailure)
{
throw new CommandValidationException(string.Format("{0} is invalid.", CommandName), validationReport);
}
return validationReport;
}
return ExecuteValidator(target);
}
private ValidationReport ExecuteValidator(TTarget target)
{
return (Validator ??
new ValidationRule<TTarget>(a => true)
.WithSuccessMessage("No rules defined for " + GetType()))
.Execute(target);
}
private ValidationReport ExecutePreparedCommandValidator()
{
var validator = PrepareCommandValidator();
return ((dynamic) validator).Execute((dynamic) this);
}
private object PrepareCommandValidator()
{
// TODO: (PrepareCommandValidator) optimize
var commandValidator = CommandValidator;
if (commandValidator.GetType() == typeof (ValidationPlan<>).MakeGenericType(GetType()))
{
// it's a ValidationPlan<TCommand>
return commandValidator;
}
// it's a ValidationRule. wrap it in a ValidationPlan in order to be able to call Execute.
var plan = Validation.CreateEmptyPlanFor(GetType());
((dynamic) plan).Add((dynamic) commandValidator);
return plan;
}
/// <summary>
/// Determines whether the command is authorized to be applied to the specified target.
/// </summary>
/// <param name="target">The target.</param>
/// <returns>true if the command is authorized; otherwise, false.</returns>
public virtual bool Authorize(TTarget target)
{
return AuthorizeDefault(target, this);
}
/// <summary>
/// If set, requires that the command be applied to this version of the target; otherwise, <see cref="ApplyTo" /> will throw..
/// </summary>
public virtual long? AppliesToVersion { get; set; }
/// <summary>
/// Gets a validator that can be used to check the valididty of the command against the state of the target before it is applied.
/// </summary>
[JsonIgnore]
public virtual IValidationRule<TTarget> Validator
{
get
{
return null;
}
}
/// <summary>
/// Gets a validator to check the state of the command in and of itself, as distinct from an target.
/// </summary>
/// <remarks>
/// By default, this returns a <see cref="ValidationPlan{TCommand}" /> where TCommand is the command's actual type, with rules built up from any System.ComponentModel.DataAnnotations attributes applied to its properties.
/// </remarks>
[JsonIgnore]
public virtual IValidationRule CommandValidator
{
get
{
return Validation.GetDefaultPlanFor(GetType());
}
}
/// <summary>
/// Gets all of the the types implementing <see cref="Command{T}" /> discovered within the AppDomain.
/// </summary>
public new static Type[] KnownTypes
{
get
{
return knownTypes;
}
}
/// <summary>
/// Gets the command type having the specified name.
/// </summary>
public static Type Named(string name)
{
return
knownTypesByName.GetOrAdd(name,
n =>
KnownTypes.SingleOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
}
public static IValidationRule<TTarget> CommandHasNotBeenApplied(ICommand command)
{
if (string.IsNullOrWhiteSpace(command.ETag) || typeof (EventSourcedAggregate).IsAssignableFrom(typeof (TTarget)))
{
return Validate.That<TTarget>(a => true)
.WithSuccessMessage("Command is not checked for idempotency via the ETag property.");
}
return Validate.That<TTarget>(target => (target as EventSourcedAggregate)
.Events()
.OfType<Event>()
.Every(e => e.ETag != command.ETag))
.WithErrorMessage(string.Format("Command with ETag '{0}' has already been applied.", command.ETag));
}
public override string ToString()
{
return string.Format("{0}.{1}",
typeof (TTarget).Name,
CommandName);
}
}
}
| |
#pragma warning disable CS0162, CS0164, CS0168, CS0649
namespace P.Program
{
using P.Runtime;
using System;
using System.Collections.Generic;
public partial class Application : StateImpl
{
public partial class Events
{
public static PrtEventValue event_POrbPublish;
public static PrtEventValue event_POrbSubscribe;
public static void Events_porb()
{
event_POrbPublish = new PrtEventValue(new PrtEvent("POrbPublish", Types.type_POrbPubMsgType, PrtEvent.DefaultMaxInstances, false));
event_POrbSubscribe = new PrtEventValue(new PrtEvent("POrbSubscribe", Types.type_POrbSubMsgType, PrtEvent.DefaultMaxInstances, false));
}
}
public partial class Types
{
public static PrtType type_1_958407665;
public static PrtType type_2_958407665;
public static PrtType type_POrbSubMsgType;
public static PrtType type_4_958407665;
public static PrtType type_5_958407665;
public static PrtType type_POrbPubMsgType;
public static PrtType type_6_958407665;
public static PrtType type_7_958407665;
public static PrtType type_8_958407665;
public static PrtType type_9_958407665;
public static PrtType type_10_958407665;
public static PrtType type_11_958407665;
public static PrtType type_12_958407665;
public static PrtType type_13_958407665;
static public void Types_porb()
{
Types.type_1_958407665 = new PrtEnumType("Topics", "heartbeat_topic", 0, "attitude_topic", 1, "global_position_topic", 2, "local_position_topic", 3, "battery_status_topic", 4, "gps_raw_int_topic", 5, "gps_status_topic", 6, "command_ack_topic", 7, "extended_sys_state_topic", 8, "px4status_topic", 9, "altitude_reached_topic", 10, "geofence_reached_topic", 11, "heartbeat_status_topic", 12, "battery_critical_topic", 13, "gps_health_topic", 14, "vehicle_ready_topic", 15, "vehicle_armed_topic", 16, "vehicle_disarmed_topic", 17, "vehicle_landed_topic", 18, "vehicle_loitering_topic", 19, "vehicle_crashed_topic", 20);
Types.type_2_958407665 = new PrtMachineType();
Types.type_POrbSubMsgType = new PrtNamedTupleType(new object[]{"topic", Types.type_1_958407665, "sub", Types.type_2_958407665});
Types.type_4_958407665 = new PrtEventType();
Types.type_5_958407665 = new PrtAnyType();
Types.type_POrbPubMsgType = new PrtNamedTupleType(new object[]{"topic", Types.type_1_958407665, "ev", Types.type_4_958407665, "payload", Types.type_5_958407665});
Types.type_6_958407665 = new PrtIntType();
Types.type_7_958407665 = new PrtBoolType();
Types.type_8_958407665 = new PrtNamedTupleType(new object[]{"index", Types.type_6_958407665});
Types.type_9_958407665 = new PrtSeqType(Types.type_2_958407665);
Types.type_10_958407665 = new PrtNamedTupleType(new object[]{"list", Types.type_9_958407665});
Types.type_11_958407665 = new PrtMapType(Types.type_1_958407665, Types.type_9_958407665);
Types.type_12_958407665 = new PrtTupleType(new PrtType[]{Types.type_6_958407665, Types.type_2_958407665});
Types.type_13_958407665 = new PrtNullType();
}
}
public static PrtImplMachine CreateMachine_POrbMachine(StateImpl application, PrtValue payload)
{
var machine = new POrbMachine(application, PrtImplMachine.DefaultMaxBufferSize, false);
(application).TraceLine("<CreateLog> Created Machine POrbMachine-{0}", (machine).instanceNumber);
((machine).self).permissions = null;
(machine).sends = null;
(machine).currentPayload = payload;
return machine;
}
public class POrbMachine : PrtImplMachine
{
public override PrtState StartState
{
get
{
return POrbMachine_Init;
}
}
public PrtValue var_topicSubscribers
{
get
{
return fields[0];
}
set
{
fields[0] = value;
}
}
public override PrtImplMachine MakeSkeleton()
{
return new POrbMachine();
}
public override int NextInstanceNumber(StateImpl app)
{
return app.NextMachineInstanceNumber(this.GetType());
}
public override string Name
{
get
{
return "POrbMachine";
}
}
public POrbMachine(): base ()
{
}
public POrbMachine(StateImpl app, int maxB, bool assume): base (app, maxB, assume)
{
(fields).Add(PrtValue.PrtMkDefaultValue(Types.type_11_958407665));
}
public class ignore_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return false;
}
}
internal class ignore_StackFrame : PrtFunStackFrame
{
public ignore_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public ignore_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
ignore_StackFrame currFun = (ignore_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new ignore_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "ignore";
}
}
public static ignore_Class ignore = new ignore_Class();
public class InitializeListener_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return false;
}
}
internal class InitializeListener_StackFrame : PrtFunStackFrame
{
public InitializeListener_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public InitializeListener_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
public PrtValue var_payload
{
get
{
return locals[0];
}
set
{
locals[0] = value;
}
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
InitializeListener_StackFrame currFun = (InitializeListener_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new InitializeListener_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "InitializeListener";
}
}
public static InitializeListener_Class InitializeListener = new InitializeListener_Class();
public class IsSubscribed_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return false;
}
}
internal class IsSubscribed_StackFrame : PrtFunStackFrame
{
public IsSubscribed_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public IsSubscribed_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
public PrtValue var_sub
{
get
{
return locals[0];
}
set
{
locals[0] = value;
}
}
public PrtValue var_machines
{
get
{
return locals[1];
}
set
{
locals[1] = value;
}
}
public PrtValue var_index
{
get
{
return locals[2];
}
set
{
locals[2] = value;
}
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
IsSubscribed_StackFrame currFun = (IsSubscribed_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
(currFun).var_index = (new PrtIntValue(0)).Clone();
IsSubscribed_loop_start_0:
;
if (!((PrtBoolValue)(new PrtBoolValue(((PrtIntValue)((currFun).var_index)).nt < ((PrtIntValue)(new PrtIntValue(((currFun).var_machines).Size()))).nt))).bl)
goto IsSubscribed_loop_end_0;
if (!((PrtBoolValue)(new PrtBoolValue(((((PrtSeqValue)((currFun).var_machines)).Lookup((currFun).var_index)).Clone()).Equals((currFun).var_sub)))).bl)
goto IsSubscribed_if_0_else;
(parent).PrtFunContReturnVal(new PrtBoolValue(true), (currFun).locals);
return;
goto IsSubscribed_if_0_end;
IsSubscribed_if_0_else:
;
IsSubscribed_if_0_end:
;
(currFun).var_index = (new PrtIntValue(((PrtIntValue)((currFun).var_index)).nt + ((PrtIntValue)(new PrtIntValue(1))).nt)).Clone();
goto IsSubscribed_loop_start_0;
IsSubscribed_loop_end_0:
;
(parent).PrtFunContReturnVal(new PrtBoolValue(false), (currFun).locals);
return;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
(locals).Add(PrtValue.PrtMkDefaultValue(Types.type_6_958407665));
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new IsSubscribed_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "IsSubscribed";
}
}
public static IsSubscribed_Class IsSubscribed = new IsSubscribed_Class();
public class Broadcast_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return false;
}
}
internal class Broadcast_StackFrame : PrtFunStackFrame
{
public Broadcast_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public Broadcast_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
public PrtValue var_machines
{
get
{
return locals[0];
}
set
{
locals[0] = value;
}
}
public PrtValue var_ev
{
get
{
return locals[1];
}
set
{
locals[1] = value;
}
}
public PrtValue var_payload
{
get
{
return locals[2];
}
set
{
locals[2] = value;
}
}
public PrtValue var_index
{
get
{
return locals[3];
}
set
{
locals[3] = value;
}
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
Broadcast_StackFrame currFun = (Broadcast_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
switch ((currFun).returnToLocation)
{
case 1:
goto Broadcast_1;
}
(currFun).var_index = (new PrtIntValue(0)).Clone();
Broadcast_loop_start_0:
;
if (!((PrtBoolValue)(new PrtBoolValue(((PrtIntValue)((currFun).var_index)).nt < ((PrtIntValue)(new PrtIntValue(((currFun).var_machines).Size()))).nt))).bl)
goto Broadcast_loop_end_0;
(((PrtMachineValue)((((PrtSeqValue)((currFun).var_machines)).Lookup((currFun).var_index)).Clone())).mach).PrtEnqueueEvent((PrtEventValue)((currFun).var_ev), (currFun).var_payload, parent, (PrtMachineValue)((((PrtSeqValue)((currFun).var_machines)).Lookup((currFun).var_index)).Clone()));
(parent).PrtFunContSend(this, (currFun).locals, 1);
return;
Broadcast_1:
;
(currFun).var_index = (new PrtIntValue(((PrtIntValue)((currFun).var_index)).nt + ((PrtIntValue)(new PrtIntValue(1))).nt)).Clone();
goto Broadcast_loop_start_0;
Broadcast_loop_end_0:
;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
(locals).Add(PrtValue.PrtMkDefaultValue(Types.type_6_958407665));
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new Broadcast_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "Broadcast";
}
}
public static Broadcast_Class Broadcast = new Broadcast_Class();
public class AnonFun0_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return true;
}
}
internal class AnonFun0_StackFrame : PrtFunStackFrame
{
public AnonFun0_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public AnonFun0_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
public PrtValue var__payload_skip
{
get
{
return locals[0];
}
set
{
locals[0] = value;
}
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
AnonFun0_StackFrame currFun = (AnonFun0_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new AnonFun0_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "AnonFun0";
}
}
public static AnonFun0_Class AnonFun0 = new AnonFun0_Class();
public class AnonFun1_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return true;
}
}
internal class AnonFun1_StackFrame : PrtFunStackFrame
{
public AnonFun1_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public AnonFun1_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
public PrtValue var__payload_skip
{
get
{
return locals[0];
}
set
{
locals[0] = value;
}
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
AnonFun1_StackFrame currFun = (AnonFun1_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new AnonFun1_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "AnonFun1";
}
}
public static AnonFun1_Class AnonFun1 = new AnonFun1_Class();
public class AnonFun2_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return true;
}
}
internal class AnonFun2_StackFrame : PrtFunStackFrame
{
public AnonFun2_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public AnonFun2_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
public PrtValue var__payload_0
{
get
{
return locals[0];
}
set
{
locals[0] = value;
}
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
AnonFun2_StackFrame currFun = (AnonFun2_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
switch ((currFun).returnToLocation)
{
case 1:
goto AnonFun2_1;
}
(parent).PrtPushFunStackFrame(InitializeListener, (InitializeListener).CreateLocals(parent.self));
AnonFun2_1:
;
(InitializeListener).Execute(application, parent);
if (((parent).continuation).reason == PrtContinuationReason.Return)
{
}
else
{
(parent).PrtPushFunStackFrame((currFun).fun, (currFun).locals, 1);
return;
}
(application).TraceLine("<GotoLog> Machine {0}-{1} goes to {2}", (parent).Name, (parent).instanceNumber, (POrbMachine_ReadMessagesAndPublish).name);
(parent).currentTrigger = Events.@null;
(parent).currentPayload = Events.@null;
(parent).destOfGoto = POrbMachine_ReadMessagesAndPublish;
(parent).PrtFunContGoto();
return;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new AnonFun2_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "AnonFun2";
}
}
public static AnonFun2_Class AnonFun2 = new AnonFun2_Class();
public class AnonFun3_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return true;
}
}
internal class AnonFun3_StackFrame : PrtFunStackFrame
{
public AnonFun3_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public AnonFun3_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
public PrtValue var__payload_skip
{
get
{
return locals[0];
}
set
{
locals[0] = value;
}
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
AnonFun3_StackFrame currFun = (AnonFun3_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new AnonFun3_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "AnonFun3";
}
}
public static AnonFun3_Class AnonFun3 = new AnonFun3_Class();
public class AnonFun4_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return true;
}
}
internal class AnonFun4_StackFrame : PrtFunStackFrame
{
public AnonFun4_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public AnonFun4_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
public PrtValue var_payload
{
get
{
return locals[0];
}
set
{
locals[0] = value;
}
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
AnonFun4_StackFrame currFun = (AnonFun4_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
switch ((currFun).returnToLocation)
{
case 1:
goto AnonFun4_1;
}
if (!((PrtBoolValue)(new PrtBoolValue(((PrtMapValue)((parent).var_topicSubscribers)).Contains((((PrtTupleValue)((currFun).var_payload)).fieldValues[0]).Clone())))).bl)
goto AnonFun4_if_0_else;
(parent).PrtPushFunStackFrame(Broadcast, (Broadcast).CreateLocals((((PrtMapValue)((parent).var_topicSubscribers)).Lookup((((PrtTupleValue)((currFun).var_payload)).fieldValues[0]).Clone())).Clone(), (((PrtTupleValue)((currFun).var_payload)).fieldValues[1]).Clone(), (((PrtTupleValue)((currFun).var_payload)).fieldValues[2]).Clone()));
AnonFun4_1:
;
(Broadcast).Execute(application, parent);
if (((parent).continuation).reason == PrtContinuationReason.Return)
{
}
else
{
(parent).PrtPushFunStackFrame((currFun).fun, (currFun).locals, 1);
return;
}
goto AnonFun4_if_0_end;
AnonFun4_if_0_else:
;
AnonFun4_if_0_end:
;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new AnonFun4_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "AnonFun4";
}
}
public static AnonFun4_Class AnonFun4 = new AnonFun4_Class();
public class AnonFun5_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return true;
}
}
internal class AnonFun5_StackFrame : PrtFunStackFrame
{
public AnonFun5_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public AnonFun5_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
public PrtValue var_payload
{
get
{
return locals[0];
}
set
{
locals[0] = value;
}
}
public PrtValue var_list
{
get
{
return locals[1];
}
set
{
locals[1] = value;
}
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
AnonFun5_StackFrame currFun = (AnonFun5_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
if (!((PrtBoolValue)(new PrtBoolValue(((PrtMapValue)((parent).var_topicSubscribers)).Contains((((PrtTupleValue)((currFun).var_payload)).fieldValues[0]).Clone())))).bl)
goto AnonFun5_if_1_else;
(currFun).var_list = ((((PrtMapValue)((parent).var_topicSubscribers)).Lookup((((PrtTupleValue)((currFun).var_payload)).fieldValues[0]).Clone())).Clone()).Clone();
if (!((PrtBoolValue)((IsSubscribed).ExecuteToCompletion(application, parent, (((PrtTupleValue)((currFun).var_payload)).fieldValues[1]).Clone(), (currFun).var_list))).bl)
goto AnonFun5_if_0_else;
(application).Trace("<PrintLog> Subscriber is already subscribed to event ");
((((PrtTupleValue)((currFun).var_payload)).fieldValues[0]).Clone()).ToString();
(application).Trace("<PrintLog> \\n");
goto AnonFun5_if_0_end;
AnonFun5_if_0_else:
;
AnonFun5_if_0_end:
;
((PrtSeqValue)(((PrtMapValue)((parent).var_topicSubscribers)).Lookup((((PrtTupleValue)((currFun).var_payload)).fieldValues[0]).Clone()))).Insert(((PrtTupleValue)(new PrtTupleValue(new PrtIntValue(0), (((PrtTupleValue)((currFun).var_payload)).fieldValues[1]).Clone()))).fieldValues[0], ((PrtTupleValue)(new PrtTupleValue(new PrtIntValue(0), (((PrtTupleValue)((currFun).var_payload)).fieldValues[1]).Clone()))).fieldValues[1]);
goto AnonFun5_if_1_end;
AnonFun5_if_1_else:
;
((PrtMapValue)((parent).var_topicSubscribers)).Update((((PrtTupleValue)((currFun).var_payload)).fieldValues[0]).Clone(), (PrtValue.PrtMkDefaultValue(Types.type_9_958407665)).Clone());
((PrtSeqValue)(((PrtMapValue)((parent).var_topicSubscribers)).Lookup((((PrtTupleValue)((currFun).var_payload)).fieldValues[0]).Clone()))).Insert(((PrtTupleValue)(new PrtTupleValue(new PrtIntValue(0), (((PrtTupleValue)((currFun).var_payload)).fieldValues[1]).Clone()))).fieldValues[0], ((PrtTupleValue)(new PrtTupleValue(new PrtIntValue(0), (((PrtTupleValue)((currFun).var_payload)).fieldValues[1]).Clone()))).fieldValues[1]);
AnonFun5_if_1_end:
;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
(locals).Add(PrtValue.PrtMkDefaultValue(Types.type_9_958407665));
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new AnonFun5_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "AnonFun5";
}
}
public static AnonFun5_Class AnonFun5 = new AnonFun5_Class();
public class AnonFun6_Class : PrtFun
{
public override bool IsAnonFun
{
get
{
return true;
}
}
internal class AnonFun6_StackFrame : PrtFunStackFrame
{
public AnonFun6_StackFrame(PrtFun fun, List<PrtValue> _locals): base (fun, _locals)
{
}
public AnonFun6_StackFrame(PrtFun fun, List<PrtValue> _locals, int retLocation): base (fun, _locals, retLocation)
{
}
public override PrtFunStackFrame Clone()
{
return this.Clone();
}
public PrtValue var__payload_skip
{
get
{
return locals[0];
}
set
{
locals[0] = value;
}
}
}
public override void Execute(StateImpl application, PrtMachine _parent)
{
POrbMachine parent = (POrbMachine)(_parent);
AnonFun6_StackFrame currFun = (AnonFun6_StackFrame)(parent.PrtPopFunStackFrame());
PrtValue swap;
parent.PrtFunContReturn((currFun).locals);
}
public override List<PrtValue> CreateLocals(params PrtValue[] args)
{
var locals = new List<PrtValue>();
foreach (var item in args)
{
locals.Add(item.Clone());
}
return locals;
}
public override PrtFunStackFrame CreateFunStackFrame(List<PrtValue> locals, int retLoc)
{
return new AnonFun6_StackFrame(this, locals, retLoc);
}
public override string ToString()
{
return "AnonFun6";
}
}
public static AnonFun6_Class AnonFun6 = new AnonFun6_Class();
public class POrbMachine_ReadMessagesAndPublish_Class : PrtState
{
public POrbMachine_ReadMessagesAndPublish_Class(string name, PrtFun entryFun, PrtFun exitFun, bool hasNullTransition, StateTemperature temperature): base (name, entryFun, exitFun, hasNullTransition, temperature)
{
}
}
public static POrbMachine_ReadMessagesAndPublish_Class POrbMachine_ReadMessagesAndPublish;
public class POrbMachine_Init_Class : PrtState
{
public POrbMachine_Init_Class(string name, PrtFun entryFun, PrtFun exitFun, bool hasNullTransition, StateTemperature temperature): base (name, entryFun, exitFun, hasNullTransition, temperature)
{
}
}
public static POrbMachine_Init_Class POrbMachine_Init;
static POrbMachine()
{
POrbMachine_ReadMessagesAndPublish = new POrbMachine_ReadMessagesAndPublish_Class("POrbMachine_ReadMessagesAndPublish", AnonFun0, AnonFun1, false, StateTemperature.Warm);
POrbMachine_Init = new POrbMachine_Init_Class("POrbMachine_Init", AnonFun2, AnonFun3, false, StateTemperature.Warm);
POrbMachine_ReadMessagesAndPublish.dos.Add(Events.event_POrbSubscribe, AnonFun5);
POrbMachine_ReadMessagesAndPublish.dos.Add(Events.event_POrbPublish, AnonFun4);
}
}
}
}
| |
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Linq;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaWriter
{
private readonly JsonWriter _writer;
private readonly JsonSchemaResolver _resolver;
public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
_writer = writer;
_resolver = resolver;
}
private void ReferenceOrWriteSchema(JsonSchema schema)
{
if (schema.Id != null && _resolver.GetSchema(schema.Id) != null)
{
_writer.WriteStartObject();
_writer.WritePropertyName(JsonSchemaConstants.ReferencePropertyName);
_writer.WriteValue(schema.Id);
_writer.WriteEndObject();
}
else
{
WriteSchema(schema);
}
}
public void WriteSchema(JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(schema, "schema");
if (!_resolver.LoadedSchemas.Contains(schema))
_resolver.LoadedSchemas.Add(schema);
_writer.WriteStartObject();
WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.RequiredPropertyName, schema.Required);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient);
if (schema.Type != null)
WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value);
if (!schema.AllowAdditionalProperties)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
_writer.WriteValue(schema.AllowAdditionalProperties);
}
else
{
if (schema.AdditionalProperties != null)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
ReferenceOrWriteSchema(schema.AdditionalProperties);
}
}
if (!schema.AllowAdditionalItems)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName);
_writer.WriteValue(schema.AllowAdditionalItems);
}
else
{
if (schema.AdditionalItems != null)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName);
ReferenceOrWriteSchema(schema.AdditionalItems);
}
}
WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PropertiesPropertyName, schema.Properties);
WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PatternPropertiesPropertyName, schema.PatternProperties);
WriteItems(schema);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMinimumPropertyName, schema.ExclusiveMinimum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMaximumPropertyName, schema.ExclusiveMaximum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumLengthPropertyName, schema.MinimumLength);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumLengthPropertyName, schema.MaximumLength);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumItemsPropertyName, schema.MinimumItems);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumItemsPropertyName, schema.MaximumItems);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DivisibleByPropertyName, schema.DivisibleBy);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern);
if (schema.Enum != null)
{
_writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName);
_writer.WriteStartArray();
foreach (JToken token in schema.Enum)
{
token.WriteTo(_writer);
}
_writer.WriteEndArray();
}
if (schema.Default != null)
{
_writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName);
schema.Default.WriteTo(_writer);
}
if (schema.Disallow != null)
WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.Value);
if (schema.Extends != null && schema.Extends.Count > 0)
{
_writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName);
if (schema.Extends.Count == 1)
{
ReferenceOrWriteSchema(schema.Extends[0]);
}
else
{
_writer.WriteStartArray();
foreach (JsonSchema jsonSchema in schema.Extends)
{
ReferenceOrWriteSchema(jsonSchema);
}
_writer.WriteEndArray();
}
}
_writer.WriteEndObject();
}
private void WriteSchemaDictionaryIfNotNull(JsonWriter writer, string propertyName, IDictionary<string, JsonSchema> properties)
{
if (properties != null)
{
writer.WritePropertyName(propertyName);
writer.WriteStartObject();
foreach (KeyValuePair<string, JsonSchema> property in properties)
{
writer.WritePropertyName(property.Key);
ReferenceOrWriteSchema(property.Value);
}
writer.WriteEndObject();
}
}
private void WriteItems(JsonSchema schema)
{
if (schema.Items == null && !schema.PositionalItemsValidation)
return;
_writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName);
if (!schema.PositionalItemsValidation)
{
if (schema.Items != null && schema.Items.Count > 0)
{
ReferenceOrWriteSchema(schema.Items[0]);
}
else
{
_writer.WriteStartObject();
_writer.WriteEndObject();
}
return;
}
_writer.WriteStartArray();
if (schema.Items != null)
{
foreach (JsonSchema itemSchema in schema.Items)
{
ReferenceOrWriteSchema(itemSchema);
}
}
_writer.WriteEndArray();
}
private void WriteType(string propertyName, JsonWriter writer, JsonSchemaType type)
{
IList<JsonSchemaType> types;
if (System.Enum.IsDefined(typeof(JsonSchemaType), type))
types = new List<JsonSchemaType> { type };
else
types = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).ToList();
if (types.Count == 0)
return;
writer.WritePropertyName(propertyName);
if (types.Count == 1)
{
writer.WriteValue(JsonSchemaBuilder.MapType(types[0]));
return;
}
writer.WriteStartArray();
foreach (JsonSchemaType jsonSchemaType in types)
{
writer.WriteValue(JsonSchemaBuilder.MapType(jsonSchemaType));
}
writer.WriteEndArray();
}
private void WritePropertyIfNotNull(JsonWriter writer, string propertyName, object value)
{
if (value != null)
{
writer.WritePropertyName(propertyName);
writer.WriteValue(value);
}
}
}
}
#endif
| |
// <copyright file="Group.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BeanIO.Internal.Config;
using BeanIO.Internal.Util;
namespace BeanIO.Internal.Parser
{
/// <summary>
/// A Group holds child nodes including records and other groups
/// </summary>
/// <remarks>
/// This class is the dynamic counterpart to the <see cref="GroupConfig"/> and
/// holds the current state of a group node during stream processing.
/// </remarks>
internal class Group : ParserComponent, ISelector
{
/// <summary>
/// map key used to store the state of the 'lastMatchedChild' attribute
/// </summary>
private const string LAST_MATCHED_KEY = "lastMatched";
private readonly ParserLocal<int> _count = new ParserLocal<int>(0);
private readonly ParserLocal<ISelector> _lastMatched = new ParserLocal<ISelector>();
/// <summary>
/// Initializes a new instance of the <see cref="Group"/> class.
/// </summary>
public Group()
: base(5)
{
Order = 1;
MaxOccurs = int.MaxValue;
}
/// <summary>
/// Gets the size of a single occurrence of this element, which is used to offset
/// field positions for repeating segments and fields.
/// </summary>
/// <remarks>
/// The concept of size is dependent on the stream format. The size of an element in a fixed
/// length stream format is determined by the length of the element in characters, while other
/// stream formats calculate size based on the number of fields. Some stream formats,
/// such as XML, may ignore size settings.
/// </remarks>
public override int? Size => null;
/// <summary>
/// Gets or sets a value indicating whether this parser or any descendant of this parser is used to identify
/// a record during unmarshalling.
/// </summary>
public override bool IsIdentifier
{
get
{
return false;
}
set
{
if (value)
throw new NotSupportedException();
}
}
/// <summary>
/// Gets a value indicating whether this node must exist during unmarshalling.
/// </summary>
public override bool IsOptional => MinOccurs == 0;
/// <summary>
/// Gets or sets the minimum number of occurrences of this component (within the context of its parent).
/// </summary>
public int MinOccurs { get; set; }
/// <summary>
/// Gets or sets the maximum number of occurrences of this component (within the context of its parent).
/// </summary>
public int? MaxOccurs { get; set; }
/// <summary>
/// Gets or sets the order of this component (within the context of its parent).
/// </summary>
public int Order { get; set; }
/// <summary>
/// Gets or sets the <see cref="IProperty"/> mapped to this component, or null if there is no property mapping.
/// </summary>
public IProperty Property { get; set; }
/// <summary>
/// Gets a value indicating whether this component is a record group.
/// </summary>
public bool IsRecordGroup => true;
/// <summary>
/// Returns whether this parser and its children match a record being unmarshalled.
/// </summary>
/// <param name="context">The <see cref="UnmarshallingContext"/></param>
/// <returns>true if matched, false otherwise</returns>
public override bool Matches(UnmarshallingContext context)
{
return false;
}
/// <summary>
/// Unmarshals a record
/// </summary>
/// <param name="context">The <see cref="UnmarshallingContext"/></param>
/// <returns>true if this component was present in the unmarshalled record, or false otherwise</returns>
public override bool Unmarshal(UnmarshallingContext context)
{
// this method is only invoked when this group is configured to
// unmarshal a bean object that spans multiple records
try
{
var child = _lastMatched.Get(context);
child.Unmarshal(context);
// read the next record
while (true)
{
context.NextRecord();
if (context.IsEof)
{
var unsatisfied = Close(context);
if (unsatisfied != null)
throw context.NewUnsatisfiedRecordException(unsatisfied.Name);
break;
}
child = MatchCurrent(context);
if (child == null)
{
Reset(context);
break;
}
try
{
child.Unmarshal(context);
}
catch (AbortRecordUnmarshalligException)
{
// Ignore aborts
}
}
Property?.CreateValue(context);
return true;
}
catch (UnsatisfiedNodeException ex)
{
throw context.NewUnsatisfiedRecordException(ex.Node.Name);
}
}
/// <summary>
/// Marshals a record
/// </summary>
/// <param name="context">The <see cref="MarshallingContext"/></param>
/// <returns>whether a value was marshalled</returns>
public override bool Marshal(MarshallingContext context)
{
// this method is only invoked when this group is configured to
// marshal a bean object that spans multiple records
return Children.Cast<IParser>().Aggregate(false, (current, child) => child.Marshal(context) || current);
}
/// <summary>
/// Returns whether this parser or any of its descendant have content for marshalling.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
/// <returns>true if there is content for marshalling, false otherwise</returns>
public override bool HasContent(ParsingContext context)
{
if (Property != null)
return !ReferenceEquals(Property.GetValue(context), Value.Missing);
return Children.Cast<IParser>().Any(child => child.HasContent(context));
}
/// <summary>
/// Clears the current property value.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
public override void ClearValue(ParsingContext context)
{
Property?.ClearValue(context);
}
/// <summary>
/// Sets the property value for marshaling.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
/// <param name="value">the property value</param>
public override void SetValue(ParsingContext context, object value)
{
Property.SetValue(context, value);
}
/// <summary>
/// Returns the unmarshalled property value.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
/// <returns>the property value</returns>
public override object GetValue(ParsingContext context)
{
return Property.GetValue(context);
}
/// <summary>
/// Returns the number of times this component was matched within the current
/// iteration of its parent component.
/// </summary>
/// <param name="context">the <see cref="ParsingContext"/></param>
/// <returns>the match count</returns>
public int GetCount(ParsingContext context)
{
return _count.Get(context);
}
/// <summary>
/// Sets the number of times this component was matched within the current
/// iteration of its parent component.
/// </summary>
/// <param name="context">the <see cref="ParsingContext"/></param>
/// <param name="value">the new count</param>
public void SetCount(ParsingContext context, int value)
{
_count.Set(context, value);
}
/// <summary>
/// Returns a value indicating whether this component has reached its maximum occurrences
/// </summary>
/// <param name="context">the <see cref="ParsingContext"/></param>
/// <returns>true if maximum occurrences has been reached</returns>
public bool IsMaxOccursReached(ParsingContext context)
{
return _lastMatched.Get(context) == null && MaxOccurs != null && GetCount(context) >= MaxOccurs;
}
/// <summary>
/// Finds a parser for marshalling a bean object
/// </summary>
/// <remarks>
/// If matched by this Selector, the method
/// should set the bean object on the property tree and return itself.
/// </remarks>
/// <param name="context">the <see cref="MarshallingContext"/></param>
/// <returns>the matched <see cref="ISelector"/> for marshalling the bean object</returns>
public ISelector MatchNext(MarshallingContext context)
{
try
{
if (Property == null)
return InternalMatchNext(context);
var componentName = context.ComponentName;
if (componentName != null && Name != componentName)
return null;
var value = context.Bean;
if (Property.Defines(value))
{
Property.SetValue(context, value);
return this;
}
return null;
}
catch (UnsatisfiedNodeException ex)
{
throw new BeanWriterException($"Bean identification failed: expected record type '{ex.Node.Name}'", ex);
}
}
/// <summary>
/// Finds a parser for unmarshalling a record based on the current state of the stream.
/// </summary>
/// <param name="context">the <see cref="UnmarshallingContext"/></param>
/// <returns>the matched <see cref="ISelector"/> for unmarshalling the record</returns>
public ISelector MatchNext(UnmarshallingContext context)
{
try
{
return InternalMatchNext(context);
}
catch (UnsatisfiedNodeException ex)
{
throw context.NewUnsatisfiedRecordException(ex.Node.Name);
}
}
/// <summary>
/// Finds a parser that matches the input record
/// </summary>
/// <remarks>
/// This method is invoked when <see cref="ISelector.MatchNext(BeanIO.Internal.Parser.UnmarshallingContext)"/> returns
/// null, in order to differentiate between unexpected and unidentified record types.
/// </remarks>
/// <param name="context">the <see cref="UnmarshallingContext"/></param>
/// <returns>the matched <see cref="ISelector"/></returns>
public ISelector MatchAny(UnmarshallingContext context)
{
return Children.Cast<ISelector>().Select(x => x.MatchAny(context)).FirstOrDefault(x => x != null);
}
/// <summary>
/// Skips a record or group of records.
/// </summary>
/// <param name="context">the <see cref="UnmarshallingContext"/></param>
public void Skip(UnmarshallingContext context)
{
// this method is only invoked when this group is configured to
// unmarshal a bean object that spans multiple records
try
{
var child = _lastMatched.Get(context);
child.Skip(context);
// read the next record
while (true)
{
context.NextRecord();
if (context.IsEof)
{
var unsatisfied = Close(context);
if (unsatisfied != null)
throw context.NewUnsatisfiedRecordException(unsatisfied.Name);
break;
}
// find the child unmarshaller for the record...
child = MatchCurrent(context);
if (child == null)
{
Reset(context);
break;
}
child.Skip(context);
}
}
catch (UnsatisfiedNodeException ex)
{
throw context.NewUnsatisfiedRecordException(ex.Node.Name);
}
}
/// <summary>
/// Checks for any unsatisfied components before the stream is closed.
/// </summary>
/// <param name="context">the <see cref="ParsingContext"/></param>
/// <returns>the first unsatisfied node</returns>
public ISelector Close(ParsingContext context)
{
var lastMatch = _lastMatched.Get(context);
if (lastMatch == null && MinOccurs == 0)
return null;
var pos = lastMatch?.Order ?? 1;
var unsatisfied = FindUnsatisfiedChild(context, pos);
if (unsatisfied != null)
return unsatisfied;
if (GetCount(context) < MinOccurs)
{
// try to find a specific record before reporting any record from this group
if (pos > 1)
{
Reset(context);
unsatisfied = FindUnsatisfiedChild(context, 1);
if (unsatisfied != null)
return unsatisfied;
}
return this;
}
return null;
}
/// <summary>
/// Resets the component count of this Selector's children.
/// </summary>
/// <param name="context">the <see cref="ParsingContext"/></param>
public void Reset(ParsingContext context)
{
_lastMatched.Set(context, null);
foreach (var node in Children.Cast<ISelector>())
{
node.SetCount(context, 0);
node.Reset(context);
}
}
/// <summary>
/// Updates a <see cref="IDictionary{TKey,TValue}"/> with the current state of the Writer to allow for restoration at a later time.
/// </summary>
/// <param name="context">the <see cref="ParsingContext"/></param>
/// <param name="ns">a <see cref="string"/> to prefix all state keys with</param>
/// <param name="state">the <see cref="IDictionary{TKey,TValue}"/> to update with the latest state</param>
public void UpdateState(ParsingContext context, string ns, IDictionary<string, object> state)
{
state[GetKey(ns, COUNT_KEY)] = _count.Get(context);
var lastMatchedChildName = string.Empty;
var lastMatch = _lastMatched.Get(context);
if (lastMatch != null)
lastMatchedChildName = lastMatch.Name;
state[GetKey(ns, LAST_MATCHED_KEY)] = lastMatchedChildName;
// allow children to update their state
foreach (var node in this.Cast<ISelector>())
node.UpdateState(context, ns, state);
}
/// <summary>
/// Restores a <see cref="IDictionary{TKey,TValue}"/> of previously stored state information
/// </summary>
/// <param name="context">the <see cref="ParsingContext"/></param>
/// <param name="ns">a <see cref="string"/> to prefix all state keys with</param>
/// <param name="state">the <see cref="IDictionary{TKey,TValue}"/> containing the state to restore</param>
public void RestoreState(ParsingContext context, string ns, IReadOnlyDictionary<string, object> state)
{
var key = GetKey(ns, COUNT_KEY);
var n = (int?)state.Get(key);
if (n == null)
throw new InvalidOperationException($"Missing state information for key '{key}'");
_count.Set(context, n.Value);
// determine the last matched child
key = GetKey(ns, LAST_MATCHED_KEY);
var lastMatchedChildName = (string)state.Get(key);
if (lastMatchedChildName == null)
throw new InvalidOperationException($"Missing state information for key '{key}'");
if (lastMatchedChildName.Length == 0)
{
_lastMatched.Set(context, null);
lastMatchedChildName = null;
}
foreach (var child in Children.Cast<ISelector>())
{
if (lastMatchedChildName != null && lastMatchedChildName == child.Name)
_lastMatched.Set(context, child);
child.RestoreState(context, ns, state);
}
}
/// <summary>
/// Called by a stream to register variables stored in the parsing context.
/// </summary>
/// <remarks>
/// This method should be overridden by subclasses that need to register
/// one or more parser context variables.
/// </remarks>
/// <param name="locals">set of local variables</param>
public override void RegisterLocals(ISet<IParserLocal> locals)
{
((Component)Property)?.RegisterLocals(locals);
if (locals.Add(_lastMatched))
{
locals.Add(_count);
base.RegisterLocals(locals);
}
}
/// <summary>
/// Returns whether a node is a supported child of this node.
/// </summary>
/// <remarks>
/// Called by <see cref="TreeNode{T}.Add"/>.
/// </remarks>
/// <param name="child">the node to test</param>
/// <returns>true if the child is allowed</returns>
public override bool IsSupportedChild(Component child)
{
return child is ISelector;
}
/// <summary>
/// Called by <see cref="TreeNode{T}.ToString"/> to append node parameters to the output
/// </summary>
/// <param name="s">The output to append</param>
protected override void ToParamString(StringBuilder s)
{
base.ToParamString(s);
s
.AppendFormat(", order={0}", Order)
.AppendFormat(", occurs={0}", DebugUtil.FormatRange(MinOccurs, MaxOccurs));
if (Property != null)
s.AppendFormat(", property={0}", Property);
}
private ISelector FindUnsatisfiedChild(ParsingContext context, int from)
{
// find any unsatisfied child
foreach (var node in Children.Cast<ISelector>())
{
if (node.Order < from)
continue;
var unsatisfied = node.Close(context);
if (unsatisfied != null)
return unsatisfied;
}
return null;
}
private ISelector InternalMatchNext(ParsingContext context)
{
/*
* A matching record is searched for in 3 stages:
* 1. First, we give the last matching node an opportunity to match the next
* record if it hasn't reached it's max occurs.
* 2. Second, we search for another matching node at the same position/order
* or increment the position until we find a matching node or a min occurs
* is not met.
* 3. Finally, if all nodes in this group have been satisfied and this group
* hasn't reached its max occurs, we search nodes from the beginning again
* and increment the group count if a node matches.
*
* If no match is found, there SHOULD be no changes to the state of this node.
*/
var match = MatchCurrent(context);
if (match == null && (MaxOccurs == null || MaxOccurs > 1))
match = MatchAgain(context);
if (match != null)
return Property != null ? this : match;
return null;
}
private ISelector MatchAgain(ParsingContext context)
{
ISelector unsatisfied = null;
if (_lastMatched.Get(context) != null)
{
// no need to check if the max occurs was already reached
if (MaxOccurs != null && GetCount(context) >= MaxOccurs)
return null;
// if there was no unsatisfied node and we haven't reached the max occurs,
// try to find a match from the beginning again so that the parent can
// skip this node
var position = 1;
foreach (var node in Children.Cast<ISelector>())
{
if (node.Order > position)
{
if (unsatisfied != null)
return null;
position = node.Order;
}
if (node.MinOccurs > 0)
{
// when marshalling, allow records to be skipped that aren't bound to a property
if (context.Mode != ParsingMode.Marshalling || node.Property != null)
unsatisfied = node;
}
ISelector match = MatchNext(context, node);
if (match != null)
{
// this is different than reset() because we reset every node
// except the one that matched...
foreach (var sel in Children.Cast<ISelector>())
{
if (ReferenceEquals(sel, node))
continue;
sel.SetCount(context, 0);
sel.Reset(context);
}
_count.Set(context, _count.Get(context) + 1);
node.SetCount(context, 1);
_lastMatched.Set(context, node);
return match;
}
}
}
return null;
}
private ISelector MatchCurrent(ParsingContext context)
{
ISelector match;
ISelector unsatisfied = null;
ISelector lastMatch = _lastMatched.Get(context);
// check the last matching node - do not check records where the max occurs
// has already been reached
if (lastMatch != null && !lastMatch.IsMaxOccursReached(context))
{
match = MatchNext(context, lastMatch);
if (match != null)
return match;
}
// set the current position to the order of the last matched node (or default to 1)
var position = lastMatch?.Order ?? 1;
// iterate over each child
foreach (var node in Children.Cast<ISelector>())
{
// skip the last node which was already checked
if (node == lastMatch)
continue;
// skip nodes where their order is less than the current position
if (node.Order < position)
continue;
// skip nodes where max occurs has already been met
if (node.IsMaxOccursReached(context))
continue;
// if no node matched at the current position, increment the position and test the next node
if (node.Order > position)
{
// before increasing the position, we must validate that all
// min occurs have been met at the previous position
if (unsatisfied != null)
{
if (lastMatch != null)
throw new UnsatisfiedNodeException(unsatisfied);
return null;
}
position = node.Order;
}
// if the min occurs has not been met for the next node, set the unsatisfied flag so we
// can throw an exception before incrementing the position again
if (node.GetCount(context) < node.MinOccurs)
{
// when marshalling, allow records to be skipped that aren't bound to a property
if (context.Mode != ParsingMode.Marshalling || node.Property != null)
{
unsatisfied = node;
}
}
// search the child node for a match
match = MatchNext(context, node);
if (match != null)
{
// the group count is incremented only when first invoked
if (lastMatch == null)
{
_count.Set(context, _count.Get(context) + 1);
}
else
{
// reset the last group when a new record or group is found
// at the same level (this has no effect for a record)
lastMatch.Reset(context);
}
_lastMatched.Set(context, node);
return match;
}
}
// if last was not null, we continued checking for matches at the current position, now
// we'll check for matches at the beginning (assuming there is no unsatisfied node)
if (lastMatch != null && unsatisfied != null)
throw new UnsatisfiedNodeException(unsatisfied);
return null;
}
private ISelector MatchNext(ParsingContext context, ISelector child)
{
switch (context.Mode)
{
case ParsingMode.Marshalling:
return child.MatchNext((MarshallingContext)context);
case ParsingMode.Unmarshalling:
return child.MatchNext((UnmarshallingContext)context);
default:
throw new InvalidOperationException($"Invalid mode: {context.Mode}");
}
}
private string GetKey(string ns, string name)
{
return $"{ns}.{Name}.{name}";
}
private class UnsatisfiedNodeException : BeanIOException
{
public UnsatisfiedNodeException(ISelector node)
{
Node = node;
}
public ISelector Node { get; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal struct AidContainer
{
internal static readonly AidContainer NullAidContainer = default(AidContainer);
private object _value;
public AidContainer(FileRecord file)
{
_value = file;
}
}
internal sealed class BSYMMGR
{
private HashSet<KAID> bsetGlobalAssemblies; // Assemblies in the global alias.
// Special nullable members.
public PropertySymbol propNubValue;
public MethodSymbol methNubCtor;
private readonly SymFactory _symFactory;
private readonly MiscSymFactory _miscSymFactory;
private readonly NamespaceSymbol _rootNS; // The "root" (unnamed) namespace.
// Map from aids to INFILESYMs and EXTERNALIASSYMs
private List<AidContainer> ssetAssembly;
// Map from aids to MODULESYMs and OUTFILESYMs
private NameManager m_nameTable;
private SYMTBL tableGlobal;
// The hash table for type arrays.
private Dictionary<TypeArrayKey, TypeArray> tableTypeArrays;
private const int LOG2_SYMTBL_INITIAL_BUCKET_CNT = 13; // Initial local size: 8192 buckets.
private static readonly TypeArray s_taEmpty = new TypeArray(Array.Empty<CType>());
public BSYMMGR(NameManager nameMgr, TypeManager typeManager)
{
this.m_nameTable = nameMgr;
this.tableGlobal = new SYMTBL();
_symFactory = new SymFactory(this.tableGlobal);
_miscSymFactory = new MiscSymFactory(this.tableGlobal);
this.ssetAssembly = new List<AidContainer>();
InputFile infileUnres = new InputFile {isSource = false};
infileUnres.SetAssemblyID(KAID.kaidUnresolved);
ssetAssembly.Add(new AidContainer(infileUnres));
this.bsetGlobalAssemblies = new HashSet<KAID>();
this.bsetGlobalAssemblies.Add(KAID.kaidThisAssembly);
this.tableTypeArrays = new Dictionary<TypeArrayKey, TypeArray>();
_rootNS = _symFactory.CreateNamespace(m_nameTable.Lookup(""), null);
GetNsAid(_rootNS, KAID.kaidGlobal);
}
public void Init()
{
/*
tableTypeArrays.Init(&this->GetPageHeap(), this->getAlloc());
tableNameToSym.Init(this);
nsToExtensionMethods.Init(this);
// Some root symbols.
Name* emptyName = m_nameTable->AddString(L"");
rootNS = symFactory.CreateNamespace(emptyName, NULL); // Root namespace
nsaGlobal = GetNsAid(rootNS, kaidGlobal);
m_infileUnres.name = emptyName;
m_infileUnres.isSource = false;
m_infileUnres.idLocalAssembly = mdTokenNil;
m_infileUnres.SetAssemblyID(kaidUnresolved, allocGlobal);
size_t isym;
isym = ssetAssembly.Add(&m_infileUnres);
ASSERT(isym == 0);
*/
InitPreLoad();
}
public NameManager GetNameManager()
{
return m_nameTable;
}
public SYMTBL GetSymbolTable()
{
return tableGlobal;
}
public static TypeArray EmptyTypeArray()
{
return s_taEmpty;
}
public AssemblyQualifiedNamespaceSymbol GetRootNsAid(KAID aid)
{
return GetNsAid(_rootNS, aid);
}
public NamespaceSymbol GetRootNS()
{
return _rootNS;
}
public KAID AidAlloc(InputFile sym)
{
ssetAssembly.Add(new AidContainer(sym));
return (KAID)(ssetAssembly.Count - 1 + KAID.kaidUnresolved);
}
public BetterType CompareTypes(TypeArray ta1, TypeArray ta2)
{
if (ta1 == ta2)
{
return BetterType.Same;
}
if (ta1.Count != ta2.Count)
{
// The one with more parameters is more specific.
return ta1.Count > ta2.Count ? BetterType.Left : BetterType.Right;
}
BetterType nTot = BetterType.Neither;
for (int i = 0; i < ta1.Count; i++)
{
CType type1 = ta1[i];
CType type2 = ta2[i];
BetterType nParam = BetterType.Neither;
LAgain:
if (type1.GetTypeKind() != type2.GetTypeKind())
{
if (type1.IsTypeParameterType())
{
nParam = BetterType.Right;
}
else if (type2.IsTypeParameterType())
{
nParam = BetterType.Left;
}
}
else
{
switch (type1.GetTypeKind())
{
default:
Debug.Assert(false, "Bad kind in CompareTypes");
break;
case TypeKind.TK_TypeParameterType:
case TypeKind.TK_ErrorType:
break;
case TypeKind.TK_PointerType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
type1 = type1.GetBaseOrParameterOrElementType();
type2 = type2.GetBaseOrParameterOrElementType();
goto LAgain;
case TypeKind.TK_AggregateType:
nParam = CompareTypes(type1.AsAggregateType().GetTypeArgsAll(), type2.AsAggregateType().GetTypeArgsAll());
break;
}
}
if (nParam == BetterType.Right || nParam == BetterType.Left)
{
if (nTot == BetterType.Same || nTot == BetterType.Neither)
{
nTot = nParam;
}
else if (nParam != nTot)
{
return BetterType.Neither;
}
}
}
return nTot;
}
public SymFactory GetSymFactory()
{
return _symFactory;
}
public MiscSymFactory GetMiscSymFactory()
{
return _miscSymFactory;
}
////////////////////////////////////////////////////////////////////////////////
// Build the data structures needed to make FPreLoad fast. Make sure the
// namespaces are created. Compute and sort hashes of the NamespaceSymbol * value and type
// name (sans arity indicator).
private void InitPreLoad()
{
for (int i = 0; i < (int)PredefinedType.PT_COUNT; ++i)
{
NamespaceSymbol ns = GetRootNS();
string name = PredefinedTypeFacts.GetName((PredefinedType)i);
int start = 0;
while (start < name.Length)
{
int iDot = name.IndexOf('.', start);
if (iDot == -1) break;
string sub = (iDot > start) ? name.Substring(start, iDot - start) : name.Substring(start);
Name nm = this.GetNameManager().Add(sub);
NamespaceSymbol sym = this.LookupGlobalSymCore(nm, ns, symbmask_t.MASK_NamespaceSymbol).AsNamespaceSymbol();
if (sym == null)
{
ns = _symFactory.CreateNamespace(nm, ns);
}
else
{
ns = sym;
}
start += sub.Length + 1;
}
}
}
public Symbol LookupGlobalSymCore(Name name, ParentSymbol parent, symbmask_t kindmask)
{
return tableGlobal.LookupSym(name, parent, kindmask);
}
public Symbol LookupAggMember(Name name, AggregateSymbol agg, symbmask_t mask)
{
return tableGlobal.LookupSym(name, agg, mask);
}
public static Symbol LookupNextSym(Symbol sym, ParentSymbol parent, symbmask_t kindmask)
{
Debug.Assert(sym.parent == parent);
sym = sym.nextSameName;
Debug.Assert(sym == null || sym.parent == parent);
// Keep traversing the list of symbols with same name and parent.
while (sym != null)
{
if ((kindmask & sym.mask()) > 0)
return sym;
sym = sym.nextSameName;
Debug.Assert(sym == null || sym.parent == parent);
}
return null;
}
public Name GetNameFromPtrs(object u1, object u2)
{
// Note: this won't produce the same names as the native logic
if (u2 != null)
{
return this.m_nameTable.Add(string.Format(CultureInfo.InvariantCulture, "{0:X}-{1:X}", u1.GetHashCode(), u2.GetHashCode()));
}
else
{
return this.m_nameTable.Add(string.Format(CultureInfo.InvariantCulture, "{0:X}", u1.GetHashCode()));
}
}
private AssemblyQualifiedNamespaceSymbol GetNsAid(NamespaceSymbol ns, KAID aid)
{
Name name = GetNameFromPtrs(aid, 0);
Debug.Assert(name != null);
AssemblyQualifiedNamespaceSymbol nsa = LookupGlobalSymCore(name, ns, symbmask_t.MASK_AssemblyQualifiedNamespaceSymbol).AsAssemblyQualifiedNamespaceSymbol();
if (nsa == null)
{
// Create a new one.
nsa = _symFactory.CreateNamespaceAid(name, ns, aid);
}
Debug.Assert(nsa.GetNS() == ns);
return nsa;
}
////////////////////////////////////////////////////////////////////////////////
// Allocate a type array; used to represent a parameter list.
// We use a hash table to make sure that allocating the same type array twice
// returns the same value. This does two things:
//
// 1) Save a lot of memory.
// 2) Make it so parameter lists can be compared by a simple pointer comparison
// 3) Allow us to associate a token with each signature for faster metadata emit
private struct TypeArrayKey : IEquatable<TypeArrayKey>
{
private readonly CType[] _types;
private readonly int _hashCode;
public TypeArrayKey(CType[] types)
{
_types = types;
_hashCode = 0;
for (int i = 0, n = types.Length; i < n; i++)
{
_hashCode ^= types[i].GetHashCode();
}
}
public bool Equals(TypeArrayKey other)
{
CType[] types = _types;
CType[] otherTypes = other._types;
if (otherTypes == types)
{
return true;
}
if (other._hashCode != _hashCode || otherTypes.Length != types.Length)
{
return false;
}
for (int i = 0; i < types.Length; i++)
{
if (!types[i].Equals(otherTypes[i]))
{
return false;
}
}
return true;
}
#if DEBUG
[ExcludeFromCodeCoverage] // Typed overload should always be the method called.
#endif
public override bool Equals(object obj)
{
Debug.Fail("Sub-optimal overload called. Check if this can be avoided.");
return obj is TypeArrayKey && Equals((TypeArrayKey)obj);
}
public override int GetHashCode()
{
return _hashCode;
}
}
public TypeArray AllocParams(int ctype, CType[] prgtype)
{
if (ctype == 0)
{
return s_taEmpty;
}
Debug.Assert(ctype == prgtype.Length);
return AllocParams(prgtype);
}
public TypeArray AllocParams(int ctype, TypeArray array, int offset)
{
CType[] types = array.Items;
CType[] newTypes = new CType[ctype];
Array.ConstrainedCopy(types, offset, newTypes, 0, ctype);
return AllocParams(newTypes);
}
public TypeArray AllocParams(params CType[] types)
{
if (types == null || types.Length == 0)
{
return s_taEmpty;
}
TypeArrayKey key = new TypeArrayKey(types);
TypeArray result;
if (!tableTypeArrays.TryGetValue(key, out result))
{
result = new TypeArray(types);
tableTypeArrays.Add(key, result);
}
return result;
}
private TypeArray ConcatParams(CType[] prgtype1, CType[] prgtype2)
{
CType[] combined = new CType[prgtype1.Length + prgtype2.Length];
Array.Copy(prgtype1, 0, combined, 0, prgtype1.Length);
Array.Copy(prgtype2, 0, combined, prgtype1.Length, prgtype2.Length);
return AllocParams(combined);
}
public TypeArray ConcatParams(TypeArray pta1, TypeArray pta2)
{
return ConcatParams(pta1.Items, pta2.Items);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SystemConsole.cs" company="Obscureware Solutions">
// MIT License
//
// Copyright(c) 2015-2017 Sebastian Gruchacz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </copyright>
// <summary>
// Defines the core SystemConsole wrapper on SystemConsole that implements IConsole interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ObscureWare.Console
{
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Conditions;
/// <summary>
/// Wraps System.Console with IConsole interface methods
/// </summary>
public class SystemConsole : IConsole
{
private readonly ConsoleController _controller;
private readonly object _atomicHandle = new object();
/// <summary>
/// In characters...
/// </summary>
public Point WindowSize { get; }
/// <summary>
/// The most safe constructor - uses default window and buffer sizes
/// </summary>
/// <param name="controller"></param>
public SystemConsole(ConsoleController controller)
{
Condition.Requires(controller, nameof(controller)).IsNotNull();
this._controller = controller;
Console.OutputEncoding = Encoding.Unicode;
Console.InputEncoding = Encoding.Unicode;
this.WindowWidth = Console.WindowWidth;
this.WindowHeight = Console.WindowHeight;
}
/// <summary>
/// Full-screen constructor, when flag value is TRUE. If no - it's just constructs 120x40 window with 120x500 buffer (larger than default).
/// </summary>
/// <param name="controller"></param>
/// <param name="isFullScreen"></param>
public SystemConsole(ConsoleController controller, bool isFullScreen) : this(controller)
{
if (isFullScreen)
{
this.SetConsoleWindowToFullScreen();
// now can calculate how large could be full-screen buffer
// SG: (-2) On Win8 the only working way to keep borders on the screen :(
// (-1) required on Win10 though :(
this.WindowSize = new Point(Console.LargestWindowWidth - 2, Console.LargestWindowHeight - 1);
// setting full-screen
Console.BufferWidth = this.WindowSize.X;
Console.WindowWidth = this.WindowSize.X;
Console.BufferHeight = this.WindowSize.Y;
Console.WindowHeight = this.WindowSize.Y;
Console.SetWindowPosition(0, 0);
}
else
{
// set console (buffer) little bigger by default
Console.BufferWidth = 120;
Console.BufferHeight = 500;
Console.WindowWidth = 120;
Console.WindowHeight = 40;
}
this.WindowWidth = Console.WindowWidth;
this.WindowHeight = Console.WindowHeight;
}
/// <summary>
/// Custom sized console
/// </summary>
/// <param name="controller"></param>
/// <param name="bufferSize">Width and height of the buffer. Must be >= window size. Will be resized automatically if not fits...</param>
/// <param name="windowSize">Width and height of the window (In columns and rows, depends of font and screen resolution!). Cannot exceed screen size. Will be automatically trimmed.</param>
public SystemConsole(ConsoleController controller, Point bufferSize, Point windowSize) : this(controller)
{
windowSize.X = Math.Min(windowSize.X, Console.LargestWindowWidth - 2);
windowSize.Y = Math.Min(windowSize.Y, Console.LargestWindowHeight - 1);
bufferSize.X = Math.Max(bufferSize.X, windowSize.X);
bufferSize.Y = Math.Max(bufferSize.Y, windowSize.Y);
Console.BufferWidth = bufferSize.X;
Console.WindowWidth = windowSize.X;
Console.BufferHeight = bufferSize.Y;
Console.WindowHeight = windowSize.Y;
this.WindowWidth = Console.WindowWidth;
this.WindowHeight = Console.WindowHeight;
}
private void SetConsoleWindowToFullScreen()
{
// http://www.codeproject.com/Articles/4426/Console-Enhancements
this.SetWindowPosition(
0,
0,
Screen.PrimaryScreen.WorkingArea.Width - (2 * 16),
Screen.PrimaryScreen.WorkingArea.Height - (2 * 16) - SystemInformation.CaptionHeight);
}
/// <inheritdoc />
public void WriteText(int x, int y, string text, Color foreColor, Color bgColor)
{
this.SetCursorPosition(x, y);
this.SetColors(foreColor, bgColor);
this.WriteText(text);
}
/// <inheritdoc />
private void WriteText(string text)
{
Console.Write(text);
}
/// <inheritdoc />
void IConsole.WriteText(string text)
{
this.WriteText(text);
}
/// <inheritdoc />
public void WriteLine(ConsoleFontColor colors, string text)
{
this.SetColors(colors.ForeColor, colors.BgColor);
Console.WriteLine(text);
}
/// <inheritdoc />
public void WriteLine(string text)
{
Console.WriteLine(text);
}
/// <inheritdoc />
public void SetColors(Color foreColor, Color bgColor)
{
Console.ForegroundColor = this._controller.CloseColorFinder.FindClosestColor(foreColor);
Console.BackgroundColor = this._controller.CloseColorFinder.FindClosestColor(bgColor);
}
/// <inheritdoc />
public void Clear()
{
Console.Clear();
}
/// <inheritdoc />
public void WriteText(ConsoleFontColor colors, string text)
{
this.SetColors(colors.ForeColor, colors.BgColor);
Console.Write(text);
}
/// <inheritdoc />
public void SetCursorPosition(int x, int y)
{
Console.SetCursorPosition(x, y);
}
/// <inheritdoc />
public Point GetCursorPosition()
{
return new Point(Console.CursorLeft, Console.CursorTop);
}
/// <inheritdoc />
public void WriteText(char character)
{
Console.Write(character);
}
/// <inheritdoc />
public int WindowHeight { get; }
/// <inheritdoc />
public int WindowWidth { get; }
/// <inheritdoc />
public ConsoleMode ConsoleMode => ConsoleMode.Buffered;
/// <inheritdoc />
public string ReadLine()
{
return Console.ReadLine();
}
/// <inheritdoc />
public ConsoleKeyInfo ReadKey()
{
return Console.ReadKey(intercept: true);
}
/// <inheritdoc />
public void WriteLine()
{
Console.WriteLine();
}
/// <inheritdoc />
public void SetColors(ConsoleFontColor style)
{
this.SetColors(style.ForeColor, style.BgColor);
}
/// <inheritdoc />
public object AtomicHandle => this._atomicHandle;
/// <inheritdoc />
public void ReplaceConsoleColor(ConsoleColor color, Color rgbColor)
{
this._controller.ReplaceConsoleColor(color, rgbColor);
}
/// <summary>
/// Sets the console window location and size in pixels
/// </summary>
public void SetWindowPosition(int x, int y, int width, int height)
{
IntPtr hwnd = NativeMethods.GetConsoleWindow();
NativeMethods.SetWindowPos(hwnd, IntPtr.Zero, x, y, width, height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE);
// no release handle?
}
/// <inheritdoc />
public void HideCursor()
{
System.Console.CursorVisible = false;
}
/// <inheritdoc />
public void ShowCursor()
{
System.Console.CursorVisible = true;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MasterPage.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* MasterPage class definition
*
* Copyright (c) 1998 Microsoft Corporation
*/
namespace System.Web.UI {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Globalization;
using System.Security.Permissions;
using System.Reflection;
using System.Web.Hosting;
using System.Web.Compilation;
using System.Web.UI.WebControls;
using System.Web.Util;
public class MasterPageControlBuilder : UserControlControlBuilder {
internal static readonly String AutoTemplatePrefix = "Template_";
}
/// <devdoc>
/// Default ControlBuilder used to parse master page files. Note that this class inherits from FileLevelPageControlBuilder
/// to reuse masterpage handling code.
/// </devdoc>
public class FileLevelMasterPageControlBuilder: FileLevelPageControlBuilder {
internal override void AddContentTemplate(object obj, string templateName, ITemplate template) {
MasterPage master = (MasterPage)obj;
master.AddContentTemplate(templateName, template);
}
}
/// <devdoc>
/// <para>This class is not marked as abstract, because the VS designer
/// needs to instantiate it when opening .master files</para>
/// </devdoc>
[
Designer("Microsoft.VisualStudio.Web.WebForms.MasterPageWebFormDesigner, " + AssemblyRef.MicrosoftVisualStudioWeb, typeof(IRootDesigner)),
ControlBuilder(typeof(MasterPageControlBuilder)),
ParseChildren(false)
]
public class MasterPage : UserControl {
private VirtualPath _masterPageFile;
private MasterPage _master;
// The collection used to store the templates created on the content page.
private IDictionary _contentTemplates;
// The collection used to store the content templates defined in MasterPage.
private IDictionary _contentTemplateCollection;
private IList _contentPlaceHolders;
private bool _masterPageApplied;
// The page or masterpage that hosts this masterPage.
internal TemplateControl _ownerControl;
public MasterPage() {
}
/// <devdoc>
/// <para>Dictionary used to store the content templates that are passed in from the content pages.</para>
/// </devdoc>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal IDictionary ContentTemplates {
get {
return _contentTemplates;
}
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal IList ContentPlaceHolders {
get {
if (_contentPlaceHolders == null) {
_contentPlaceHolders = new ArrayList();
}
return _contentPlaceHolders;
}
}
/// <devdoc>
/// <para>The MasterPage used by this nested MasterPage control.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
WebSysDescription(SR.MasterPage_MasterPage)
]
public MasterPage Master {
get {
if (_master == null && !_masterPageApplied) {
_master = MasterPage.CreateMaster(this, Context, _masterPageFile, _contentTemplateCollection);
}
return _master;
}
}
/// <devdoc>
/// <para>Gets and sets the masterPageFile of this control.</para>
/// </devdoc>
[
DefaultValue(""),
WebCategory("Behavior"),
WebSysDescription(SR.MasterPage_MasterPageFile)
]
public string MasterPageFile {
get {
return VirtualPath.GetVirtualPathString(_masterPageFile);
}
set {
if (_masterPageApplied) {
throw new InvalidOperationException(SR.GetString(SR.PropertySetBeforePageEvent, "MasterPageFile", "Page_PreInit"));
}
if (value != VirtualPath.GetVirtualPathString(_masterPageFile)) {
_masterPageFile = VirtualPath.CreateAllowNull(value);
if (_master != null && Controls.Contains(_master)) {
Controls.Remove(_master);
}
_master = null;
}
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal void AddContentTemplate(string templateName, ITemplate template) {
if (_contentTemplateCollection == null) {
_contentTemplateCollection = new Hashtable(10, StringComparer.OrdinalIgnoreCase);
}
try {
_contentTemplateCollection.Add(templateName, template);
}
catch (ArgumentException) {
throw new HttpException(SR.GetString(SR.MasterPage_Multiple_content, templateName));
}
}
internal static MasterPage CreateMaster(TemplateControl owner, HttpContext context,
VirtualPath masterPageFile, IDictionary contentTemplateCollection) {
Debug.Assert(owner is MasterPage || owner is Page);
MasterPage master = null;
if (masterPageFile == null) {
if (contentTemplateCollection != null && contentTemplateCollection.Count > 0) {
throw new HttpException(SR.GetString(SR.Content_only_allowed_in_content_page));
}
return null;
}
// If it's relative, make it *app* relative. Treat is as relative to this
// user control (ASURT 55513)
VirtualPath virtualPath = VirtualPathProvider.CombineVirtualPathsInternal(
owner.TemplateControlVirtualPath, masterPageFile);
// Compile the declarative control and get its Type
ITypedWebObjectFactory result = (ITypedWebObjectFactory)BuildManager.GetVPathBuildResult(
context, virtualPath);
// Make sure it has the correct base type
if (!typeof(MasterPage).IsAssignableFrom(result.InstantiatedType)) {
throw new HttpException(SR.GetString(SR.Invalid_master_base,
masterPageFile));
}
master = (MasterPage)result.CreateInstance();
master.TemplateControlVirtualPath = virtualPath;
if (owner.HasControls()) {
foreach (Control control in owner.Controls) {
LiteralControl literal = control as LiteralControl;
if (literal == null || Util.FirstNonWhiteSpaceIndex(literal.Text) >= 0) {
throw new HttpException(SR.GetString(SR.Content_allowed_in_top_level_only));
}
}
// Remove existing controls.
owner.Controls.Clear();
}
// Make sure the control collection is writable.
if (owner.Controls.IsReadOnly) {
throw new HttpException(SR.GetString(SR.MasterPage_Cannot_ApplyTo_ReadOnly_Collection));
}
if (contentTemplateCollection != null) {
foreach(String contentName in contentTemplateCollection.Keys) {
if (!master.ContentPlaceHolders.Contains(contentName.ToLower(CultureInfo.InvariantCulture))) {
throw new HttpException(SR.GetString(SR.MasterPage_doesnt_have_contentplaceholder, contentName, masterPageFile));
}
}
master._contentTemplates = contentTemplateCollection;
}
master._ownerControl = owner;
master.InitializeAsUserControl(owner.Page);
owner.Controls.Add(master);
return master;
}
internal static void ApplyMasterRecursive(MasterPage master, IList appliedMasterFilePaths) {
Debug.Assert(appliedMasterFilePaths != null);
// Recursively apply master pages to the nested masterpages.
if (master.Master != null) {
string pageFile = master._masterPageFile.VirtualPathString.ToLower(CultureInfo.InvariantCulture);
if (appliedMasterFilePaths.Contains(pageFile)) {
throw new InvalidOperationException(SR.GetString(SR.MasterPage_Circular_Master_Not_Allowed, master._masterPageFile));
}
appliedMasterFilePaths.Add(pageFile);
ApplyMasterRecursive(master.Master, appliedMasterFilePaths);
}
master._masterPageApplied = true;
}
public void InstantiateInContentPlaceHolder(Control contentPlaceHolder, ITemplate template) {
HttpContext context = HttpContext.Current;
// Remember the old TemplateControl
TemplateControl oldControl = context.TemplateControl;
// Storing the template control into the context
// since each thread needs to set it differently.
context.TemplateControl = _ownerControl;
try {
// Instantiate the template using the correct TemplateControl
template.InstantiateIn(contentPlaceHolder);
}
finally {
// Revert back to the old templateControl
context.TemplateControl = oldControl;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.Network;
using Microsoft.WindowsAzure.Management.Network.Models;
namespace Microsoft.WindowsAzure.Management.Network
{
/// <summary>
/// The Network Management API includes operations for managing the client
/// root certificates for your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for
/// more information)
/// </summary>
internal partial class ClientRootCertificateOperations : IServiceOperations<NetworkManagementClient>, IClientRootCertificateOperations
{
/// <summary>
/// Initializes a new instance of the ClientRootCertificateOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ClientRootCertificateOperations(NetworkManagementClient client)
{
this._client = client;
}
private NetworkManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient.
/// </summary>
public NetworkManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Upload Client Root Certificate operation is used to upload a
/// new client root certificate to Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx
/// for more information)
/// </summary>
/// <param name='networkName'>
/// Required. The name of the virtual network for this gateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Upload Client Root Certificate
/// Virtual Network Gateway operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<GatewayOperationResponse> CreateAsync(string networkName, ClientRootCertificateCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (networkName == null)
{
throw new ArgumentNullException("networkName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Certificate == null)
{
throw new ArgumentNullException("parameters.Certificate");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("networkName", networkName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/";
url = url + Uri.EscapeDataString(networkName);
url = url + "/gateway/clientrootcertificates";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Certificate;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GatewayOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GatewayOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Delete Client Root Certificate operation deletes a previously
/// uploaded client root certificate from Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn205128.aspx
/// for more information)
/// </summary>
/// <param name='networkName'>
/// Required. The name of the virtual network for this gateway.
/// </param>
/// <param name='certificateThumbprint'>
/// Required. The X509 certificate thumbprint.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<GatewayOperationResponse> DeleteAsync(string networkName, string certificateThumbprint, CancellationToken cancellationToken)
{
// Validate
if (networkName == null)
{
throw new ArgumentNullException("networkName");
}
if (certificateThumbprint == null)
{
throw new ArgumentNullException("certificateThumbprint");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("networkName", networkName);
tracingParameters.Add("certificateThumbprint", certificateThumbprint);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/";
url = url + Uri.EscapeDataString(networkName);
url = url + "/gateway/clientrootcertificates/";
url = url + Uri.EscapeDataString(certificateThumbprint);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GatewayOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GatewayOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Client Root Certificate operation returns the public
/// portion of a previously uploaded client root certificate in a
/// base-64-encoded format from Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn205127.aspx
/// for more information)
/// </summary>
/// <param name='networkName'>
/// Required. The name of the virtual network for this gateway.
/// </param>
/// <param name='certificateThumbprint'>
/// Required. The X509 certificate thumbprint.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response to the Get Client Root Certificate operation.
/// </returns>
public async Task<ClientRootCertificateGetResponse> GetAsync(string networkName, string certificateThumbprint, CancellationToken cancellationToken)
{
// Validate
if (networkName == null)
{
throw new ArgumentNullException("networkName");
}
if (certificateThumbprint == null)
{
throw new ArgumentNullException("certificateThumbprint");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("networkName", networkName);
tracingParameters.Add("certificateThumbprint", certificateThumbprint);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/";
url = url + Uri.EscapeDataString(networkName);
url = url + "/gateway/clientrootcertificates/";
url = url + Uri.EscapeDataString(certificateThumbprint);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ClientRootCertificateGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ClientRootCertificateGetResponse();
result.Certificate = responseContent;
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Client Root Certificates operation returns a list of all
/// the client root certificates that are associated with the
/// specified virtual network in Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx
/// for more information)
/// </summary>
/// <param name='networkName'>
/// Required. The name of the virtual network for this gateway.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response for the List Client Root Certificates operation.
/// </returns>
public async Task<ClientRootCertificateListResponse> ListAsync(string networkName, CancellationToken cancellationToken)
{
// Validate
if (networkName == null)
{
throw new ArgumentNullException("networkName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("networkName", networkName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/";
url = url + Uri.EscapeDataString(networkName);
url = url + "/gateway/clientrootcertificates";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2016-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ClientRootCertificateListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ClientRootCertificateListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement clientRootCertificatesSequenceElement = responseDoc.Element(XName.Get("ClientRootCertificates", "http://schemas.microsoft.com/windowsazure"));
if (clientRootCertificatesSequenceElement != null)
{
foreach (XElement clientRootCertificatesElement in clientRootCertificatesSequenceElement.Elements(XName.Get("ClientRootCertificate", "http://schemas.microsoft.com/windowsazure")))
{
ClientRootCertificateListResponse.ClientRootCertificate clientRootCertificateInstance = new ClientRootCertificateListResponse.ClientRootCertificate();
result.ClientRootCertificates.Add(clientRootCertificateInstance);
XElement expirationTimeElement = clientRootCertificatesElement.Element(XName.Get("ExpirationTime", "http://schemas.microsoft.com/windowsazure"));
if (expirationTimeElement != null)
{
DateTime expirationTimeInstance = DateTime.Parse(expirationTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
clientRootCertificateInstance.ExpirationTime = expirationTimeInstance;
}
XElement subjectElement = clientRootCertificatesElement.Element(XName.Get("Subject", "http://schemas.microsoft.com/windowsazure"));
if (subjectElement != null)
{
string subjectInstance = subjectElement.Value;
clientRootCertificateInstance.Subject = subjectInstance;
}
XElement thumbprintElement = clientRootCertificatesElement.Element(XName.Get("Thumbprint", "http://schemas.microsoft.com/windowsazure"));
if (thumbprintElement != null)
{
string thumbprintInstance = thumbprintElement.Value;
clientRootCertificateInstance.Thumbprint = thumbprintInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
public partial class Process : IDisposable
{
private static readonly object s_createProcessLock = new object();
/// <summary>
/// Creates an array of <see cref="Process"/> components that are associated with process resources on a
/// remote computer. These process resources share the specified process name.
/// </summary>
public static Process[] GetProcessesByName(string processName, string machineName)
{
if (processName == null)
{
processName = string.Empty;
}
Process[] procs = GetProcesses(machineName);
var list = new List<Process>();
for (int i = 0; i < procs.Length; i++)
{
if (string.Equals(processName, procs[i].ProcessName, StringComparison.OrdinalIgnoreCase))
{
list.Add(procs[i]);
}
else
{
procs[i].Dispose();
}
}
return list.ToArray();
}
[CLSCompliant(false)]
public static Process Start(string fileName, string userName, SecureString password, string domain)
{
ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
startInfo.UserName = userName;
startInfo.Password = password;
startInfo.Domain = domain;
startInfo.UseShellExecute = false;
return Start(startInfo);
}
[CLSCompliant(false)]
public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain)
{
ProcessStartInfo startInfo = new ProcessStartInfo(fileName, arguments);
startInfo.UserName = userName;
startInfo.Password = password;
startInfo.Domain = domain;
startInfo.UseShellExecute = false;
return Start(startInfo);
}
/// <summary>
/// Puts a Process component in state to interact with operating system processes that run in a
/// special mode by enabling the native property SeDebugPrivilege on the current thread.
/// </summary>
public static void EnterDebugMode()
{
SetPrivilege(Interop.Advapi32.SeDebugPrivilege, (int)Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED);
}
/// <summary>
/// Takes a Process component out of the state that lets it interact with operating system processes
/// that run in a special mode.
/// </summary>
public static void LeaveDebugMode()
{
SetPrivilege(Interop.Advapi32.SeDebugPrivilege, 0);
}
/// <summary>Terminates the associated process immediately.</summary>
public void Kill()
{
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_TERMINATE | Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION, throwIfExited: false))
{
// If the process has exited, the handle is invalid.
if (handle.IsInvalid)
return;
if (!Interop.Kernel32.TerminateProcess(handle, -1))
{
// Capture the exception
var exception = new Win32Exception();
// Don't throw if the process has exited.
if (exception.NativeErrorCode == Interop.Errors.ERROR_ACCESS_DENIED &&
Interop.Kernel32.GetExitCodeProcess(handle, out int localExitCode) && localExitCode != Interop.Kernel32.HandleOptions.STILL_ACTIVE)
{
return;
}
throw exception;
}
}
}
/// <summary>Discards any information about the associated process.</summary>
private void RefreshCore()
{
_signaled = false;
}
/// <summary>Additional logic invoked when the Process is closed.</summary>
private void CloseCore()
{
// Nop
}
/// <devdoc>
/// Make sure we are watching for a process exit.
/// </devdoc>
/// <internalonly/>
private void EnsureWatchingForExit()
{
if (!_watchingForExit)
{
lock (this)
{
if (!_watchingForExit)
{
Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process");
_watchingForExit = true;
try
{
_waitHandle = new Interop.Kernel32.ProcessWaitHandle(GetOrOpenProcessHandle());
_registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle,
new WaitOrTimerCallback(CompletionCallback), _waitHandle, -1, true);
}
catch
{
_watchingForExit = false;
throw;
}
}
}
}
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit.
/// </summary>
private bool WaitForExitCore(int milliseconds)
{
SafeProcessHandle handle = null;
try
{
handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.SYNCHRONIZE, false);
if (handle.IsInvalid)
return true;
using (Interop.Kernel32.ProcessWaitHandle processWaitHandle = new Interop.Kernel32.ProcessWaitHandle(handle))
{
return _signaled = processWaitHandle.WaitOne(milliseconds);
}
}
finally
{
// If we have a hard timeout, we cannot wait for the streams
if (_output != null && milliseconds == Timeout.Infinite)
_output.WaitUtilEOF();
if (_error != null && milliseconds == Timeout.Infinite)
_error.WaitUtilEOF();
handle?.Dispose();
}
}
/// <summary>Gets the main module for the associated process.</summary>
public ProcessModule MainModule
{
get
{
// We only return null if we couldn't find a main module. This could be because
// the process hasn't finished loading the main module (most likely).
// On NT, the first module is the main module.
EnsureState(State.HaveId | State.IsLocal);
return NtProcessManager.GetFirstModule(_processId);
}
}
/// <summary>Checks whether the process has exited and updates state accordingly.</summary>
private void UpdateHasExited()
{
using (SafeProcessHandle handle = GetProcessHandle(
Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION | Interop.Advapi32.ProcessOptions.SYNCHRONIZE, false))
{
if (handle.IsInvalid)
{
_exited = true;
}
else
{
int localExitCode;
// Although this is the wrong way to check whether the process has exited,
// it was historically the way we checked for it, and a lot of code then took a dependency on
// the fact that this would always be set before the pipes were closed, so they would read
// the exit code out after calling ReadToEnd() or standard output or standard error. In order
// to allow 259 to function as a valid exit code and to break as few people as possible that
// took the ReadToEnd dependency, we check for an exit code before doing the more correct
// check to see if we have been signaled.
if (Interop.Kernel32.GetExitCodeProcess(handle, out localExitCode) && localExitCode != Interop.Kernel32.HandleOptions.STILL_ACTIVE)
{
_exitCode = localExitCode;
_exited = true;
}
else
{
// The best check for exit is that the kernel process object handle is invalid,
// or that it is valid and signaled. Checking if the exit code != STILL_ACTIVE
// does not guarantee the process is closed,
// since some process could return an actual STILL_ACTIVE exit code (259).
if (!_signaled) // if we just came from WaitForExit, don't repeat
{
using (var wh = new Interop.Kernel32.ProcessWaitHandle(handle))
{
_signaled = wh.WaitOne(0);
}
}
if (_signaled)
{
if (!Interop.Kernel32.GetExitCodeProcess(handle, out localExitCode))
throw new Win32Exception();
_exitCode = localExitCode;
_exited = true;
}
}
}
}
}
/// <summary>Gets the time that the associated process exited.</summary>
private DateTime ExitTimeCore
{
get { return GetProcessTimes().ExitTime; }
}
/// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary>
public TimeSpan PrivilegedProcessorTime
{
get { return GetProcessTimes().PrivilegedProcessorTime; }
}
/// <summary>Gets the time the associated process was started.</summary>
internal DateTime StartTimeCore
{
get { return GetProcessTimes().StartTime; }
}
/// <summary>
/// Gets the amount of time the associated process has spent utilizing the CPU.
/// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and
/// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>.
/// </summary>
public TimeSpan TotalProcessorTime
{
get { return GetProcessTimes().TotalProcessorTime; }
}
/// <summary>
/// Gets the amount of time the associated process has spent running code
/// inside the application portion of the process (not the operating system core).
/// </summary>
public TimeSpan UserProcessorTime
{
get { return GetProcessTimes().UserProcessorTime; }
}
/// <summary>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </summary>
private bool PriorityBoostEnabledCore
{
get
{
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION))
{
bool disabled;
if (!Interop.Kernel32.GetProcessPriorityBoost(handle, out disabled))
{
throw new Win32Exception();
}
return !disabled;
}
}
set
{
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION))
{
if (!Interop.Kernel32.SetProcessPriorityBoost(handle, !value))
throw new Win32Exception();
}
}
}
/// <summary>
/// Gets or sets the overall priority category for the associated process.
/// </summary>
private ProcessPriorityClass PriorityClassCore
{
get
{
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION))
{
int value = Interop.Kernel32.GetPriorityClass(handle);
if (value == 0)
{
throw new Win32Exception();
}
return (ProcessPriorityClass)value;
}
}
set
{
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION))
{
if (!Interop.Kernel32.SetPriorityClass(handle, (int)value))
throw new Win32Exception();
}
}
}
/// <summary>
/// Gets or sets which processors the threads in this process can be scheduled to run on.
/// </summary>
private IntPtr ProcessorAffinityCore
{
get
{
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION))
{
IntPtr processAffinity, systemAffinity;
if (!Interop.Kernel32.GetProcessAffinityMask(handle, out processAffinity, out systemAffinity))
throw new Win32Exception();
return processAffinity;
}
}
set
{
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION))
{
if (!Interop.Kernel32.SetProcessAffinityMask(handle, value))
throw new Win32Exception();
}
}
}
/// <summary>Gets the ID of the current process.</summary>
private static int GetCurrentProcessId()
{
return unchecked((int)Interop.Kernel32.GetCurrentProcessId());
}
/// <summary>
/// Gets a short-term handle to the process, with the given access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle GetProcessHandle()
{
return GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_ALL_ACCESS);
}
/// <summary>Get the minimum and maximum working set limits.</summary>
private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet)
{
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION))
{
int ignoredFlags;
if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out minWorkingSet, out maxWorkingSet, out ignoredFlags))
throw new Win32Exception();
}
}
/// <summary>Sets one or both of the minimum and maximum working set limits.</summary>
/// <param name="newMin">The new minimum working set limit, or null not to change it.</param>
/// <param name="newMax">The new maximum working set limit, or null not to change it.</param>
/// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param>
/// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param>
private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax)
{
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_SET_QUOTA))
{
IntPtr min, max;
int ignoredFlags;
if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags))
{
throw new Win32Exception();
}
if (newMin.HasValue)
{
min = newMin.Value;
}
if (newMax.HasValue)
{
max = newMax.Value;
}
if ((long)min > (long)max)
{
if (newMin != null)
{
throw new ArgumentException(SR.BadMinWorkset);
}
else
{
throw new ArgumentException(SR.BadMaxWorkset);
}
}
// We use SetProcessWorkingSetSizeEx which gives an option to follow
// the max and min value even in low-memory and abundant-memory situations.
// However, we do not use these flags to emulate the existing behavior
if (!Interop.Kernel32.SetProcessWorkingSetSizeEx(handle, min, max, 0))
{
throw new Win32Exception();
}
// The value may be rounded/changed by the OS, so go get it
if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags))
{
throw new Win32Exception();
}
resultingMin = min;
resultingMax = max;
}
}
/// <summary>Starts the process using the supplied start info.</summary>
/// <param name="startInfo">The start info with which to start the process.</param>
private unsafe bool StartWithCreateProcess(ProcessStartInfo startInfo)
{
// See knowledge base article Q190351 for an explanation of the following code. Noteworthy tricky points:
// * The handles are duplicated as non-inheritable before they are passed to CreateProcess so
// that the child process can not close them
// * CreateProcess allows you to redirect all or none of the standard IO handles, so we use
// GetStdHandle for the handles that are not being redirected
StringBuilder commandLine = BuildCommandLine(startInfo.FileName, StartInfo.Arguments);
Process.AppendArguments(commandLine, StartInfo.ArgumentList);
Interop.Kernel32.STARTUPINFO startupInfo = new Interop.Kernel32.STARTUPINFO();
Interop.Kernel32.PROCESS_INFORMATION processInfo = new Interop.Kernel32.PROCESS_INFORMATION();
Interop.Kernel32.SECURITY_ATTRIBUTES unused_SecAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES();
SafeProcessHandle procSH = new SafeProcessHandle();
SafeThreadHandle threadSH = new SafeThreadHandle();
// handles used in parent process
SafeFileHandle parentInputPipeHandle = null;
SafeFileHandle childInputPipeHandle = null;
SafeFileHandle parentOutputPipeHandle = null;
SafeFileHandle childOutputPipeHandle = null;
SafeFileHandle parentErrorPipeHandle = null;
SafeFileHandle childErrorPipeHandle = null;
lock (s_createProcessLock)
{
try
{
startupInfo.cb = sizeof(Interop.Kernel32.STARTUPINFO);
// set up the streams
if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
{
if (startInfo.RedirectStandardInput)
{
CreatePipe(out parentInputPipeHandle, out childInputPipeHandle, true);
}
else
{
childInputPipeHandle = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE), false);
}
if (startInfo.RedirectStandardOutput)
{
CreatePipe(out parentOutputPipeHandle, out childOutputPipeHandle, false);
}
else
{
childOutputPipeHandle = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE), false);
}
if (startInfo.RedirectStandardError)
{
CreatePipe(out parentErrorPipeHandle, out childErrorPipeHandle, false);
}
else
{
childErrorPipeHandle = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE), false);
}
startupInfo.hStdInput = childInputPipeHandle.DangerousGetHandle();
startupInfo.hStdOutput = childOutputPipeHandle.DangerousGetHandle();
startupInfo.hStdError = childErrorPipeHandle.DangerousGetHandle();
startupInfo.dwFlags = Interop.Advapi32.StartupInfoOptions.STARTF_USESTDHANDLES;
}
// set up the creation flags parameter
int creationFlags = 0;
if (startInfo.CreateNoWindow) creationFlags |= Interop.Advapi32.StartupInfoOptions.CREATE_NO_WINDOW;
// set up the environment block parameter
string environmentBlock = null;
if (startInfo._environmentVariables != null)
{
creationFlags |= Interop.Advapi32.StartupInfoOptions.CREATE_UNICODE_ENVIRONMENT;
environmentBlock = GetEnvironmentVariablesBlock(startInfo._environmentVariables);
}
string workingDirectory = startInfo.WorkingDirectory;
if (workingDirectory == string.Empty)
workingDirectory = Directory.GetCurrentDirectory();
bool retVal;
int errorCode = 0;
if (startInfo.UserName.Length != 0)
{
if (startInfo.Password != null && startInfo.PasswordInClearText != null)
{
throw new ArgumentException(SR.CantSetDuplicatePassword);
}
Interop.Advapi32.LogonFlags logonFlags = (Interop.Advapi32.LogonFlags)0;
if (startInfo.LoadUserProfile)
{
logonFlags = Interop.Advapi32.LogonFlags.LOGON_WITH_PROFILE;
}
fixed (char* passwordInClearTextPtr = startInfo.PasswordInClearText ?? string.Empty)
fixed (char* environmentBlockPtr = environmentBlock)
{
IntPtr passwordPtr = (startInfo.Password != null) ?
Marshal.SecureStringToGlobalAllocUnicode(startInfo.Password) : IntPtr.Zero;
try
{
retVal = Interop.Advapi32.CreateProcessWithLogonW(
startInfo.UserName,
startInfo.Domain,
(passwordPtr != IntPtr.Zero) ? passwordPtr : (IntPtr)passwordInClearTextPtr,
logonFlags,
null, // we don't need this since all the info is in commandLine
commandLine,
creationFlags,
(IntPtr)environmentBlockPtr,
workingDirectory,
ref startupInfo, // pointer to STARTUPINFO
ref processInfo // pointer to PROCESS_INFORMATION
);
if (!retVal)
errorCode = Marshal.GetLastWin32Error();
}
finally
{
if (passwordPtr != IntPtr.Zero)
Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
}
}
}
else
{
fixed (char* environmentBlockPtr = environmentBlock)
{
retVal = Interop.Kernel32.CreateProcess(
null, // we don't need this since all the info is in commandLine
commandLine, // pointer to the command line string
ref unused_SecAttrs, // address to process security attributes, we don't need to inherit the handle
ref unused_SecAttrs, // address to thread security attributes.
true, // handle inheritance flag
creationFlags, // creation flags
(IntPtr)environmentBlockPtr, // pointer to new environment block
workingDirectory, // pointer to current directory name
ref startupInfo, // pointer to STARTUPINFO
ref processInfo // pointer to PROCESS_INFORMATION
);
if (!retVal)
errorCode = Marshal.GetLastWin32Error();
}
}
if (processInfo.hProcess != IntPtr.Zero && processInfo.hProcess != new IntPtr(-1))
procSH.InitialSetHandle(processInfo.hProcess);
if (processInfo.hThread != IntPtr.Zero && processInfo.hThread != new IntPtr(-1))
threadSH.InitialSetHandle(processInfo.hThread);
if (!retVal)
{
if (errorCode == Interop.Errors.ERROR_BAD_EXE_FORMAT || errorCode == Interop.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH)
{
throw new Win32Exception(errorCode, SR.InvalidApplication);
}
throw new Win32Exception(errorCode);
}
}
finally
{
childInputPipeHandle?.Dispose();
childOutputPipeHandle?.Dispose();
childErrorPipeHandle?.Dispose();
threadSH?.Dispose();
}
}
if (startInfo.RedirectStandardInput)
{
Encoding enc = startInfo.StandardInputEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleCP());
_standardInput = new StreamWriter(new FileStream(parentInputPipeHandle, FileAccess.Write, 4096, false), enc, 4096);
_standardInput.AutoFlush = true;
}
if (startInfo.RedirectStandardOutput)
{
Encoding enc = startInfo.StandardOutputEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleOutputCP());
_standardOutput = new StreamReader(new FileStream(parentOutputPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096);
}
if (startInfo.RedirectStandardError)
{
Encoding enc = startInfo.StandardErrorEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleOutputCP());
_standardError = new StreamReader(new FileStream(parentErrorPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096);
}
if (procSH.IsInvalid)
return false;
SetProcessHandle(procSH);
SetProcessId((int)processInfo.dwProcessId);
return true;
}
private static Encoding GetEncoding(int codePage)
{
Encoding enc = EncodingHelper.GetSupportedConsoleEncoding(codePage);
return new ConsoleEncoding(enc); // ensure encoding doesn't output a preamble
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private bool _signaled;
private static StringBuilder BuildCommandLine(string executableFileName, string arguments)
{
// Construct a StringBuilder with the appropriate command line
// to pass to CreateProcess. If the filename isn't already
// in quotes, we quote it here. This prevents some security
// problems (it specifies exactly which part of the string
// is the file to execute).
StringBuilder commandLine = new StringBuilder();
string fileName = executableFileName.Trim();
bool fileNameIsQuoted = (fileName.StartsWith("\"", StringComparison.Ordinal) && fileName.EndsWith("\"", StringComparison.Ordinal));
if (!fileNameIsQuoted)
{
commandLine.Append("\"");
}
commandLine.Append(fileName);
if (!fileNameIsQuoted)
{
commandLine.Append("\"");
}
if (!string.IsNullOrEmpty(arguments))
{
commandLine.Append(" ");
commandLine.Append(arguments);
}
return commandLine;
}
/// <summary>Gets timing information for the current process.</summary>
private ProcessThreadTimes GetProcessTimes()
{
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION, false))
{
if (handle.IsInvalid)
{
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString()));
}
ProcessThreadTimes processTimes = new ProcessThreadTimes();
if (!Interop.Kernel32.GetProcessTimes(handle,
out processTimes._create, out processTimes._exit,
out processTimes._kernel, out processTimes._user))
{
throw new Win32Exception();
}
return processTimes;
}
}
private static unsafe void SetPrivilege(string privilegeName, int attrib)
{
// this is only a "pseudo handle" to the current process - no need to close it later
SafeProcessHandle processHandle = Interop.Kernel32.GetCurrentProcess();
SafeTokenHandle hToken = null;
try
{
// get the process token so we can adjust the privilege on it. We DO need to
// close the token when we're done with it.
if (!Interop.Advapi32.OpenProcessToken(processHandle, Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out hToken))
{
throw new Win32Exception();
}
if (!Interop.Advapi32.LookupPrivilegeValue(null, privilegeName, out Interop.Advapi32.LUID luid))
{
throw new Win32Exception();
}
Interop.Advapi32.TOKEN_PRIVILEGE tp;
tp.PrivilegeCount = 1;
tp.Privileges.Luid = luid;
tp.Privileges.Attributes = (uint)attrib;
Interop.Advapi32.AdjustTokenPrivileges(hToken, false, &tp, 0, null, null);
// AdjustTokenPrivileges can return true even if it failed to
// set the privilege, so we need to use GetLastError
if (Marshal.GetLastWin32Error() != Interop.Errors.ERROR_SUCCESS)
{
throw new Win32Exception();
}
}
finally
{
if (hToken != null)
{
hToken.Dispose();
}
}
}
/// <devdoc>
/// Gets a short-term handle to the process, with the given access.
/// If a handle is stored in current process object, then use it.
/// Note that the handle we stored in current process object will have all access we need.
/// </devdoc>
/// <internalonly/>
private SafeProcessHandle GetProcessHandle(int access, bool throwIfExited)
{
if (_haveProcessHandle)
{
if (throwIfExited)
{
// Since haveProcessHandle is true, we know we have the process handle
// open with at least SYNCHRONIZE access, so we can wait on it with
// zero timeout to see if the process has exited.
using (Interop.Kernel32.ProcessWaitHandle waitHandle = new Interop.Kernel32.ProcessWaitHandle(_processHandle))
{
if (waitHandle.WaitOne(0))
{
if (_haveProcessId)
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString()));
else
throw new InvalidOperationException(SR.ProcessHasExitedNoId);
}
}
}
// If we dispose of our contained handle we'll be in a bad state. NetFX dealt with this
// by doing a try..finally around every usage of GetProcessHandle and only disposed if
// it wasn't our handle.
return new SafeProcessHandle(_processHandle.DangerousGetHandle(), ownsHandle: false);
}
else
{
EnsureState(State.HaveId | State.IsLocal);
SafeProcessHandle handle = SafeProcessHandle.InvalidHandle;
handle = ProcessManager.OpenProcess(_processId, access, throwIfExited);
if (throwIfExited && (access & Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION) != 0)
{
if (Interop.Kernel32.GetExitCodeProcess(handle, out _exitCode) && _exitCode != Interop.Kernel32.HandleOptions.STILL_ACTIVE)
{
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString()));
}
}
return handle;
}
}
/// <devdoc>
/// Gets a short-term handle to the process, with the given access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </devdoc>
/// <internalonly/>
private SafeProcessHandle GetProcessHandle(int access)
{
return GetProcessHandle(access, true);
}
private static void CreatePipeWithSecurityAttributes(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, ref Interop.Kernel32.SECURITY_ATTRIBUTES lpPipeAttributes, int nSize)
{
bool ret = Interop.Kernel32.CreatePipe(out hReadPipe, out hWritePipe, ref lpPipeAttributes, nSize);
if (!ret || hReadPipe.IsInvalid || hWritePipe.IsInvalid)
{
throw new Win32Exception();
}
}
// Using synchronous Anonymous pipes for process input/output redirection means we would end up
// wasting a worker threadpool thread per pipe instance. Overlapped pipe IO is desirable, since
// it will take advantage of the NT IO completion port infrastructure. But we can't really use
// Overlapped I/O for process input/output as it would break Console apps (managed Console class
// methods such as WriteLine as well as native CRT functions like printf) which are making an
// assumption that the console standard handles (obtained via GetStdHandle()) are opened
// for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchronously!
private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs)
{
Interop.Kernel32.SECURITY_ATTRIBUTES securityAttributesParent = new Interop.Kernel32.SECURITY_ATTRIBUTES();
securityAttributesParent.bInheritHandle = Interop.BOOL.TRUE;
SafeFileHandle hTmp = null;
try
{
if (parentInputs)
{
CreatePipeWithSecurityAttributes(out childHandle, out hTmp, ref securityAttributesParent, 0);
}
else
{
CreatePipeWithSecurityAttributes(out hTmp,
out childHandle,
ref securityAttributesParent,
0);
}
// Duplicate the parent handle to be non-inheritable so that the child process
// doesn't have access. This is done for correctness sake, exact reason is unclear.
// One potential theory is that child process can do something brain dead like
// closing the parent end of the pipe and there by getting into a blocking situation
// as parent will not be draining the pipe at the other end anymore.
SafeProcessHandle currentProcHandle = Interop.Kernel32.GetCurrentProcess();
if (!Interop.Kernel32.DuplicateHandle(currentProcHandle,
hTmp,
currentProcHandle,
out parentHandle,
0,
false,
Interop.Kernel32.HandleOptions.DUPLICATE_SAME_ACCESS))
{
throw new Win32Exception();
}
}
finally
{
if (hTmp != null && !hTmp.IsInvalid)
{
hTmp.Dispose();
}
}
}
private static string GetEnvironmentVariablesBlock(IDictionary<string, string> sd)
{
// get the keys
string[] keys = new string[sd.Count];
sd.Keys.CopyTo(keys, 0);
// sort both by the keys
// Windows 2000 requires the environment block to be sorted by the key
// It will first converting the case the strings and do ordinal comparison.
// We do not use Array.Sort(keys, values, IComparer) since it is only supported
// in System.Runtime contract from 4.20.0.0 and Test.Net depends on System.Runtime 4.0.10.0
// we workaround this by sorting only the keys and then lookup the values form the keys.
Array.Sort(keys, StringComparer.OrdinalIgnoreCase);
// create a list of null terminated "key=val" strings
StringBuilder stringBuff = new StringBuilder();
for (int i = 0; i < sd.Count; ++i)
{
stringBuff.Append(keys[i]);
stringBuff.Append('=');
stringBuff.Append(sd[keys[i]]);
stringBuff.Append('\0');
}
// an extra null at the end that indicates end of list will come from the string.
return stringBuff.ToString();
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace LessProject.DotLessIntegration
{
// Last command type sent to the macro recorder. Note that there are more commands
// recorded than is implied by this list. Commands in this list (other than
// LastMacroNone) are coalesced when multiples of the same command are received
// consecutively.
// This enum should be extended or replaced with your own command identifiers to enable
// Coalescing of commands.
public enum LastMacro
{
None,
Text,
DownArrowLine,
DownArrowLineSelection,
DownArrowPara,
DownArrowParaSelection,
UpArrowLine,
UpArrowLineSelection,
UpArrowPara,
UpArrowParaSelection,
LeftArrowChar,
LeftArrowCharSelection,
LeftArrowWord,
LeftArrowWordSelection,
RightArrowChar,
RightArrowCharSelection,
RightArrowWord,
RightArrowWordSelection,
DeleteChar,
DeleteWord,
BackspaceChar,
BackspaceWord
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")]
public enum MoveScope
{
Character = tom.tomConstants.tomCharacter,
Word = tom.tomConstants.tomWord,
Line = tom.tomConstants.tomLine,
Paragraph = tom.tomConstants.tomParagraph
}
/// <summary>
/// The VSMacroRecorder class implementation and the IVsMacroRecorder Interface definition
/// were included here in this seperate class because they were not included in the
/// interop assemblies shipped with Visual Studio 2005.
///
/// When implementing a macro recorder this class should be copied into your own name space
/// and not shared between different 3rd party packages.
/// </summary>
public class VSMacroRecorder
{
private IVsMacroRecorder m_VsMacroRecorder;
private LastMacro m_LastMacroRecorded;
private uint m_TimesPreviouslyRecorded;
Guid m_GuidEmitter;
public VSMacroRecorder(Guid emitter)
{
this.m_LastMacroRecorded = LastMacro.None;
this.m_GuidEmitter = emitter;
}
// Compiler generated destructor is fine
public void Reset()
{
m_LastMacroRecorded = LastMacro.None;
m_TimesPreviouslyRecorded = 0;
}
public void Stop()
{
Reset();
m_VsMacroRecorder = null;
}
public bool IsLastRecordedMacro(LastMacro macro)
{
return (macro == m_LastMacroRecorded && ObjectIsLastMacroEmitter()) ? true : false;
}
public bool IsRecording()
{
// If the property can not be retreived it is assumeed no macro is being recorded.
VSRECORDSTATE recordState = VSRECORDSTATE.VSRECORDSTATE_OFF;
// Retrieve the macro recording state.
IVsShell vsShell = (IVsShell)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SVsShell));
if (vsShell != null)
{
object var;
if (ErrorHandler.Succeeded(vsShell.GetProperty((int)__VSSPROPID.VSSPROPID_RecordState, out var)) && null != var)
{
recordState = (VSRECORDSTATE)var;
}
}
// If there is a change in the record state to OFF or ON we must either obtain
// or release the macro recorder.
if (recordState == VSRECORDSTATE.VSRECORDSTATE_ON && m_VsMacroRecorder == null)
{
// If this QueryService fails we no macro recording
m_VsMacroRecorder = (IVsMacroRecorder)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(IVsMacroRecorder));
}
else if (recordState == VSRECORDSTATE.VSRECORDSTATE_OFF && m_VsMacroRecorder != null)
{
// If the macro recording state has been switched off then we can release
// the service. Note that if the state has become paused we take no action.
Stop();
}
return (m_VsMacroRecorder != null);
}
public void RecordLine(string line)
{
m_VsMacroRecorder.RecordLine(line, ref m_GuidEmitter);
Reset();
}
public bool RecordBatchedLine(LastMacro macroRecorded, string line)
{
if (null == line)
line = "";
return RecordBatchedLine(macroRecorded, line, 0);
}
public bool RecordBatchedLine(LastMacro macroRecorded, string line, int maxLineLength)
{
if (null == line)
line = "";
if (maxLineLength > 0 && line.Length >= maxLineLength)
{
// Reset the state after recording the line, so it will not be appended to further
RecordLine(line);
// Notify the caller that the this line will not be appended to further
return true;
}
if(IsLastRecordedMacro(macroRecorded))
{
m_VsMacroRecorder.ReplaceLine(line, ref m_GuidEmitter);
// m_LastMacroRecorded can stay the same
++m_TimesPreviouslyRecorded;
}
else
{
m_VsMacroRecorder.RecordLine(line, ref m_GuidEmitter);
m_LastMacroRecorded = macroRecorded;
m_TimesPreviouslyRecorded = 1;
}
return false;
}
public uint GetTimesPreviouslyRecorded(LastMacro macro)
{
return IsLastRecordedMacro(macro) ? m_TimesPreviouslyRecorded : 0;
}
// This function determines if the last line sent to the macro recorder was
// sent from this emitter. Note it is not valid to call this function if
// macro recording is switched off.
private bool ObjectIsLastMacroEmitter()
{
Guid guid;
m_VsMacroRecorder.GetLastEmitterId(out guid);
return guid.Equals(m_GuidEmitter);
}
}
#region "IVsMacro Interfaces"
[StructLayout(LayoutKind.Sequential, Pack = 4), ComConversionLoss]
internal struct _VSPROPSHEETPAGE
{
public uint dwSize;
public uint dwFlags;
[ComAliasName("vbapkg.ULONG_PTR")]
public uint hInstance;
public ushort wTemplateId;
public uint dwTemplateSize;
[ComConversionLoss]
public IntPtr pTemplate;
[ComAliasName("vbapkg.ULONG_PTR")]
public uint pfnDlgProc;
[ComAliasName("vbapkg.LONG_PTR")]
public int lParam;
[ComAliasName("vbapkg.ULONG_PTR")]
public uint pfnCallback;
[ComConversionLoss]
public IntPtr pcRefParent;
public uint dwReserved;
[ComConversionLoss, ComAliasName("vbapkg.wireHWND")]
public IntPtr hwndDlg;
}
internal enum _VSRECORDMODE
{
// Fields
VSRECORDMODE_ABSOLUTE = 1,
VSRECORDMODE_RELATIVE = 2
}
[ComImport, ComConversionLoss, InterfaceType(1), Guid("55ED27C1-4CE7-11D2-890F-0060083196C6")]
internal interface IVsMacros
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetMacroCommands([Out] IntPtr ppsaMacroCanonicalNames);
}
[ComImport, InterfaceType(1), Guid("04BBF6A5-4697-11D2-890E-0060083196C6")]
internal interface IVsMacroRecorder
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void RecordStart([In, MarshalAs(UnmanagedType.LPWStr)] string pszReserved);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void RecordEnd();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void RecordLine([In, MarshalAs(UnmanagedType.LPWStr)] string pszLine, [In] ref Guid rguidEmitter);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetLastEmitterId([Out] out Guid pguidEmitter);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ReplaceLine([In, MarshalAs(UnmanagedType.LPWStr)] string pszLine, [In] ref Guid rguidEmitter);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void RecordCancel();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void RecordPause();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void RecordResume();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetCodeEmittedFlag([In] int fFlag);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetCodeEmittedFlag([Out] out int pfFlag);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetKeyWord([In] uint uiKeyWordId, [Out, MarshalAs(UnmanagedType.BStr)] out string pbstrKeyWord);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void IsValidIdentifier([In, MarshalAs(UnmanagedType.LPWStr)] string pszIdentifier);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetRecordMode([Out] out _VSRECORDMODE peRecordMode);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetRecordMode([In] _VSRECORDMODE eRecordMode);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetStringLiteralExpression([In, MarshalAs(UnmanagedType.LPWStr)] string pszStringValue, [Out, MarshalAs(UnmanagedType.BStr)] out string pbstrLiteralExpression);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ExecuteLine([In, MarshalAs(UnmanagedType.LPWStr)] string pszLine);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void AddTypeLibRef([In] ref Guid guidTypeLib, [In] uint uVerMaj, [In] uint uVerMin);
}
#endregion
}
| |
// 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 gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedBatchJobServiceClientTest
{
[Category("Autogenerated")][Test]
public void MutateBatchJobRequestObject()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
MutateBatchJobRequest request = new MutateBatchJobRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new BatchJobOperation(),
};
MutateBatchJobResponse expectedResponse = new MutateBatchJobResponse
{
Result = new MutateBatchJobResult(),
};
mockGrpcClient.Setup(x => x.MutateBatchJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
MutateBatchJobResponse response = client.MutateBatchJob(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateBatchJobRequestObjectAsync()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
MutateBatchJobRequest request = new MutateBatchJobRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new BatchJobOperation(),
};
MutateBatchJobResponse expectedResponse = new MutateBatchJobResponse
{
Result = new MutateBatchJobResult(),
};
mockGrpcClient.Setup(x => x.MutateBatchJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateBatchJobResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
MutateBatchJobResponse responseCallSettings = await client.MutateBatchJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateBatchJobResponse responseCancellationToken = await client.MutateBatchJobAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateBatchJob()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
MutateBatchJobRequest request = new MutateBatchJobRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new BatchJobOperation(),
};
MutateBatchJobResponse expectedResponse = new MutateBatchJobResponse
{
Result = new MutateBatchJobResult(),
};
mockGrpcClient.Setup(x => x.MutateBatchJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
MutateBatchJobResponse response = client.MutateBatchJob(request.CustomerId, request.Operation);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateBatchJobAsync()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
MutateBatchJobRequest request = new MutateBatchJobRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new BatchJobOperation(),
};
MutateBatchJobResponse expectedResponse = new MutateBatchJobResponse
{
Result = new MutateBatchJobResult(),
};
mockGrpcClient.Setup(x => x.MutateBatchJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateBatchJobResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
MutateBatchJobResponse responseCallSettings = await client.MutateBatchJobAsync(request.CustomerId, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateBatchJobResponse responseCancellationToken = await client.MutateBatchJobAsync(request.CustomerId, request.Operation, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetBatchJobRequestObject()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchJobRequest request = new GetBatchJobRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
};
gagvr::BatchJob expectedResponse = new gagvr::BatchJob
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
Metadata = new gagvr::BatchJob.Types.BatchJobMetadata(),
Status = gagve::BatchJobStatusEnum.Types.BatchJobStatus.Done,
Id = -6774108720365892680L,
NextAddSequenceToken = "next_add_sequence_token93fee49d",
LongRunningOperation = "long_running_operation0897bd41",
};
mockGrpcClient.Setup(x => x.GetBatchJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
gagvr::BatchJob response = client.GetBatchJob(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetBatchJobRequestObjectAsync()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchJobRequest request = new GetBatchJobRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
};
gagvr::BatchJob expectedResponse = new gagvr::BatchJob
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
Metadata = new gagvr::BatchJob.Types.BatchJobMetadata(),
Status = gagve::BatchJobStatusEnum.Types.BatchJobStatus.Done,
Id = -6774108720365892680L,
NextAddSequenceToken = "next_add_sequence_token93fee49d",
LongRunningOperation = "long_running_operation0897bd41",
};
mockGrpcClient.Setup(x => x.GetBatchJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BatchJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
gagvr::BatchJob responseCallSettings = await client.GetBatchJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::BatchJob responseCancellationToken = await client.GetBatchJobAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetBatchJob()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchJobRequest request = new GetBatchJobRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
};
gagvr::BatchJob expectedResponse = new gagvr::BatchJob
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
Metadata = new gagvr::BatchJob.Types.BatchJobMetadata(),
Status = gagve::BatchJobStatusEnum.Types.BatchJobStatus.Done,
Id = -6774108720365892680L,
NextAddSequenceToken = "next_add_sequence_token93fee49d",
LongRunningOperation = "long_running_operation0897bd41",
};
mockGrpcClient.Setup(x => x.GetBatchJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
gagvr::BatchJob response = client.GetBatchJob(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetBatchJobAsync()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchJobRequest request = new GetBatchJobRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
};
gagvr::BatchJob expectedResponse = new gagvr::BatchJob
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
Metadata = new gagvr::BatchJob.Types.BatchJobMetadata(),
Status = gagve::BatchJobStatusEnum.Types.BatchJobStatus.Done,
Id = -6774108720365892680L,
NextAddSequenceToken = "next_add_sequence_token93fee49d",
LongRunningOperation = "long_running_operation0897bd41",
};
mockGrpcClient.Setup(x => x.GetBatchJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BatchJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
gagvr::BatchJob responseCallSettings = await client.GetBatchJobAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::BatchJob responseCancellationToken = await client.GetBatchJobAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetBatchJobResourceNames()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchJobRequest request = new GetBatchJobRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
};
gagvr::BatchJob expectedResponse = new gagvr::BatchJob
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
Metadata = new gagvr::BatchJob.Types.BatchJobMetadata(),
Status = gagve::BatchJobStatusEnum.Types.BatchJobStatus.Done,
Id = -6774108720365892680L,
NextAddSequenceToken = "next_add_sequence_token93fee49d",
LongRunningOperation = "long_running_operation0897bd41",
};
mockGrpcClient.Setup(x => x.GetBatchJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
gagvr::BatchJob response = client.GetBatchJob(request.ResourceNameAsBatchJobName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetBatchJobResourceNamesAsync()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchJobRequest request = new GetBatchJobRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
};
gagvr::BatchJob expectedResponse = new gagvr::BatchJob
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
Metadata = new gagvr::BatchJob.Types.BatchJobMetadata(),
Status = gagve::BatchJobStatusEnum.Types.BatchJobStatus.Done,
Id = -6774108720365892680L,
NextAddSequenceToken = "next_add_sequence_token93fee49d",
LongRunningOperation = "long_running_operation0897bd41",
};
mockGrpcClient.Setup(x => x.GetBatchJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::BatchJob>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
gagvr::BatchJob responseCallSettings = await client.GetBatchJobAsync(request.ResourceNameAsBatchJobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::BatchJob responseCancellationToken = await client.GetBatchJobAsync(request.ResourceNameAsBatchJobName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void AddBatchJobOperationsRequestObject()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
AddBatchJobOperationsRequest request = new AddBatchJobOperationsRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
SequenceToken = "sequence_tokene6b46f6e",
MutateOperations =
{
new MutateOperation(),
},
};
AddBatchJobOperationsResponse expectedResponse = new AddBatchJobOperationsResponse
{
TotalOperations = -8188520186954789005L,
NextSequenceToken = "next_sequence_token160dabc7",
};
mockGrpcClient.Setup(x => x.AddBatchJobOperations(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
AddBatchJobOperationsResponse response = client.AddBatchJobOperations(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task AddBatchJobOperationsRequestObjectAsync()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
AddBatchJobOperationsRequest request = new AddBatchJobOperationsRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
SequenceToken = "sequence_tokene6b46f6e",
MutateOperations =
{
new MutateOperation(),
},
};
AddBatchJobOperationsResponse expectedResponse = new AddBatchJobOperationsResponse
{
TotalOperations = -8188520186954789005L,
NextSequenceToken = "next_sequence_token160dabc7",
};
mockGrpcClient.Setup(x => x.AddBatchJobOperationsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AddBatchJobOperationsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
AddBatchJobOperationsResponse responseCallSettings = await client.AddBatchJobOperationsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
AddBatchJobOperationsResponse responseCancellationToken = await client.AddBatchJobOperationsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void AddBatchJobOperations1()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
AddBatchJobOperationsRequest request = new AddBatchJobOperationsRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
SequenceToken = "sequence_tokene6b46f6e",
MutateOperations =
{
new MutateOperation(),
},
};
AddBatchJobOperationsResponse expectedResponse = new AddBatchJobOperationsResponse
{
TotalOperations = -8188520186954789005L,
NextSequenceToken = "next_sequence_token160dabc7",
};
mockGrpcClient.Setup(x => x.AddBatchJobOperations(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
AddBatchJobOperationsResponse response = client.AddBatchJobOperations(request.ResourceName, request.SequenceToken, request.MutateOperations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task AddBatchJobOperations1Async()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
AddBatchJobOperationsRequest request = new AddBatchJobOperationsRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
SequenceToken = "sequence_tokene6b46f6e",
MutateOperations =
{
new MutateOperation(),
},
};
AddBatchJobOperationsResponse expectedResponse = new AddBatchJobOperationsResponse
{
TotalOperations = -8188520186954789005L,
NextSequenceToken = "next_sequence_token160dabc7",
};
mockGrpcClient.Setup(x => x.AddBatchJobOperationsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AddBatchJobOperationsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
AddBatchJobOperationsResponse responseCallSettings = await client.AddBatchJobOperationsAsync(request.ResourceName, request.SequenceToken, request.MutateOperations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
AddBatchJobOperationsResponse responseCancellationToken = await client.AddBatchJobOperationsAsync(request.ResourceName, request.SequenceToken, request.MutateOperations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void AddBatchJobOperations1ResourceNames()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
AddBatchJobOperationsRequest request = new AddBatchJobOperationsRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
SequenceToken = "sequence_tokene6b46f6e",
MutateOperations =
{
new MutateOperation(),
},
};
AddBatchJobOperationsResponse expectedResponse = new AddBatchJobOperationsResponse
{
TotalOperations = -8188520186954789005L,
NextSequenceToken = "next_sequence_token160dabc7",
};
mockGrpcClient.Setup(x => x.AddBatchJobOperations(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
AddBatchJobOperationsResponse response = client.AddBatchJobOperations(request.ResourceNameAsBatchJobName, request.SequenceToken, request.MutateOperations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task AddBatchJobOperations1ResourceNamesAsync()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
AddBatchJobOperationsRequest request = new AddBatchJobOperationsRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
SequenceToken = "sequence_tokene6b46f6e",
MutateOperations =
{
new MutateOperation(),
},
};
AddBatchJobOperationsResponse expectedResponse = new AddBatchJobOperationsResponse
{
TotalOperations = -8188520186954789005L,
NextSequenceToken = "next_sequence_token160dabc7",
};
mockGrpcClient.Setup(x => x.AddBatchJobOperationsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AddBatchJobOperationsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
AddBatchJobOperationsResponse responseCallSettings = await client.AddBatchJobOperationsAsync(request.ResourceNameAsBatchJobName, request.SequenceToken, request.MutateOperations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
AddBatchJobOperationsResponse responseCancellationToken = await client.AddBatchJobOperationsAsync(request.ResourceNameAsBatchJobName, request.SequenceToken, request.MutateOperations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void AddBatchJobOperations2()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
AddBatchJobOperationsRequest request = new AddBatchJobOperationsRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
MutateOperations =
{
new MutateOperation(),
},
};
AddBatchJobOperationsResponse expectedResponse = new AddBatchJobOperationsResponse
{
TotalOperations = -8188520186954789005L,
NextSequenceToken = "next_sequence_token160dabc7",
};
mockGrpcClient.Setup(x => x.AddBatchJobOperations(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
AddBatchJobOperationsResponse response = client.AddBatchJobOperations(request.ResourceName, request.MutateOperations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task AddBatchJobOperations2Async()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
AddBatchJobOperationsRequest request = new AddBatchJobOperationsRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
MutateOperations =
{
new MutateOperation(),
},
};
AddBatchJobOperationsResponse expectedResponse = new AddBatchJobOperationsResponse
{
TotalOperations = -8188520186954789005L,
NextSequenceToken = "next_sequence_token160dabc7",
};
mockGrpcClient.Setup(x => x.AddBatchJobOperationsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AddBatchJobOperationsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
AddBatchJobOperationsResponse responseCallSettings = await client.AddBatchJobOperationsAsync(request.ResourceName, request.MutateOperations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
AddBatchJobOperationsResponse responseCancellationToken = await client.AddBatchJobOperationsAsync(request.ResourceName, request.MutateOperations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void AddBatchJobOperations2ResourceNames()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
AddBatchJobOperationsRequest request = new AddBatchJobOperationsRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
MutateOperations =
{
new MutateOperation(),
},
};
AddBatchJobOperationsResponse expectedResponse = new AddBatchJobOperationsResponse
{
TotalOperations = -8188520186954789005L,
NextSequenceToken = "next_sequence_token160dabc7",
};
mockGrpcClient.Setup(x => x.AddBatchJobOperations(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
AddBatchJobOperationsResponse response = client.AddBatchJobOperations(request.ResourceNameAsBatchJobName, request.MutateOperations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task AddBatchJobOperations2ResourceNamesAsync()
{
moq::Mock<BatchJobService.BatchJobServiceClient> mockGrpcClient = new moq::Mock<BatchJobService.BatchJobServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
AddBatchJobOperationsRequest request = new AddBatchJobOperationsRequest
{
ResourceNameAsBatchJobName = gagvr::BatchJobName.FromCustomerBatchJob("[CUSTOMER_ID]", "[BATCH_JOB_ID]"),
MutateOperations =
{
new MutateOperation(),
},
};
AddBatchJobOperationsResponse expectedResponse = new AddBatchJobOperationsResponse
{
TotalOperations = -8188520186954789005L,
NextSequenceToken = "next_sequence_token160dabc7",
};
mockGrpcClient.Setup(x => x.AddBatchJobOperationsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AddBatchJobOperationsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchJobServiceClient client = new BatchJobServiceClientImpl(mockGrpcClient.Object, null);
AddBatchJobOperationsResponse responseCallSettings = await client.AddBatchJobOperationsAsync(request.ResourceNameAsBatchJobName, request.MutateOperations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
AddBatchJobOperationsResponse responseCancellationToken = await client.AddBatchJobOperationsAsync(request.ResourceNameAsBatchJobName, request.MutateOperations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Text.RegularExpressions;
namespace GitVersion
{
public class SemanticVersion : IFormattable, IComparable<SemanticVersion>
{
private static SemanticVersion Empty = new SemanticVersion();
private static readonly Regex ParseSemVer = new Regex(
@"^(?<SemVer>(?<Major>\d+)(\.(?<Minor>\d+))(\.(?<Patch>\d+))?)(\.(?<FourthPart>\d+))?(-(?<Tag>[^\+]*))?(\+(?<BuildMetaData>.*))?$",
RegexOptions.Compiled);
public int Major;
public int Minor;
public int Patch;
public SemanticVersionPreReleaseTag PreReleaseTag;
public SemanticVersionBuildMetaData BuildMetaData;
public SemanticVersion(int major = 0, int minor = 0, int patch = 0)
{
Major = major;
Minor = minor;
Patch = patch;
PreReleaseTag = new SemanticVersionPreReleaseTag();
BuildMetaData = new SemanticVersionBuildMetaData();
}
public SemanticVersion(SemanticVersion semanticVersion)
{
Major = semanticVersion.Major;
Minor = semanticVersion.Minor;
Patch = semanticVersion.Patch;
PreReleaseTag = new SemanticVersionPreReleaseTag(semanticVersion.PreReleaseTag);
BuildMetaData = new SemanticVersionBuildMetaData(semanticVersion.BuildMetaData);
}
public bool Equals(SemanticVersion obj)
{
if (obj == null)
{
return false;
}
return Major == obj.Major &&
Minor == obj.Minor &&
Patch == obj.Patch &&
PreReleaseTag == obj.PreReleaseTag &&
BuildMetaData == obj.BuildMetaData;
}
public bool IsEmpty()
{
return Equals(Empty);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((SemanticVersion)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = Major;
hashCode = (hashCode * 397) ^ Minor;
hashCode = (hashCode * 397) ^ Patch;
hashCode = (hashCode * 397) ^ (PreReleaseTag != null ? PreReleaseTag.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (BuildMetaData != null ? BuildMetaData.GetHashCode() : 0);
return hashCode;
}
}
public static bool operator ==(SemanticVersion v1, SemanticVersion v2)
{
if (ReferenceEquals(v1, null))
{
return ReferenceEquals(v2, null);
}
return v1.Equals(v2);
}
public static bool operator !=(SemanticVersion v1, SemanticVersion v2)
{
return !(v1 == v2);
}
public static bool operator >(SemanticVersion v1, SemanticVersion v2)
{
if (v1 == null)
throw new ArgumentNullException(nameof(v1));
if (v2 == null)
throw new ArgumentNullException(nameof(v2));
return v1.CompareTo(v2) > 0;
}
public static bool operator >=(SemanticVersion v1, SemanticVersion v2)
{
if (v1 == null)
throw new ArgumentNullException(nameof(v1));
if (v2 == null)
throw new ArgumentNullException(nameof(v2));
return v1.CompareTo(v2) >= 0;
}
public static bool operator <=(SemanticVersion v1, SemanticVersion v2)
{
if (v1 == null)
throw new ArgumentNullException(nameof(v1));
if (v2 == null)
throw new ArgumentNullException(nameof(v2));
return v1.CompareTo(v2) <= 0;
}
public static bool operator <(SemanticVersion v1, SemanticVersion v2)
{
if (v1 == null)
throw new ArgumentNullException(nameof(v1));
if (v2 == null)
throw new ArgumentNullException(nameof(v2));
return v1.CompareTo(v2) < 0;
}
public static SemanticVersion Parse(string version, string tagPrefixRegex)
{
if (!TryParse(version, tagPrefixRegex, out var semanticVersion))
throw new WarningException($"Failed to parse {version} into a Semantic Version");
return semanticVersion;
}
public static bool TryParse(string version, string tagPrefixRegex, out SemanticVersion semanticVersion)
{
var match = Regex.Match(version, $"^({tagPrefixRegex})?(?<version>.*)$");
if (!match.Success)
{
semanticVersion = null;
return false;
}
version = match.Groups["version"].Value;
var parsed = ParseSemVer.Match(version);
if (!parsed.Success)
{
semanticVersion = null;
return false;
}
var semanticVersionBuildMetaData = SemanticVersionBuildMetaData.Parse(parsed.Groups["BuildMetaData"].Value);
var fourthPart = parsed.Groups["FourthPart"];
if (fourthPart.Success && semanticVersionBuildMetaData.CommitsSinceTag == null)
{
semanticVersionBuildMetaData.CommitsSinceTag = int.Parse(fourthPart.Value);
}
semanticVersion = new SemanticVersion
{
Major = int.Parse(parsed.Groups["Major"].Value),
Minor = parsed.Groups["Minor"].Success ? int.Parse(parsed.Groups["Minor"].Value) : 0,
Patch = parsed.Groups["Patch"].Success ? int.Parse(parsed.Groups["Patch"].Value) : 0,
PreReleaseTag = SemanticVersionPreReleaseTag.Parse(parsed.Groups["Tag"].Value),
BuildMetaData = semanticVersionBuildMetaData
};
return true;
}
public int CompareTo(SemanticVersion value)
{
return CompareTo(value, true);
}
public int CompareTo(SemanticVersion value, bool includePrerelease)
{
if (value == null)
{
return 1;
}
if (Major != value.Major)
{
if (Major > value.Major)
{
return 1;
}
return -1;
}
if (Minor != value.Minor)
{
if (Minor > value.Minor)
{
return 1;
}
return -1;
}
if (Patch != value.Patch)
{
if (Patch > value.Patch)
{
return 1;
}
return -1;
}
if (includePrerelease && PreReleaseTag != value.PreReleaseTag)
{
if (PreReleaseTag > value.PreReleaseTag)
{
return 1;
}
return -1;
}
return 0;
}
public override string ToString()
{
return ToString(null);
}
/// <summary>
/// <para>s - Default SemVer [1.2.3-beta.4+5]</para>
/// <para>f - Full SemVer [1.2.3-beta.4+5]</para>
/// <para>i - Informational SemVer [1.2.3-beta.4+5.Branch.master.BranchType.Master.Sha.000000]</para>
/// <para>j - Just the SemVer part [1.2.3]</para>
/// <para>t - SemVer with the tag [1.2.3-beta.4]</para>
/// <para>l - Legacy SemVer tag for systems which do not support SemVer 2.0 properly [1.2.3-beta4]</para>
/// <para>lp - Legacy SemVer tag for systems which do not support SemVer 2.0 properly (padded) [1.2.3-beta0004]</para>
/// </summary>
public string ToString(string format, IFormatProvider formatProvider = null)
{
if (string.IsNullOrEmpty(format))
format = "s";
if (formatProvider != null)
{
if (formatProvider.GetFormat(GetType()) is ICustomFormatter formatter)
return formatter.Format(format, this, formatProvider);
}
// Check for lp first because the param can vary
format = format.ToLower();
if (format.StartsWith("lp", StringComparison.Ordinal))
{
// handle the padding
return PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag.ToString(format)}" : ToString("j");
}
switch (format)
{
case "j":
return $"{Major}.{Minor}.{Patch}";
case "s":
return PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag}" : ToString("j");
case "t":
return PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag.ToString("t")}" : ToString("j");
case "l":
return PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag.ToString("l")}" : ToString("j");
case "f":
{
var buildMetadata = BuildMetaData.ToString();
return !string.IsNullOrEmpty(buildMetadata) ? $"{ToString("s")}+{buildMetadata}" : ToString("s");
}
case "i":
{
var buildMetadata = BuildMetaData.ToString("f");
return !string.IsNullOrEmpty(buildMetadata) ? $"{ToString("s")}+{buildMetadata}" : ToString("s");
}
default:
throw new ArgumentException($"Unrecognised format '{format}'", nameof(format));
}
}
public SemanticVersion IncrementVersion(VersionField incrementStrategy)
{
var incremented = new SemanticVersion(this);
if (!incremented.PreReleaseTag.HasTag())
{
switch (incrementStrategy)
{
case VersionField.None:
break;
case VersionField.Major:
incremented.Major++;
incremented.Minor = 0;
incremented.Patch = 0;
break;
case VersionField.Minor:
incremented.Minor++;
incremented.Patch = 0;
break;
case VersionField.Patch:
incremented.Patch++;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
else
{
if (incremented.PreReleaseTag.Number != null)
{
incremented.PreReleaseTag.Number = incremented.PreReleaseTag.Number;
incremented.PreReleaseTag.Number++;
}
}
return incremented;
}
}
public enum VersionField
{
None,
Patch,
Minor,
Major
}
}
| |
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 Forum.WebApi.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 Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using System.IO;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Analyzer = Lucene.Net.Analysis.Analyzer;
using BytesRef = Lucene.Net.Util.BytesRef;
using CachingTokenFilter = Lucene.Net.Analysis.CachingTokenFilter;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using IOUtils = Lucene.Net.Util.IOUtils;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
using MockTokenFilter = Lucene.Net.Analysis.MockTokenFilter;
using MockTokenizer = Lucene.Net.Analysis.MockTokenizer;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using StringField = StringField;
using TextField = TextField;
using TokenStream = Lucene.Net.Analysis.TokenStream;
/// <summary>
/// tests for writing term vectors </summary>
[TestFixture]
public class TestTermVectorsWriter : LuceneTestCase
{
// LUCENE-1442
[Test]
public virtual void TestDoubleOffsetCounting()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document doc = new Document();
FieldType customType = new FieldType(StringField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd", customType);
doc.Add(f);
doc.Add(f);
Field f2 = NewField("field", "", customType);
doc.Add(f2);
doc.Add(f);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
Terms vector = r.GetTermVectors(0).GetTerms("field");
Assert.IsNotNull(vector);
TermsEnum termsEnum = vector.GetEnumerator();
Assert.IsTrue(termsEnum.MoveNext());
Assert.AreEqual("", termsEnum.Term.Utf8ToString());
// Token "" occurred once
Assert.AreEqual(1, termsEnum.TotalTermFreq);
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(8, dpEnum.StartOffset);
Assert.AreEqual(8, dpEnum.EndOffset);
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
// Token "abcd" occurred three times
Assert.IsTrue(termsEnum.MoveNext());
Assert.AreEqual(new BytesRef("abcd"), termsEnum.Term);
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.AreEqual(3, termsEnum.TotalTermFreq);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset);
Assert.AreEqual(4, dpEnum.EndOffset);
dpEnum.NextPosition();
Assert.AreEqual(4, dpEnum.StartOffset);
Assert.AreEqual(8, dpEnum.EndOffset);
dpEnum.NextPosition();
Assert.AreEqual(8, dpEnum.StartOffset);
Assert.AreEqual(12, dpEnum.EndOffset);
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
Assert.IsFalse(termsEnum.MoveNext());
r.Dispose();
dir.Dispose();
}
// LUCENE-1442
[Test]
public virtual void TestDoubleOffsetCounting2()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd", customType);
doc.Add(f);
doc.Add(f);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator();
Assert.IsTrue(termsEnum.MoveNext());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(2, termsEnum.TotalTermFreq);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset);
Assert.AreEqual(4, dpEnum.EndOffset);
dpEnum.NextPosition();
Assert.AreEqual(5, dpEnum.StartOffset);
Assert.AreEqual(9, dpEnum.EndOffset);
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionCharAnalyzer()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd ", customType);
doc.Add(f);
doc.Add(f);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator();
Assert.IsTrue(termsEnum.MoveNext());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(2, termsEnum.TotalTermFreq);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset);
Assert.AreEqual(4, dpEnum.EndOffset);
dpEnum.NextPosition();
Assert.AreEqual(8, dpEnum.StartOffset);
Assert.AreEqual(12, dpEnum.EndOffset);
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionWithCachingTokenFilter()
{
Directory dir = NewDirectory();
Analyzer analyzer = new MockAnalyzer(Random);
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
Document doc = new Document();
IOException priorException = null;
TokenStream stream = analyzer.GetTokenStream("field", new StringReader("abcd "));
try
{
stream.Reset(); // TODO: weird to reset before wrapping with CachingTokenFilter... correct?
TokenStream cachedStream = new CachingTokenFilter(stream);
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = new Field("field", cachedStream, customType);
doc.Add(f);
doc.Add(f);
w.AddDocument(doc);
}
catch (IOException e)
{
priorException = e;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorException, stream);
}
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator();
Assert.IsTrue(termsEnum.MoveNext());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(2, termsEnum.TotalTermFreq);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset);
Assert.AreEqual(4, dpEnum.EndOffset);
dpEnum.NextPosition();
Assert.AreEqual(8, dpEnum.StartOffset);
Assert.AreEqual(12, dpEnum.EndOffset);
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionStopFilter()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET)));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd the", customType);
doc.Add(f);
doc.Add(f);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator();
Assert.IsTrue(termsEnum.MoveNext());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(2, termsEnum.TotalTermFreq);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset);
Assert.AreEqual(4, dpEnum.EndOffset);
dpEnum.NextPosition();
Assert.AreEqual(9, dpEnum.StartOffset);
Assert.AreEqual(13, dpEnum.EndOffset);
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionStandard()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd the ", customType);
Field f2 = NewField("field", "crunch man", customType);
doc.Add(f);
doc.Add(f2);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator();
Assert.IsTrue(termsEnum.MoveNext());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset);
Assert.AreEqual(4, dpEnum.EndOffset);
Assert.IsTrue(termsEnum.MoveNext());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(11, dpEnum.StartOffset);
Assert.AreEqual(17, dpEnum.EndOffset);
Assert.IsTrue(termsEnum.MoveNext());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(18, dpEnum.StartOffset);
Assert.AreEqual(21, dpEnum.EndOffset);
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionStandardEmptyField()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "", customType);
Field f2 = NewField("field", "crunch man", customType);
doc.Add(f);
doc.Add(f2);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator();
Assert.IsTrue(termsEnum.MoveNext());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(1, (int)termsEnum.TotalTermFreq);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(1, dpEnum.StartOffset);
Assert.AreEqual(7, dpEnum.EndOffset);
Assert.IsTrue(termsEnum.MoveNext());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(8, dpEnum.StartOffset);
Assert.AreEqual(11, dpEnum.EndOffset);
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionStandardEmptyField2()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd", customType);
doc.Add(f);
doc.Add(NewField("field", "", customType));
Field f2 = NewField("field", "crunch", customType);
doc.Add(f2);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator();
Assert.IsTrue(termsEnum.MoveNext());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(1, (int)termsEnum.TotalTermFreq);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset);
Assert.AreEqual(4, dpEnum.EndOffset);
Assert.IsTrue(termsEnum.MoveNext());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(6, dpEnum.StartOffset);
Assert.AreEqual(12, dpEnum.EndOffset);
r.Dispose();
dir.Dispose();
}
// LUCENE-1168
[Test]
public virtual void TestTermVectorCorruption()
{
// LUCENENET specific - log the current locking strategy used and HResult values
// for assistance troubleshooting problems on Linux/macOS
LogNativeFSFactoryDebugInfo();
Directory dir = NewDirectory();
for (int iter = 0; iter < 2; iter++)
{
IndexWriter writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy()));
Document document = new Document();
FieldType customType = new FieldType();
customType.IsStored = true;
Field storedField = NewField("stored", "stored", customType);
document.Add(storedField);
writer.AddDocument(document);
writer.AddDocument(document);
document = new Document();
document.Add(storedField);
FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorPositions = true;
customType2.StoreTermVectorOffsets = true;
Field termVectorField = NewField("termVector", "termVector", customType2);
document.Add(termVectorField);
writer.AddDocument(document);
writer.ForceMerge(1);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
for (int i = 0; i < reader.NumDocs; i++)
{
reader.Document(i);
reader.GetTermVectors(i);
}
reader.Dispose();
writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy()));
Directory[] indexDirs = new Directory[] { new MockDirectoryWrapper(Random, new RAMDirectory(dir, NewIOContext(Random))) };
writer.AddIndexes(indexDirs);
writer.ForceMerge(1);
writer.Dispose();
}
dir.Dispose();
}
// LUCENE-1168
[Test]
public virtual void TestTermVectorCorruption2()
{
Directory dir = NewDirectory();
for (int iter = 0; iter < 2; iter++)
{
IndexWriter writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy()));
Document document = new Document();
FieldType customType = new FieldType();
customType.IsStored = true;
Field storedField = NewField("stored", "stored", customType);
document.Add(storedField);
writer.AddDocument(document);
writer.AddDocument(document);
document = new Document();
document.Add(storedField);
FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorPositions = true;
customType2.StoreTermVectorOffsets = true;
Field termVectorField = NewField("termVector", "termVector", customType2);
document.Add(termVectorField);
writer.AddDocument(document);
writer.ForceMerge(1);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
Assert.IsNull(reader.GetTermVectors(0));
Assert.IsNull(reader.GetTermVectors(1));
Assert.IsNotNull(reader.GetTermVectors(2));
reader.Dispose();
}
dir.Dispose();
}
// LUCENE-1168
[Test]
public virtual void TestTermVectorCorruption3()
{
Directory dir = NewDirectory();
IndexWriter writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy()));
Document document = new Document();
FieldType customType = new FieldType();
customType.IsStored = true;
Field storedField = NewField("stored", "stored", customType);
document.Add(storedField);
FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorPositions = true;
customType2.StoreTermVectorOffsets = true;
Field termVectorField = NewField("termVector", "termVector", customType2);
document.Add(termVectorField);
for (int i = 0; i < 10; i++)
{
writer.AddDocument(document);
}
writer.Dispose();
writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy()));
for (int i = 0; i < 6; i++)
{
writer.AddDocument(document);
}
writer.ForceMerge(1);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
for (int i = 0; i < 10; i++)
{
reader.GetTermVectors(i);
reader.Document(i);
}
reader.Dispose();
dir.Dispose();
}
// LUCENE-1008
[Test]
public virtual void TestNoTermVectorAfterTermVector()
{
Directory dir = NewDirectory();
IndexWriter iw = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document document = new Document();
FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorPositions = true;
customType2.StoreTermVectorOffsets = true;
document.Add(NewField("tvtest", "a b c", customType2));
iw.AddDocument(document);
document = new Document();
document.Add(NewTextField("tvtest", "x y z", Field.Store.NO));
iw.AddDocument(document);
// Make first segment
iw.Commit();
FieldType customType = new FieldType(StringField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
document.Add(NewField("tvtest", "a b c", customType));
iw.AddDocument(document);
// Make 2nd segment
iw.Commit();
iw.ForceMerge(1);
iw.Dispose();
dir.Dispose();
}
// LUCENE-1010
[Test]
public virtual void TestNoTermVectorAfterTermVectorMerge()
{
Directory dir = NewDirectory();
IndexWriter iw = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document document = new Document();
FieldType customType = new FieldType(StringField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
document.Add(NewField("tvtest", "a b c", customType));
iw.AddDocument(document);
iw.Commit();
document = new Document();
document.Add(NewTextField("tvtest", "x y z", Field.Store.NO));
iw.AddDocument(document);
// Make first segment
iw.Commit();
iw.ForceMerge(1);
FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED);
customType2.StoreTermVectors = true;
document.Add(NewField("tvtest", "a b c", customType2));
iw.AddDocument(document);
// Make 2nd segment
iw.Commit();
iw.ForceMerge(1);
iw.Dispose();
dir.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System;
using System.Globalization;
using System.Diagnostics.SymbolStore;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security;
internal class DynamicILGenerator : ILGenerator
{
internal DynamicScope m_scope;
private int m_methodSigToken;
internal unsafe DynamicILGenerator(DynamicMethod method, byte[] methodSignature, int size)
: base(method, size)
{
m_scope = new DynamicScope();
m_methodSigToken = m_scope.GetTokenFor(methodSignature);
}
internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
{
dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
module,
m_methodBuilder.Name,
(byte[])m_scope[m_methodSigToken],
new DynamicResolver(this));
}
#if FEATURE_APPX
private bool ProfileAPICheck
{
get
{
return ((DynamicMethod)m_methodBuilder).ProfileAPICheck;
}
}
#endif // FEATURE_APPX
// *** ILGenerator api ***
public override LocalBuilder DeclareLocal(Type localType, bool pinned)
{
LocalBuilder localBuilder;
if (localType == null)
throw new ArgumentNullException(nameof(localType));
Contract.EndContractBlock();
RuntimeType rtType = localType as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
#if FEATURE_APPX
if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
#endif
localBuilder = new LocalBuilder(m_localCount, localType, m_methodBuilder);
// add the localType to local signature
m_localSignature.AddArgument(localType, pinned);
m_localCount++;
return localBuilder;
}
//
//
// Token resolution calls
//
//
public override void Emit(OpCode opcode, MethodInfo meth)
{
if (meth == null)
throw new ArgumentNullException(nameof(meth));
Contract.EndContractBlock();
int stackchange = 0;
int token = 0;
DynamicMethod dynMeth = meth as DynamicMethod;
if (dynMeth == null)
{
RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo;
if (rtMeth == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(meth));
RuntimeType declaringType = rtMeth.GetRuntimeType();
if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray))
token = GetTokenFor(rtMeth, declaringType);
else
token = GetTokenFor(rtMeth);
}
else
{
// rule out not allowed operations on DynamicMethods
if (opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn))
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOpCodeOnDynamicMethod"));
}
token = GetTokenFor(dynMeth);
}
EnsureCapacity(7);
InternalEmit(opcode);
if (opcode.StackBehaviourPush == StackBehaviour.Varpush
&& meth.ReturnType != typeof(void))
{
stackchange++;
}
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
stackchange -= meth.GetParametersNoCopy().Length;
}
// Pop the "this" parameter if the method is non-static,
// and the instruction is not newobj/ldtoken/ldftn.
if (!meth.IsStatic &&
!(opcode.Equals(OpCodes.Newobj) || opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn)))
{
stackchange--;
}
UpdateStackSize(opcode, stackchange);
PutInteger4(token);
}
public override void Emit(OpCode opcode, ConstructorInfo con)
{
if (con == null)
throw new ArgumentNullException(nameof(con));
Contract.EndContractBlock();
RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo;
if (rtConstructor == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(con));
RuntimeType declaringType = rtConstructor.GetRuntimeType();
int token;
if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray))
// need to sort out the stack size story
token = GetTokenFor(rtConstructor, declaringType);
else
token = GetTokenFor(rtConstructor);
EnsureCapacity(7);
InternalEmit(opcode);
// need to sort out the stack size story
UpdateStackSize(opcode, 1);
PutInteger4(token);
}
public override void Emit(OpCode opcode, Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
int token = GetTokenFor(rtType);
EnsureCapacity(7);
InternalEmit(opcode);
PutInteger4(token);
}
public override void Emit(OpCode opcode, FieldInfo field)
{
if (field == null)
throw new ArgumentNullException(nameof(field));
Contract.EndContractBlock();
RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo;
if (runtimeField == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(field));
int token;
if (field.DeclaringType == null)
token = GetTokenFor(runtimeField);
else
token = GetTokenFor(runtimeField, runtimeField.GetRuntimeType());
EnsureCapacity(7);
InternalEmit(opcode);
PutInteger4(token);
}
public override void Emit(OpCode opcode, String str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
Contract.EndContractBlock();
int tempVal = GetTokenForString(str);
EnsureCapacity(7);
InternalEmit(opcode);
PutInteger4(tempVal);
}
//
//
// Signature related calls (vararg, calli)
//
//
public override void EmitCalli(OpCode opcode,
CallingConventions callingConvention,
Type returnType,
Type[] parameterTypes,
Type[] optionalParameterTypes)
{
int stackchange = 0;
SignatureHelper sig;
if (optionalParameterTypes != null)
if ((callingConvention & CallingConventions.VarArgs) == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
sig = GetMemberRefSignature(callingConvention,
returnType,
parameterTypes,
optionalParameterTypes);
EnsureCapacity(7);
Emit(OpCodes.Calli);
// If there is a non-void return type, push one.
if (returnType != typeof(void))
stackchange++;
// Pop off arguments if any.
if (parameterTypes != null)
stackchange -= parameterTypes.Length;
// Pop off vararg arguments.
if (optionalParameterTypes != null)
stackchange -= optionalParameterTypes.Length;
// Pop the this parameter if the method has a this parameter.
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
stackchange--;
// Pop the native function pointer.
stackchange--;
UpdateStackSize(OpCodes.Calli, stackchange);
int token = GetTokenForSig(sig.GetSignature(true));
PutInteger4(token);
}
public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
{
if (methodInfo == null)
throw new ArgumentNullException(nameof(methodInfo));
if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode));
if (methodInfo.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));
if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));
Contract.EndContractBlock();
int tk;
int stackchange = 0;
tk = GetMemberRefToken(methodInfo, optionalParameterTypes);
EnsureCapacity(7);
InternalEmit(opcode);
// Push the return value if there is one.
if (methodInfo.ReturnType != typeof(void))
stackchange++;
// Pop the parameters.
stackchange -= methodInfo.GetParameterTypes().Length;
// Pop the this parameter if the method is non-static and the
// instruction is not newobj.
if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj)))
stackchange--;
// Pop the optional parameters off the stack.
if (optionalParameterTypes != null)
stackchange -= optionalParameterTypes.Length;
UpdateStackSize(opcode, stackchange);
PutInteger4(tk);
}
public override void Emit(OpCode opcode, SignatureHelper signature)
{
if (signature == null)
throw new ArgumentNullException(nameof(signature));
Contract.EndContractBlock();
int stackchange = 0;
EnsureCapacity(7);
InternalEmit(opcode);
// The only IL instruction that has VarPop behaviour, that takes a
// Signature token as a parameter is calli. Pop the parameters and
// the native function pointer. To be conservative, do not pop the
// this pointer since this information is not easily derived from
// SignatureHelper.
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
Debug.Assert(opcode.Equals(OpCodes.Calli),
"Unexpected opcode encountered for StackBehaviour VarPop.");
// Pop the arguments..
stackchange -= signature.ArgumentCount;
// Pop native function pointer off the stack.
stackchange--;
UpdateStackSize(opcode, stackchange);
}
int token = GetTokenForSig(signature.GetSignature(true)); ;
PutInteger4(token);
}
//
//
// Exception related generation
//
//
public override void BeginExceptFilterBlock()
{
// Begins an exception filter block. Emits a branch instruction to the end of the current exception block.
if (CurrExcStackCount == 0)
throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
__ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];
Label endLabel = current.GetEndLabel();
Emit(OpCodes.Leave, endLabel);
UpdateStackSize(OpCodes.Nop, 1);
current.MarkFilterAddr(ILOffset);
}
public override void BeginCatchBlock(Type exceptionType)
{
if (CurrExcStackCount == 0)
throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
Contract.EndContractBlock();
__ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];
RuntimeType rtType = exceptionType as RuntimeType;
if (current.GetCurrentState() == __ExceptionInfo.State_Filter)
{
if (exceptionType != null)
{
throw new ArgumentException(Environment.GetResourceString("Argument_ShouldNotSpecifyExceptionType"));
}
this.Emit(OpCodes.Endfilter);
current.MarkCatchAddr(ILOffset, null);
}
else
{
// execute this branch if previous clause is Catch or Fault
if (exceptionType == null)
throw new ArgumentNullException(nameof(exceptionType));
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
Label endLabel = current.GetEndLabel();
this.Emit(OpCodes.Leave, endLabel);
// if this is a catch block the exception will be pushed on the stack and we need to update the stack info
UpdateStackSize(OpCodes.Nop, 1);
current.MarkCatchAddr(ILOffset, exceptionType);
// this is relying on too much implementation details of the base and so it's highly breaking
// Need to have a more integrated story for exceptions
current.m_filterAddr[current.m_currentCatch - 1] = GetTokenFor(rtType);
}
}
//
//
// debugger related calls.
//
//
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void UsingNamespace(String ns)
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void MarkSequencePoint(ISymbolDocumentWriter document,
int startLine,
int startColumn,
int endLine,
int endColumn)
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
public override void BeginScope()
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
public override void EndScope()
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes)
{
Type[] parameterTypes;
if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
RuntimeMethodInfo rtMeth = methodInfo as RuntimeMethodInfo;
DynamicMethod dm = methodInfo as DynamicMethod;
if (rtMeth == null && dm == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(methodInfo));
ParameterInfo[] paramInfo = methodInfo.GetParametersNoCopy();
if (paramInfo != null && paramInfo.Length != 0)
{
parameterTypes = new Type[paramInfo.Length];
for (int i = 0; i < paramInfo.Length; i++)
parameterTypes[i] = paramInfo[i].ParameterType;
}
else
{
parameterTypes = null;
}
SignatureHelper sig = GetMemberRefSignature(methodInfo.CallingConvention,
MethodBuilder.GetMethodBaseReturnType(methodInfo),
parameterTypes,
optionalParameterTypes);
if (rtMeth != null)
return GetTokenForVarArgMethod(rtMeth, sig);
else
return GetTokenForVarArgMethod(dm, sig);
}
internal override SignatureHelper GetMemberRefSignature(
CallingConventions call,
Type returnType,
Type[] parameterTypes,
Type[] optionalParameterTypes)
{
SignatureHelper sig = SignatureHelper.GetMethodSigHelper(call, returnType);
if (parameterTypes != null)
{
foreach (Type t in parameterTypes)
sig.AddArgument(t);
}
if (optionalParameterTypes != null && optionalParameterTypes.Length != 0)
{
// add the sentinel
sig.AddSentinel();
foreach (Type t in optionalParameterTypes)
sig.AddArgument(t);
}
return sig;
}
internal override void RecordTokenFixup()
{
// DynamicMethod doesn't need fixup.
}
#region GetTokenFor helpers
private int GetTokenFor(RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
#endif
return m_scope.GetTokenFor(rtType.TypeHandle);
}
private int GetTokenFor(RuntimeFieldInfo runtimeField)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
RtFieldInfo rtField = runtimeField as RtFieldInfo;
if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
}
#endif
return m_scope.GetTokenFor(runtimeField.FieldHandle);
}
private int GetTokenFor(RuntimeFieldInfo runtimeField, RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
RtFieldInfo rtField = runtimeField as RtFieldInfo;
if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
}
#endif
return m_scope.GetTokenFor(runtimeField.FieldHandle, rtType.TypeHandle);
}
private int GetTokenFor(RuntimeConstructorInfo rtMeth)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle);
}
private int GetTokenFor(RuntimeConstructorInfo rtMeth, RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
}
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle);
}
private int GetTokenFor(RuntimeMethodInfo rtMeth)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle);
}
private int GetTokenFor(RuntimeMethodInfo rtMeth, RuntimeType rtType)
{
#if FEATURE_APPX
if (ProfileAPICheck)
{
if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
}
#endif
return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle);
}
private int GetTokenFor(DynamicMethod dm)
{
return m_scope.GetTokenFor(dm);
}
private int GetTokenForVarArgMethod(RuntimeMethodInfo rtMeth, SignatureHelper sig)
{
#if FEATURE_APPX
if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif
VarArgMethod varArgMeth = new VarArgMethod(rtMeth, sig);
return m_scope.GetTokenFor(varArgMeth);
}
private int GetTokenForVarArgMethod(DynamicMethod dm, SignatureHelper sig)
{
VarArgMethod varArgMeth = new VarArgMethod(dm, sig);
return m_scope.GetTokenFor(varArgMeth);
}
private int GetTokenForString(String s)
{
return m_scope.GetTokenFor(s);
}
private int GetTokenForSig(byte[] sig)
{
return m_scope.GetTokenFor(sig);
}
#endregion
}
internal class DynamicResolver : Resolver
{
#region Private Data Members
private __ExceptionInfo[] m_exceptions;
private byte[] m_exceptionHeader;
private DynamicMethod m_method;
private byte[] m_code;
private byte[] m_localSignature;
private int m_stackSize;
private DynamicScope m_scope;
#endregion
#region Internal Methods
internal DynamicResolver(DynamicILGenerator ilGenerator)
{
m_stackSize = ilGenerator.GetMaxStackSize();
m_exceptions = ilGenerator.GetExceptions();
m_code = ilGenerator.BakeByteArray();
m_localSignature = ilGenerator.m_localSignature.InternalGetSignatureArray();
m_scope = ilGenerator.m_scope;
m_method = (DynamicMethod)ilGenerator.m_methodBuilder;
m_method.m_resolver = this;
}
internal DynamicResolver(DynamicILInfo dynamicILInfo)
{
m_stackSize = dynamicILInfo.MaxStackSize;
m_code = dynamicILInfo.Code;
m_localSignature = dynamicILInfo.LocalSignature;
m_exceptionHeader = dynamicILInfo.Exceptions;
//m_exceptions = dynamicILInfo.Exceptions;
m_scope = dynamicILInfo.DynamicScope;
m_method = dynamicILInfo.DynamicMethod;
m_method.m_resolver = this;
}
//
// We can destroy the unmanaged part of dynamic method only after the managed part is definitely gone and thus
// nobody can call the dynamic method anymore. A call to finalizer alone does not guarantee that the managed
// part is gone. A malicious code can keep a reference to DynamicMethod in long weak reference that survives finalization,
// or we can be running during shutdown where everything is finalized.
//
// The unmanaged resolver keeps a reference to the managed resolver in long weak handle. If the long weak handle
// is null, we can be sure that the managed part of the dynamic method is definitely gone and that it is safe to
// destroy the unmanaged part. (Note that the managed finalizer has to be on the same object that the long weak handle
// points to in order for this to work.) Unfortunately, we can not perform the above check when out finalizer
// is called - the long weak handle won't be cleared yet. Instead, we create a helper scout object that will attempt
// to do the destruction after next GC.
//
// The finalization does not have to be done using CriticalFinalizerObject. We have to go over all DynamicMethodDescs
// during AppDomain shutdown anyway to avoid leaks e.g. if somebody stores reference to DynamicMethod in static.
//
~DynamicResolver()
{
DynamicMethod method = m_method;
if (method == null)
return;
if (method.m_methodHandle == null)
return;
DestroyScout scout = null;
try
{
scout = new DestroyScout();
}
catch
{
// We go over all DynamicMethodDesc during AppDomain shutdown and make sure
// that everything associated with them is released. So it is ok to skip reregistration
// for finalization during appdomain shutdown
if (!Environment.HasShutdownStarted &&
!AppDomain.CurrentDomain.IsFinalizingForUnload())
{
// Try again later.
GC.ReRegisterForFinalize(this);
}
return;
}
// We can never ever have two active destroy scouts for the same method. We need to initialize the scout
// outside the try/reregister block to avoid possibility of reregistration for finalization with active scout.
scout.m_methodHandle = method.m_methodHandle.Value;
}
private class DestroyScout
{
internal RuntimeMethodHandleInternal m_methodHandle;
~DestroyScout()
{
if (m_methodHandle.IsNullHandle())
return;
// It is not safe to destroy the method if the managed resolver is alive.
if (RuntimeMethodHandle.GetResolver(m_methodHandle) != null)
{
if (!Environment.HasShutdownStarted &&
!AppDomain.CurrentDomain.IsFinalizingForUnload())
{
// Somebody might have been holding a reference on us via weak handle.
// We will keep trying. It will be hopefully released eventually.
GC.ReRegisterForFinalize(this);
}
return;
}
RuntimeMethodHandle.Destroy(m_methodHandle);
}
}
// Keep in sync with vm/dynamicmethod.h
[Flags]
internal enum SecurityControlFlags
{
Default = 0x0,
SkipVisibilityChecks = 0x1,
RestrictedSkipVisibilityChecks = 0x2,
HasCreationContext = 0x4,
CanSkipCSEvaluation = 0x8,
}
internal override RuntimeType GetJitContext(ref int securityControlFlags)
{
RuntimeType typeOwner;
SecurityControlFlags flags = SecurityControlFlags.Default;
if (m_method.m_restrictedSkipVisibility)
flags |= SecurityControlFlags.RestrictedSkipVisibilityChecks;
else if (m_method.m_skipVisibility)
flags |= SecurityControlFlags.SkipVisibilityChecks;
typeOwner = m_method.m_typeOwner;
securityControlFlags = (int)flags;
return typeOwner;
}
private static int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
{
int num = 0;
if (excp == null)
return 0;
for (int i = 0; i < excp.Length; i++)
num += excp[i].GetNumberOfCatches();
return num;
}
internal override byte[] GetCodeInfo(
ref int stackSize, ref int initLocals, ref int EHCount)
{
stackSize = m_stackSize;
if (m_exceptionHeader != null && m_exceptionHeader.Length != 0)
{
if (m_exceptionHeader.Length < 4)
throw new FormatException();
byte header = m_exceptionHeader[0];
if ((header & 0x40) != 0) // Fat
{
byte[] size = new byte[4];
for (int q = 0; q < 3; q++)
size[q] = m_exceptionHeader[q + 1];
EHCount = (BitConverter.ToInt32(size, 0) - 4) / 24;
}
else
EHCount = (m_exceptionHeader[1] - 2) / 12;
}
else
{
EHCount = CalculateNumberOfExceptions(m_exceptions);
}
initLocals = (m_method.InitLocals) ? 1 : 0;
return m_code;
}
internal override byte[] GetLocalsSignature()
{
return m_localSignature;
}
internal override unsafe byte[] GetRawEHInfo()
{
return m_exceptionHeader;
}
internal override unsafe void GetEHInfo(int excNumber, void* exc)
{
CORINFO_EH_CLAUSE* exception = (CORINFO_EH_CLAUSE*)exc;
for (int i = 0; i < m_exceptions.Length; i++)
{
int excCount = m_exceptions[i].GetNumberOfCatches();
if (excNumber < excCount)
{
// found the right exception block
exception->Flags = m_exceptions[i].GetExceptionTypes()[excNumber];
exception->TryOffset = m_exceptions[i].GetStartAddress();
if ((exception->Flags & __ExceptionInfo.Finally) != __ExceptionInfo.Finally)
exception->TryLength = m_exceptions[i].GetEndAddress() - exception->TryOffset;
else
exception->TryLength = m_exceptions[i].GetFinallyEndAddress() - exception->TryOffset;
exception->HandlerOffset = m_exceptions[i].GetCatchAddresses()[excNumber];
exception->HandlerLength = m_exceptions[i].GetCatchEndAddresses()[excNumber] - exception->HandlerOffset;
// this is cheating because the filter address is the token of the class only for light code gen
exception->ClassTokenOrFilterOffset = m_exceptions[i].GetFilterAddresses()[excNumber];
break;
}
excNumber -= excCount;
}
}
internal override String GetStringLiteral(int token) { return m_scope.GetString(token); }
internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle)
{
typeHandle = new IntPtr();
methodHandle = new IntPtr();
fieldHandle = new IntPtr();
Object handle = m_scope[token];
if (handle == null)
throw new InvalidProgramException();
if (handle is RuntimeTypeHandle)
{
typeHandle = ((RuntimeTypeHandle)handle).Value;
return;
}
if (handle is RuntimeMethodHandle)
{
methodHandle = ((RuntimeMethodHandle)handle).Value;
return;
}
if (handle is RuntimeFieldHandle)
{
fieldHandle = ((RuntimeFieldHandle)handle).Value;
return;
}
DynamicMethod dm = handle as DynamicMethod;
if (dm != null)
{
methodHandle = dm.GetMethodDescriptor().Value;
return;
}
GenericMethodInfo gmi = handle as GenericMethodInfo;
if (gmi != null)
{
methodHandle = gmi.m_methodHandle.Value;
typeHandle = gmi.m_context.Value;
return;
}
GenericFieldInfo gfi = handle as GenericFieldInfo;
if (gfi != null)
{
fieldHandle = gfi.m_fieldHandle.Value;
typeHandle = gfi.m_context.Value;
return;
}
VarArgMethod vaMeth = handle as VarArgMethod;
if (vaMeth != null)
{
if (vaMeth.m_dynamicMethod == null)
{
methodHandle = vaMeth.m_method.MethodHandle.Value;
typeHandle = vaMeth.m_method.GetDeclaringTypeInternal().GetTypeHandleInternal().Value;
}
else
methodHandle = vaMeth.m_dynamicMethod.GetMethodDescriptor().Value;
return;
}
}
internal override byte[] ResolveSignature(int token, int fromMethod)
{
return m_scope.ResolveSignature(token, fromMethod);
}
internal override MethodInfo GetDynamicMethod()
{
return m_method.GetMethodInfo();
}
#endregion
}
internal class DynamicILInfo
{
#region Private Data Members
private DynamicMethod m_method;
private DynamicScope m_scope;
private byte[] m_exceptions;
private byte[] m_code;
private byte[] m_localSignature;
private int m_maxStackSize;
private int m_methodSignature;
#endregion
#region Internal Methods
internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
{
dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
module, m_method.Name, (byte[])m_scope[m_methodSignature], new DynamicResolver(this));
}
internal byte[] LocalSignature
{
get
{
if (m_localSignature == null)
m_localSignature = SignatureHelper.GetLocalVarSigHelper().InternalGetSignatureArray();
return m_localSignature;
}
}
internal byte[] Exceptions { get { return m_exceptions; } }
internal byte[] Code { get { return m_code; } }
internal int MaxStackSize { get { return m_maxStackSize; } }
#endregion
#region Public ILGenerator Methods
public DynamicMethod DynamicMethod { get { return m_method; } }
internal DynamicScope DynamicScope { get { return m_scope; } }
#endregion
#region Public Scope Methods
#endregion
}
internal class DynamicScope
{
#region Private Data Members
internal List<Object> m_tokens;
#endregion
#region Constructor
internal unsafe DynamicScope()
{
m_tokens = new List<Object>();
m_tokens.Add(null);
}
#endregion
#region Internal Methods
internal object this[int token]
{
get
{
token &= 0x00FFFFFF;
if (token < 0 || token > m_tokens.Count)
return null;
return m_tokens[token];
}
}
internal int GetTokenFor(VarArgMethod varArgMethod)
{
m_tokens.Add(varArgMethod);
return m_tokens.Count - 1 | (int)MetadataTokenType.MemberRef;
}
internal string GetString(int token) { return this[token] as string; }
internal byte[] ResolveSignature(int token, int fromMethod)
{
if (fromMethod == 0)
return (byte[])this[token];
VarArgMethod vaMethod = this[token] as VarArgMethod;
if (vaMethod == null)
return null;
return vaMethod.m_signature.GetSignature(true);
}
#endregion
#region Public Methods
public int GetTokenFor(RuntimeMethodHandle method)
{
IRuntimeMethodInfo methodReal = method.GetMethodInfo();
RuntimeMethodHandleInternal rmhi = methodReal.Value;
if (methodReal != null && !RuntimeMethodHandle.IsDynamicMethod(rmhi))
{
RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi);
if ((type != null) && RuntimeTypeHandle.HasInstantiation(type))
{
// Do we really need to retrieve this much info just to throw an exception?
MethodBase m = RuntimeType.GetMethodBase(methodReal);
Type t = m.DeclaringType.GetGenericTypeDefinition();
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGenericLcg"), m, t));
}
}
m_tokens.Add(method);
return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
}
public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle typeContext)
{
m_tokens.Add(new GenericMethodInfo(method, typeContext));
return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
}
public int GetTokenFor(DynamicMethod method)
{
m_tokens.Add(method);
return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
}
public int GetTokenFor(RuntimeFieldHandle field)
{
m_tokens.Add(field);
return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef;
}
public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle typeContext)
{
m_tokens.Add(new GenericFieldInfo(field, typeContext));
return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef;
}
public int GetTokenFor(RuntimeTypeHandle type)
{
m_tokens.Add(type);
return m_tokens.Count - 1 | (int)MetadataTokenType.TypeDef;
}
public int GetTokenFor(string literal)
{
m_tokens.Add(literal);
return m_tokens.Count - 1 | (int)MetadataTokenType.String;
}
public int GetTokenFor(byte[] signature)
{
m_tokens.Add(signature);
return m_tokens.Count - 1 | (int)MetadataTokenType.Signature;
}
#endregion
}
internal sealed class GenericMethodInfo
{
internal RuntimeMethodHandle m_methodHandle;
internal RuntimeTypeHandle m_context;
internal GenericMethodInfo(RuntimeMethodHandle methodHandle, RuntimeTypeHandle context)
{
m_methodHandle = methodHandle;
m_context = context;
}
}
internal sealed class GenericFieldInfo
{
internal RuntimeFieldHandle m_fieldHandle;
internal RuntimeTypeHandle m_context;
internal GenericFieldInfo(RuntimeFieldHandle fieldHandle, RuntimeTypeHandle context)
{
m_fieldHandle = fieldHandle;
m_context = context;
}
}
internal sealed class VarArgMethod
{
internal RuntimeMethodInfo m_method;
internal DynamicMethod m_dynamicMethod;
internal SignatureHelper m_signature;
internal VarArgMethod(DynamicMethod dm, SignatureHelper signature)
{
m_dynamicMethod = dm;
m_signature = signature;
}
internal VarArgMethod(RuntimeMethodInfo method, SignatureHelper signature)
{
m_method = method;
m_signature = signature;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using System.Threading.Tasks;
using DHT.Server.Data;
using DHT.Server.Data.Filters;
using DHT.Utils.Collections;
using DHT.Utils.Logging;
using Microsoft.Data.Sqlite;
namespace DHT.Server.Database.Sqlite {
public sealed class SqliteDatabaseFile : IDatabaseFile {
public static async Task<SqliteDatabaseFile?> OpenOrCreate(string path, Func<Task<bool>> checkCanUpgradeSchemas) {
string connectionString = new SqliteConnectionStringBuilder {
DataSource = path,
Mode = SqliteOpenMode.ReadWriteCreate
}.ToString();
var conn = new SqliteConnection(connectionString);
conn.Open();
return await new Schema(conn).Setup(checkCanUpgradeSchemas) ? new SqliteDatabaseFile(path, conn) : null;
}
public string Path { get; }
public DatabaseStatistics Statistics { get; }
private readonly Log log;
private readonly SqliteConnection conn;
private SqliteDatabaseFile(string path, SqliteConnection conn) {
this.log = Log.ForType(typeof(SqliteDatabaseFile), System.IO.Path.GetFileName(path));
this.conn = conn;
this.Path = path;
this.Statistics = new DatabaseStatistics();
UpdateServerStatistics();
UpdateChannelStatistics();
UpdateUserStatistics();
UpdateMessageStatistics();
}
public void Dispose() {
conn.Dispose();
}
public void AddServer(Data.Server server) {
using var cmd = conn.Upsert("servers", new[] {
("id", SqliteType.Integer),
("name", SqliteType.Text),
("type", SqliteType.Text)
});
cmd.Set(":id", server.Id);
cmd.Set(":name", server.Name);
cmd.Set(":type", ServerTypes.ToString(server.Type));
cmd.ExecuteNonQuery();
UpdateServerStatistics();
}
public List<Data.Server> GetAllServers() {
var perf = log.Start();
var list = new List<Data.Server>();
using var cmd = conn.Command("SELECT id, name, type FROM servers");
using var reader = cmd.ExecuteReader();
while (reader.Read()) {
list.Add(new Data.Server {
Id = reader.GetUint64(0),
Name = reader.GetString(1),
Type = ServerTypes.FromString(reader.GetString(2))
});
}
perf.End();
return list;
}
public void AddChannel(Channel channel) {
using var cmd = conn.Upsert("channels", new[] {
("id", SqliteType.Integer),
("server", SqliteType.Integer),
("name", SqliteType.Text),
("parent_id", SqliteType.Integer),
("position", SqliteType.Integer),
("topic", SqliteType.Text),
("nsfw", SqliteType.Integer)
});
cmd.Set(":id", channel.Id);
cmd.Set(":server", channel.Server);
cmd.Set(":name", channel.Name);
cmd.Set(":parent_id", channel.ParentId);
cmd.Set(":position", channel.Position);
cmd.Set(":topic", channel.Topic);
cmd.Set(":nsfw", channel.Nsfw);
cmd.ExecuteNonQuery();
UpdateChannelStatistics();
}
public List<Channel> GetAllChannels() {
var list = new List<Channel>();
using var cmd = conn.Command("SELECT id, server, name, parent_id, position, topic, nsfw FROM channels");
using var reader = cmd.ExecuteReader();
while (reader.Read()) {
list.Add(new Channel {
Id = reader.GetUint64(0),
Server = reader.GetUint64(1),
Name = reader.GetString(2),
ParentId = reader.IsDBNull(3) ? null : reader.GetUint64(3),
Position = reader.IsDBNull(4) ? null : reader.GetInt32(4),
Topic = reader.IsDBNull(5) ? null : reader.GetString(5),
Nsfw = reader.IsDBNull(6) ? null : reader.GetBoolean(6)
});
}
return list;
}
public void AddUsers(User[] users) {
using var tx = conn.BeginTransaction();
using var cmd = conn.Upsert("users", new[] {
("id", SqliteType.Integer),
("name", SqliteType.Text),
("avatar_url", SqliteType.Text),
("discriminator", SqliteType.Text)
});
foreach (var user in users) {
cmd.Set(":id", user.Id);
cmd.Set(":name", user.Name);
cmd.Set(":avatar_url", user.AvatarUrl);
cmd.Set(":discriminator", user.Discriminator);
cmd.ExecuteNonQuery();
}
tx.Commit();
UpdateUserStatistics();
}
public List<User> GetAllUsers() {
var perf = log.Start();
var list = new List<User>();
using var cmd = conn.Command("SELECT id, name, avatar_url, discriminator FROM users");
using var reader = cmd.ExecuteReader();
while (reader.Read()) {
list.Add(new User {
Id = reader.GetUint64(0),
Name = reader.GetString(1),
AvatarUrl = reader.IsDBNull(2) ? null : reader.GetString(2),
Discriminator = reader.IsDBNull(3) ? null : reader.GetString(3)
});
}
perf.End();
return list;
}
public void AddMessages(Message[] messages) {
static SqliteCommand DeleteByMessageId(SqliteConnection conn, string tableName) {
return conn.Delete(tableName, ("message_id", SqliteType.Integer));
}
static void ExecuteDeleteByMessageId(SqliteCommand cmd, object id) {
cmd.Set(":message_id", id);
cmd.ExecuteNonQuery();
}
using var tx = conn.BeginTransaction();
using var messageCmd = conn.Upsert("messages", new[] {
("message_id", SqliteType.Integer),
("sender_id", SqliteType.Integer),
("channel_id", SqliteType.Integer),
("text", SqliteType.Text),
("timestamp", SqliteType.Integer)
});
using var deleteEditTimestampCmd = DeleteByMessageId(conn, "edit_timestamps");
using var deleteRepliedToCmd = DeleteByMessageId(conn, "replied_to");
using var deleteAttachmentsCmd = DeleteByMessageId(conn, "attachments");
using var deleteEmbedsCmd = DeleteByMessageId(conn, "embeds");
using var deleteReactionsCmd = DeleteByMessageId(conn, "reactions");
using var editTimestampCmd = conn.Insert("edit_timestamps", new [] {
("message_id", SqliteType.Integer),
("edit_timestamp", SqliteType.Integer)
});
using var repliedToCmd = conn.Insert("replied_to", new [] {
("message_id", SqliteType.Integer),
("replied_to_id", SqliteType.Integer)
});
using var attachmentCmd = conn.Insert("attachments", new[] {
("message_id", SqliteType.Integer),
("attachment_id", SqliteType.Integer),
("name", SqliteType.Text),
("type", SqliteType.Text),
("url", SqliteType.Text),
("size", SqliteType.Integer)
});
using var embedCmd = conn.Insert("embeds", new[] {
("message_id", SqliteType.Integer),
("json", SqliteType.Text)
});
using var reactionCmd = conn.Insert("reactions", new[] {
("message_id", SqliteType.Integer),
("emoji_id", SqliteType.Integer),
("emoji_name", SqliteType.Text),
("emoji_flags", SqliteType.Integer),
("count", SqliteType.Integer)
});
foreach (var message in messages) {
object messageId = message.Id;
messageCmd.Set(":message_id", messageId);
messageCmd.Set(":sender_id", message.Sender);
messageCmd.Set(":channel_id", message.Channel);
messageCmd.Set(":text", message.Text);
messageCmd.Set(":timestamp", message.Timestamp);
messageCmd.ExecuteNonQuery();
ExecuteDeleteByMessageId(deleteEditTimestampCmd, messageId);
ExecuteDeleteByMessageId(deleteRepliedToCmd, messageId);
ExecuteDeleteByMessageId(deleteAttachmentsCmd, messageId);
ExecuteDeleteByMessageId(deleteEmbedsCmd, messageId);
ExecuteDeleteByMessageId(deleteReactionsCmd, messageId);
if (message.EditTimestamp is {} timestamp) {
editTimestampCmd.Set(":message_id", messageId);
editTimestampCmd.Set(":edit_timestamp", timestamp);
editTimestampCmd.ExecuteNonQuery();
}
if (message.RepliedToId is {} repliedToId) {
repliedToCmd.Set(":message_id", messageId);
repliedToCmd.Set(":replied_to_id", repliedToId);
repliedToCmd.ExecuteNonQuery();
}
if (!message.Attachments.IsEmpty) {
foreach (var attachment in message.Attachments) {
attachmentCmd.Set(":message_id", messageId);
attachmentCmd.Set(":attachment_id", attachment.Id);
attachmentCmd.Set(":name", attachment.Name);
attachmentCmd.Set(":type", attachment.Type);
attachmentCmd.Set(":url", attachment.Url);
attachmentCmd.Set(":size", attachment.Size);
attachmentCmd.ExecuteNonQuery();
}
}
if (!message.Embeds.IsEmpty) {
foreach (var embed in message.Embeds) {
embedCmd.Set(":message_id", messageId);
embedCmd.Set(":json", embed.Json);
embedCmd.ExecuteNonQuery();
}
}
if (!message.Reactions.IsEmpty) {
foreach (var reaction in message.Reactions) {
reactionCmd.Set(":message_id", messageId);
reactionCmd.Set(":emoji_id", reaction.EmojiId);
reactionCmd.Set(":emoji_name", reaction.EmojiName);
reactionCmd.Set(":emoji_flags", (int) reaction.EmojiFlags);
reactionCmd.Set(":count", reaction.Count);
reactionCmd.ExecuteNonQuery();
}
}
}
tx.Commit();
UpdateMessageStatistics();
}
public int CountMessages(MessageFilter? filter = null) {
using var cmd = conn.Command("SELECT COUNT(*) FROM messages" + filter.GenerateWhereClause());
using var reader = cmd.ExecuteReader();
return reader.Read() ? reader.GetInt32(0) : 0;
}
public List<Message> GetMessages(MessageFilter? filter = null) {
var perf = log.Start();
var list = new List<Message>();
var attachments = GetAllAttachments();
var embeds = GetAllEmbeds();
var reactions = GetAllReactions();
using var cmd = conn.Command(@"
SELECT m.message_id, m.sender_id, m.channel_id, m.text, m.timestamp, et.edit_timestamp, rt.replied_to_id
FROM messages m
LEFT JOIN edit_timestamps et ON m.message_id = et.message_id
LEFT JOIN replied_to rt ON m.message_id = rt.message_id" + filter.GenerateWhereClause("m"));
using var reader = cmd.ExecuteReader();
while (reader.Read()) {
ulong id = reader.GetUint64(0);
list.Add(new Message {
Id = id,
Sender = reader.GetUint64(1),
Channel = reader.GetUint64(2),
Text = reader.GetString(3),
Timestamp = reader.GetInt64(4),
EditTimestamp = reader.IsDBNull(5) ? null : reader.GetInt64(5),
RepliedToId = reader.IsDBNull(6) ? null : reader.GetUint64(6),
Attachments = attachments.GetListOrNull(id)?.ToImmutableArray() ?? ImmutableArray<Attachment>.Empty,
Embeds = embeds.GetListOrNull(id)?.ToImmutableArray() ?? ImmutableArray<Embed>.Empty,
Reactions = reactions.GetListOrNull(id)?.ToImmutableArray() ?? ImmutableArray<Reaction>.Empty
});
}
perf.End();
return list;
}
public void RemoveMessages(MessageFilter filter, MessageFilterRemovalMode mode) {
var whereClause = filter.GenerateWhereClause(invert: mode == MessageFilterRemovalMode.KeepMatching);
if (string.IsNullOrEmpty(whereClause)) {
return;
}
var perf = log.Start();
// Rider is being stupid...
StringBuilder build = new StringBuilder()
.Append("DELETE ")
.Append("FROM messages")
.Append(whereClause);
using var cmd = conn.Command(build.ToString());
cmd.ExecuteNonQuery();
UpdateMessageStatistics();
perf.End();
}
private MultiDictionary<ulong, Attachment> GetAllAttachments() {
var dict = new MultiDictionary<ulong, Attachment>();
using var cmd = conn.Command("SELECT message_id, attachment_id, name, type, url, size FROM attachments");
using var reader = cmd.ExecuteReader();
while (reader.Read()) {
ulong messageId = reader.GetUint64(0);
dict.Add(messageId, new Attachment {
Id = reader.GetUint64(1),
Name = reader.GetString(2),
Type = reader.IsDBNull(3) ? null : reader.GetString(3),
Url = reader.GetString(4),
Size = reader.GetUint64(5)
});
}
return dict;
}
private MultiDictionary<ulong, Embed> GetAllEmbeds() {
var dict = new MultiDictionary<ulong, Embed>();
using var cmd = conn.Command("SELECT message_id, json FROM embeds");
using var reader = cmd.ExecuteReader();
while (reader.Read()) {
ulong messageId = reader.GetUint64(0);
dict.Add(messageId, new Embed {
Json = reader.GetString(1)
});
}
return dict;
}
private MultiDictionary<ulong, Reaction> GetAllReactions() {
var dict = new MultiDictionary<ulong, Reaction>();
using var cmd = conn.Command("SELECT message_id, emoji_id, emoji_name, emoji_flags, count FROM reactions");
using var reader = cmd.ExecuteReader();
while (reader.Read()) {
ulong messageId = reader.GetUint64(0);
dict.Add(messageId, new Reaction {
EmojiId = reader.IsDBNull(1) ? null : reader.GetUint64(1),
EmojiName = reader.IsDBNull(2) ? null : reader.GetString(2),
EmojiFlags = (EmojiFlags) reader.GetInt16(3),
Count = reader.GetInt32(4)
});
}
return dict;
}
private void UpdateServerStatistics() {
Statistics.TotalServers = conn.SelectScalar("SELECT COUNT(*) FROM servers") as long? ?? 0;
}
private void UpdateChannelStatistics() {
Statistics.TotalChannels = conn.SelectScalar("SELECT COUNT(*) FROM channels") as long? ?? 0;
}
private void UpdateUserStatistics() {
Statistics.TotalUsers = conn.SelectScalar("SELECT COUNT(*) FROM users") as long? ?? 0;
}
private void UpdateMessageStatistics() {
Statistics.TotalMessages = conn.SelectScalar("SELECT COUNT(*) FROM messages") as long? ?? 0L;
}
}
}
| |
// 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.Dynamic.Utils;
namespace System.Linq.Expressions.Interpreter
{
internal abstract class LessThanOrEqualInstruction : Instruction
{
private readonly object _nullValue;
private static Instruction s_SByte, s_Int16, s_Char, s_Int32, s_Int64, s_Byte, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double;
private static Instruction s_liftedToNullSByte, s_liftedToNullInt16, s_liftedToNullChar, s_liftedToNullInt32, s_liftedToNullInt64, s_liftedToNullByte, s_liftedToNullUInt16, s_liftedToNullUInt32, s_liftedToNullUInt64, s_liftedToNullSingle, s_liftedToNullDouble;
public override int ConsumedStack => 2;
public override int ProducedStack => 1;
public override string InstructionName => "LessThanOrEqual";
private LessThanOrEqualInstruction(object nullValue)
{
_nullValue = nullValue;
}
private sealed class LessThanOrEqualSByte : LessThanOrEqualInstruction
{
public LessThanOrEqualSByte(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((sbyte)left <= (sbyte)right);
}
return 1;
}
}
private sealed class LessThanOrEqualInt16 : LessThanOrEqualInstruction
{
public LessThanOrEqualInt16(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((short)left <= (short)right);
}
return 1;
}
}
private sealed class LessThanOrEqualChar : LessThanOrEqualInstruction
{
public LessThanOrEqualChar(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((char)left <= (char)right);
}
return 1;
}
}
private sealed class LessThanOrEqualInt32 : LessThanOrEqualInstruction
{
public LessThanOrEqualInt32(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((int)left <= (int)right);
}
return 1;
}
}
private sealed class LessThanOrEqualInt64 : LessThanOrEqualInstruction
{
public LessThanOrEqualInt64(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((long)left <= (long)right);
}
return 1;
}
}
private sealed class LessThanOrEqualByte : LessThanOrEqualInstruction
{
public LessThanOrEqualByte(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((byte)left <= (byte)right);
}
return 1;
}
}
private sealed class LessThanOrEqualUInt16 : LessThanOrEqualInstruction
{
public LessThanOrEqualUInt16(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((ushort)left <= (ushort)right);
}
return 1;
}
}
private sealed class LessThanOrEqualUInt32 : LessThanOrEqualInstruction
{
public LessThanOrEqualUInt32(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((uint)left <= (uint)right);
}
return 1;
}
}
private sealed class LessThanOrEqualUInt64 : LessThanOrEqualInstruction
{
public LessThanOrEqualUInt64(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((ulong)left <= (ulong)right);
}
return 1;
}
}
private sealed class LessThanOrEqualSingle : LessThanOrEqualInstruction
{
public LessThanOrEqualSingle(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((float)left <= (float)right);
}
return 1;
}
}
private sealed class LessThanOrEqualDouble : LessThanOrEqualInstruction
{
public LessThanOrEqualDouble(object nullValue)
: base(nullValue)
{
}
public override int Run(InterpretedFrame frame)
{
object right = frame.Pop();
object left = frame.Pop();
if (left == null || right == null)
{
frame.Push(_nullValue);
}
else
{
frame.Push((double)left <= (double)right);
}
return 1;
}
}
public static Instruction Create(Type type, bool liftedToNull = false)
{
Debug.Assert(!type.IsEnum);
if (liftedToNull)
{
return type.GetNonNullableType().GetTypeCode() switch
{
TypeCode.SByte => s_liftedToNullSByte ?? (s_liftedToNullSByte = new LessThanOrEqualSByte(null)),
TypeCode.Int16 => s_liftedToNullInt16 ?? (s_liftedToNullInt16 = new LessThanOrEqualInt16(null)),
TypeCode.Char => s_liftedToNullChar ?? (s_liftedToNullChar = new LessThanOrEqualChar(null)),
TypeCode.Int32 => s_liftedToNullInt32 ?? (s_liftedToNullInt32 = new LessThanOrEqualInt32(null)),
TypeCode.Int64 => s_liftedToNullInt64 ?? (s_liftedToNullInt64 = new LessThanOrEqualInt64(null)),
TypeCode.Byte => s_liftedToNullByte ?? (s_liftedToNullByte = new LessThanOrEqualByte(null)),
TypeCode.UInt16 => s_liftedToNullUInt16 ?? (s_liftedToNullUInt16 = new LessThanOrEqualUInt16(null)),
TypeCode.UInt32 => s_liftedToNullUInt32 ?? (s_liftedToNullUInt32 = new LessThanOrEqualUInt32(null)),
TypeCode.UInt64 => s_liftedToNullUInt64 ?? (s_liftedToNullUInt64 = new LessThanOrEqualUInt64(null)),
TypeCode.Single => s_liftedToNullSingle ?? (s_liftedToNullSingle = new LessThanOrEqualSingle(null)),
TypeCode.Double => s_liftedToNullDouble ?? (s_liftedToNullDouble = new LessThanOrEqualDouble(null)),
_ => throw ContractUtils.Unreachable,
};
}
else
{
return type.GetNonNullableType().GetTypeCode() switch
{
TypeCode.SByte => s_SByte ?? (s_SByte = new LessThanOrEqualSByte(Utils.BoxedFalse)),
TypeCode.Int16 => s_Int16 ?? (s_Int16 = new LessThanOrEqualInt16(Utils.BoxedFalse)),
TypeCode.Char => s_Char ?? (s_Char = new LessThanOrEqualChar(Utils.BoxedFalse)),
TypeCode.Int32 => s_Int32 ?? (s_Int32 = new LessThanOrEqualInt32(Utils.BoxedFalse)),
TypeCode.Int64 => s_Int64 ?? (s_Int64 = new LessThanOrEqualInt64(Utils.BoxedFalse)),
TypeCode.Byte => s_Byte ?? (s_Byte = new LessThanOrEqualByte(Utils.BoxedFalse)),
TypeCode.UInt16 => s_UInt16 ?? (s_UInt16 = new LessThanOrEqualUInt16(Utils.BoxedFalse)),
TypeCode.UInt32 => s_UInt32 ?? (s_UInt32 = new LessThanOrEqualUInt32(Utils.BoxedFalse)),
TypeCode.UInt64 => s_UInt64 ?? (s_UInt64 = new LessThanOrEqualUInt64(Utils.BoxedFalse)),
TypeCode.Single => s_Single ?? (s_Single = new LessThanOrEqualSingle(Utils.BoxedFalse)),
TypeCode.Double => s_Double ?? (s_Double = new LessThanOrEqualDouble(Utils.BoxedFalse)),
_ => throw ContractUtils.Unreachable,
};
}
}
}
}
| |
// 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.Collections.ObjectModel;
using System.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Hosting;
using Xunit;
namespace System.ComponentModel.Composition.AttributedModel
{
public class INotifyImportTests
{
[Export(typeof(PartWithoutImports))]
public class PartWithoutImports : IPartImportsSatisfiedNotification
{
public bool ImportsSatisfiedInvoked { get; private set; }
public void OnImportsSatisfied()
{
this.ImportsSatisfiedInvoked = true;
}
}
[Fact]
public void ImportsSatisfiedOnComponentWithoutImports()
{
CompositionContainer container = ContainerFactory.CreateWithAttributedCatalog(typeof(PartWithoutImports));
PartWithoutImports partWithoutImports = container.GetExportedValue<PartWithoutImports>();
Assert.NotNull(partWithoutImports);
Assert.True(partWithoutImports.ImportsSatisfiedInvoked);
}
[Fact]
public void ImportCompletedTest()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var entrypoint = new UpperCaseStringComponent();
batch.AddParts(new LowerCaseString("abc"), entrypoint);
container.Compose(batch);
batch = new CompositionBatch();
batch.AddParts(new object());
container.Compose(batch);
Assert.Equal(1, entrypoint.LowerCaseStrings.Count);
Assert.Equal(1, entrypoint.ImportCompletedCallCount);
Assert.Equal(1, entrypoint.UpperCaseStrings.Count);
Assert.Equal("abc", entrypoint.LowerCaseStrings[0].Value.String);
Assert.Equal("ABC", entrypoint.UpperCaseStrings[0]);
}
[Fact]
public void ImportCompletedWithRecomposing()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var entrypoint = new UpperCaseStringComponent();
batch.AddParts(new LowerCaseString("abc"), entrypoint);
container.Compose(batch);
Assert.Equal(1, entrypoint.LowerCaseStrings.Count);
Assert.Equal(1, entrypoint.ImportCompletedCallCount);
Assert.Equal(1, entrypoint.UpperCaseStrings.Count);
Assert.Equal("abc", entrypoint.LowerCaseStrings[0].Value.String);
Assert.Equal("ABC", entrypoint.UpperCaseStrings[0]);
// Add another component to verify recomposing
batch = new CompositionBatch();
batch.AddParts(new LowerCaseString("def"));
container.Compose(batch);
Assert.Equal(2, entrypoint.LowerCaseStrings.Count);
Assert.Equal(2, entrypoint.ImportCompletedCallCount);
Assert.Equal(2, entrypoint.UpperCaseStrings.Count);
Assert.Equal("def", entrypoint.LowerCaseStrings[1].Value.String);
Assert.Equal("DEF", entrypoint.UpperCaseStrings[1]);
// Verify that adding a random component doesn't cause
// the OnImportsSatisfied to be called again.
batch = new CompositionBatch();
batch.AddParts(new object());
container.Compose(batch);
Assert.Equal(2, entrypoint.LowerCaseStrings.Count);
Assert.Equal(2, entrypoint.ImportCompletedCallCount);
Assert.Equal(2, entrypoint.UpperCaseStrings.Count);
}
[Fact]
[ActiveIssue(700940)]
public void ImportCompletedUsingSatisfyImportsOnce()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
var entrypoint = new UpperCaseStringComponent();
var entrypointPart = AttributedModelServices.CreatePart(entrypoint);
batch.AddParts(new LowerCaseString("abc"));
container.Compose(batch);
container.SatisfyImportsOnce(entrypointPart);
Assert.Equal(1, entrypoint.LowerCaseStrings.Count);
Assert.Equal(1, entrypoint.ImportCompletedCallCount);
Assert.Equal(1, entrypoint.UpperCaseStrings.Count);
Assert.Equal("abc", entrypoint.LowerCaseStrings[0].Value.String);
Assert.Equal("ABC", entrypoint.UpperCaseStrings[0]);
batch = new CompositionBatch();
batch.AddParts(new object());
container.Compose(batch);
container.SatisfyImportsOnce(entrypointPart);
Assert.Equal(1, entrypoint.LowerCaseStrings.Count);
Assert.Equal(1, entrypoint.ImportCompletedCallCount);
Assert.Equal(1, entrypoint.UpperCaseStrings.Count);
Assert.Equal("abc", entrypoint.LowerCaseStrings[0].Value.String);
Assert.Equal("ABC", entrypoint.UpperCaseStrings[0]);
batch.AddParts(new LowerCaseString("def"));
container.Compose(batch);
container.SatisfyImportsOnce(entrypointPart);
Assert.Equal(2, entrypoint.LowerCaseStrings.Count);
Assert.Equal(2, entrypoint.ImportCompletedCallCount);
Assert.Equal(2, entrypoint.UpperCaseStrings.Count);
Assert.Equal("abc", entrypoint.LowerCaseStrings[0].Value.String);
Assert.Equal("ABC", entrypoint.UpperCaseStrings[0]);
Assert.Equal("def", entrypoint.LowerCaseStrings[1].Value.String);
Assert.Equal("DEF", entrypoint.UpperCaseStrings[1]);
}
[Fact]
[ActiveIssue(654513)]
public void ImportCompletedCalledAfterAllImportsAreFullyComposed()
{
int importSatisfationCount = 0;
var importer1 = new MyEventDrivenFullComposedNotifyImporter1();
var importer2 = new MyEventDrivenFullComposedNotifyImporter2();
Action<object, EventArgs> verificationAction = (object sender, EventArgs e) =>
{
Assert.True(importer1.AreAllImportsFullyComposed);
Assert.True(importer2.AreAllImportsFullyComposed);
++importSatisfationCount;
};
importer1.ImportsSatisfied += new EventHandler(verificationAction);
importer2.ImportsSatisfied += new EventHandler(verificationAction);
// importer1 added first
var batch = new CompositionBatch();
batch.AddParts(importer1, importer2);
var container = ContainerFactory.Create();
container.ComposeExportedValue<ICompositionService>(container);
container.Compose(batch);
Assert.Equal(2, importSatisfationCount);
// importer2 added first
importSatisfationCount = 0;
batch = new CompositionBatch();
batch.AddParts(importer2, importer1);
container = ContainerFactory.Create();
container.ComposeExportedValue<ICompositionService>(container);
container.Compose(batch);
Assert.Equal(2, importSatisfationCount);
}
[Fact]
public void ImportCompletedAddPartAndBindComponent()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
batch.AddParts(new CallbackImportNotify(delegate
{
batch = new CompositionBatch();
batch.AddPart(new object());
container.Compose(batch);
}));
container.Compose(batch);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportCompletedChildNeedsParentContainer()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var parent = new CompositionContainer(cat);
CompositionBatch parentBatch = new CompositionBatch();
CompositionBatch childBatch = new CompositionBatch();
CompositionBatch child2Batch = new CompositionBatch();
parentBatch.AddExportedValue<ICompositionService>(parent);
parent.Compose(parentBatch);
var child = new CompositionContainer(parent);
var child2 = new CompositionContainer(parent);
var parentImporter = new MyNotifyImportImporter(parent);
var childImporter = new MyNotifyImportImporter(child);
var child2Importer = new MyNotifyImportImporter(child2);
parentBatch = new CompositionBatch();
parentBatch.AddPart(parentImporter);
childBatch.AddPart(childImporter);
child2Batch.AddPart(child2Importer);
parent.Compose(parentBatch);
child.Compose(childBatch);
child2.Compose(child2Batch);
Assert.Equal(1, parentImporter.ImportCompletedCallCount);
Assert.Equal(1, childImporter.ImportCompletedCallCount);
Assert.Equal(1, child2Importer.ImportCompletedCallCount);
MyNotifyImportExporter parentExporter = parent.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, parentExporter.ImportCompletedCallCount);
MyNotifyImportExporter childExporter = child.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, childExporter.ImportCompletedCallCount);
MyNotifyImportExporter child2Exporter = child2.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, child2Exporter.ImportCompletedCallCount);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportCompletedChildDoesnotNeedParentContainer()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var parent = new CompositionContainer(cat);
CompositionBatch parentBatch = new CompositionBatch();
CompositionBatch childBatch = new CompositionBatch();
parentBatch.AddExportedValue<ICompositionService>(parent);
parent.Compose(parentBatch);
var child = new CompositionContainer(parent);
var parentImporter = new MyNotifyImportImporter(parent);
var childImporter = new MyNotifyImportImporter(child);
parentBatch = new CompositionBatch();
parentBatch.AddPart(parentImporter);
childBatch.AddParts(childImporter, new MyNotifyImportExporter());
child.Compose(childBatch);
Assert.Equal(0, parentImporter.ImportCompletedCallCount);
Assert.Equal(1, childImporter.ImportCompletedCallCount);
// Parent will become bound at this point.
MyNotifyImportExporter parentExporter = parent.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
parent.Compose(parentBatch);
Assert.Equal(1, parentImporter.ImportCompletedCallCount);
Assert.Equal(1, parentExporter.ImportCompletedCallCount);
MyNotifyImportExporter childExporter = child.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, childExporter.ImportCompletedCallCount);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportCompletedBindChildIndirectlyThroughParentContainerBind()
{
var cat = CatalogFactory.CreateDefaultAttributed();
var parent = new CompositionContainer(cat);
CompositionBatch parentBatch = new CompositionBatch();
CompositionBatch childBatch = new CompositionBatch();
parentBatch.AddExportedValue<ICompositionService>(parent);
parent.Compose(parentBatch);
var child = new CompositionContainer(parent);
var parentImporter = new MyNotifyImportImporter(parent);
var childImporter = new MyNotifyImportImporter(child);
parentBatch = new CompositionBatch();
parentBatch.AddPart(parentImporter);
childBatch.AddParts(childImporter, new MyNotifyImportExporter());
parent.Compose(parentBatch);
child.Compose(childBatch);
Assert.Equal(1, parentImporter.ImportCompletedCallCount);
Assert.Equal(1, childImporter.ImportCompletedCallCount);
MyNotifyImportExporter parentExporter = parent.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, parentExporter.ImportCompletedCallCount);
MyNotifyImportExporter childExporter = child.GetExportedValue<MyNotifyImportExporter>("MyNotifyImportExporter");
Assert.Equal(1, childExporter.ImportCompletedCallCount);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportCompletedGetExportedValueLazy()
{
var cat = CatalogFactory.CreateDefaultAttributed();
CompositionContainer container = new CompositionContainer(cat);
NotifyImportExportee.InstanceCount = 0;
NotifyImportExportsLazy notifyee = container.GetExportedValue<NotifyImportExportsLazy>("NotifyImportExportsLazy");
Assert.NotNull(notifyee);
Assert.NotNull(notifyee.Imports);
Assert.True(notifyee.NeedRefresh);
Assert.Equal(3, notifyee.Imports.Count);
Assert.Equal(0, NotifyImportExportee.InstanceCount);
Assert.Equal(0, notifyee.realImports.Count);
Assert.Equal(2, notifyee.RealImports.Count);
Assert.Equal(1, notifyee.RealImports[0].Id);
Assert.Equal(3, notifyee.RealImports[1].Id);
Assert.Equal(2, NotifyImportExportee.InstanceCount);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ImportCompletedGetExportedValueEager()
{
var cat = CatalogFactory.CreateDefaultAttributed();
CompositionContainer container = new CompositionContainer(cat);
NotifyImportExportee.InstanceCount = 0;
var notifyee = container.GetExportedValue<NotifyImportExportsEager>("NotifyImportExportsEager");
Assert.NotNull(notifyee);
Assert.NotNull(notifyee.Imports);
Assert.Equal(3, notifyee.Imports.Count);
Assert.Equal(2, NotifyImportExportee.InstanceCount);
Assert.Equal(2, notifyee.realImports.Count);
Assert.Equal(2, notifyee.RealImports.Count);
Assert.Equal(1, notifyee.RealImports[0].Id);
Assert.Equal(3, notifyee.RealImports[1].Id);
Assert.Equal(2, NotifyImportExportee.InstanceCount);
}
}
public class NotifyImportExportee
{
public NotifyImportExportee(int id)
{
Id = id;
InstanceCount++;
}
public int Id { get; set; }
public static int InstanceCount { get; set; }
}
public class NotifyImportExporter
{
public NotifyImportExporter()
{
}
[Export()]
[ExportMetadata("Filter", false)]
public NotifyImportExportee Export1
{
get
{
return new NotifyImportExportee(1);
}
}
[Export()]
[ExportMetadata("Filter", true)]
public NotifyImportExportee Export2
{
get
{
return new NotifyImportExportee(2);
}
}
[Export()]
[ExportMetadata("Filter", false)]
public NotifyImportExportee Export3
{
get
{
return new NotifyImportExportee(3);
}
}
}
[Export("NotifyImportExportsLazy")]
public class NotifyImportExportsLazy : IPartImportsSatisfiedNotification
{
public NotifyImportExportsLazy()
{
NeedRefresh = false;
}
[ImportMany(typeof(NotifyImportExportee))]
public Collection<Lazy<NotifyImportExportee, IDictionary<string, object>>> Imports { get; set; }
public bool NeedRefresh { get; set; }
public void OnImportsSatisfied()
{
NeedRefresh = true;
}
internal Collection<NotifyImportExportee> realImports = new Collection<NotifyImportExportee>();
public Collection<NotifyImportExportee> RealImports
{
get
{
if (NeedRefresh)
{
realImports.Clear();
foreach (var import in Imports)
{
if (!((bool)import.Metadata["Filter"]))
{
realImports.Add(import.Value);
}
}
NeedRefresh = false;
}
return realImports;
}
}
}
[Export("NotifyImportExportsEager")]
public class NotifyImportExportsEager : IPartImportsSatisfiedNotification
{
public NotifyImportExportsEager()
{
}
[ImportMany]
public Collection<Lazy<NotifyImportExportee, IDictionary<string, object>>> Imports { get; set; }
public void OnImportsSatisfied()
{
realImports.Clear();
foreach (var import in Imports)
{
if (!((bool)import.Metadata["Filter"]))
{
realImports.Add(import.Value);
}
}
}
internal Collection<NotifyImportExportee> realImports = new Collection<NotifyImportExportee>();
public Collection<NotifyImportExportee> RealImports
{
get
{
return realImports;
}
}
}
public class MyEventDrivenNotifyImporter : IPartImportsSatisfiedNotification
{
[Import]
public ICompositionService ImportSomethingSoIGetImportCompletedCalled { get; set; }
public event EventHandler ImportsSatisfied;
public void OnImportsSatisfied()
{
if (this.ImportsSatisfied != null)
{
this.ImportsSatisfied(this, new EventArgs());
}
}
}
[Export]
public class MyEventDrivenFullComposedNotifyImporter1 : MyEventDrivenNotifyImporter
{
[Import]
public MyEventDrivenFullComposedNotifyImporter2 FullyComposedImport { get; set; }
public bool AreAllImportsSet
{
get
{
return (this.ImportSomethingSoIGetImportCompletedCalled != null)
&& (this.FullyComposedImport != null);
}
}
public bool AreAllImportsFullyComposed
{
get
{
return this.AreAllImportsSet && this.FullyComposedImport.AreAllImportsSet;
}
}
}
[Export]
public class MyEventDrivenFullComposedNotifyImporter2 : MyEventDrivenNotifyImporter
{
[Import]
public MyEventDrivenFullComposedNotifyImporter1 FullyComposedImport { get; set; }
public bool AreAllImportsSet
{
get
{
return (this.ImportSomethingSoIGetImportCompletedCalled != null)
&& (this.FullyComposedImport != null);
}
}
public bool AreAllImportsFullyComposed
{
get
{
return this.AreAllImportsSet && this.FullyComposedImport.AreAllImportsSet;
}
}
}
[Export("MyNotifyImportExporter")]
public class MyNotifyImportExporter : IPartImportsSatisfiedNotification
{
[Import]
public ICompositionService ImportSomethingSoIGetImportCompletedCalled { get; set; }
public int ImportCompletedCallCount { get; set; }
public void OnImportsSatisfied()
{
ImportCompletedCallCount++;
}
}
public class MyNotifyImportImporter : IPartImportsSatisfiedNotification
{
private CompositionContainer container;
public MyNotifyImportImporter(CompositionContainer container)
{
this.container = container;
}
[Import("MyNotifyImportExporter")]
public MyNotifyImportExporter MyNotifyImportExporter { get; set; }
public int ImportCompletedCallCount { get; set; }
public void OnImportsSatisfied()
{
ImportCompletedCallCount++;
}
}
[Export("LowerCaseString")]
public class LowerCaseString
{
public string String { get; private set; }
public LowerCaseString(string s)
{
String = s.ToLower();
}
}
public class UpperCaseStringComponent : IPartImportsSatisfiedNotification
{
public UpperCaseStringComponent()
{
UpperCaseStrings = new List<string>();
}
Collection<Lazy<LowerCaseString>> lowerCaseString = new Collection<Lazy<LowerCaseString>>();
[ImportMany("LowerCaseString", AllowRecomposition = true)]
public Collection<Lazy<LowerCaseString>> LowerCaseStrings
{
get { return lowerCaseString; }
set { lowerCaseString = value; }
}
public List<string> UpperCaseStrings { get; set; }
public int ImportCompletedCallCount { get; set; }
// This method gets called whenever a bind is completed and any of
// of the imports have changed, but ar safe to use now.
public void OnImportsSatisfied()
{
UpperCaseStrings.Clear();
foreach (var i in LowerCaseStrings)
UpperCaseStrings.Add(i.Value.String.ToUpper());
ImportCompletedCallCount++;
}
}
}
| |
//
// BaseWebServer.cs
//
// Author:
// Aaron Bockover <[email protected]>
// James Wilcox <[email protected]>
// Neil Loknath <[email protected]
//
// Copyright (C) 2005-2006 Novell, Inc.
// Copyright (C) 2009 Neil Loknath
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
namespace Banshee.Web
{
public abstract class BaseHttpServer
{
protected Socket server;
private int backlog;
private ushort port;
protected readonly ArrayList clients = new ArrayList();
public BaseHttpServer (EndPoint endpoint, string name)
{
this.end_point = endpoint;
this.name = name;
}
public BaseHttpServer (EndPoint endpoint, string name, int chunk_length) : this (endpoint, name)
{
this.chunk_length = chunk_length;
}
private string name = "Banshee Web Server";
public string Name {
get { return name; }
}
private EndPoint end_point = new IPEndPoint (IPAddress.Any, 80);
protected EndPoint EndPoint {
get { return end_point; }
set {
if (value == null) {
throw new ArgumentNullException ("end_point");
}
if (running) {
throw new InvalidOperationException ("Cannot set EndPoint while running.");
}
end_point = value;
}
}
private bool running;
public bool Running {
get { return running; }
protected set { running = value; }
}
private int chunk_length = 8192;
public int ChunkLength {
get { return chunk_length; }
}
public ushort Port {
get { return port; }
}
public void Start ()
{
Start (10);
}
public virtual void Start (int backlog)
{
if (backlog < 0) {
throw new ArgumentOutOfRangeException ("backlog");
}
if (running) {
return;
}
this.backlog = backlog;
running = true;
Thread thread = new Thread (ServerLoop);
thread.Name = this.Name;
thread.IsBackground = true;
thread.Start ();
}
public virtual void Stop ()
{
running = false;
if (server != null) {
server.Close ();
server = null;
}
foreach (Socket client in (ArrayList)clients.Clone ()) {
client.Close ();
}
}
private void ServerLoop ()
{
server = new Socket (this.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.IP);
server.Bind (this.EndPoint);
server.Listen (backlog);
port = (ushort)(server.LocalEndPoint as IPEndPoint).Port;
while (true) {
try {
if (!running) {
break;
}
Socket client = server.Accept ();
clients.Add (client);
ThreadPool.QueueUserWorkItem (HandleConnection, client);
} catch (SocketException) {
break;
}
}
}
private void HandleConnection (object o)
{
Socket client = (Socket) o;
try {
while (HandleRequest(client));
} catch (IOException) {
} catch (Exception e) {
Hyena.Log.Exception (e);
} finally {
clients.Remove (client);
client.Close ();
}
}
protected virtual long ParseRangeRequest (string line)
{
long offset = 0;
if (String.IsNullOrEmpty (line)) {
return offset;
}
string [] split_line = line.Split (' ', '=', '-');
foreach (string word in split_line) {
if (long.TryParse (word, out offset)) {
return offset;
}
}
return offset;
}
protected virtual bool HandleRequest (Socket client)
{
if (client == null || !client.Connected) {
return false;
}
bool keep_connection = true;
using (StreamReader reader = new StreamReader (new NetworkStream (client, false))) {
string request_line = reader.ReadLine ();
if (request_line == null) {
return false;
}
List <string> request_headers = new List <string> ();
string line = null;
do {
line = reader.ReadLine ();
if (line.ToLower () == "connection: close") {
keep_connection = false;
}
request_headers.Add (line);
} while (line != String.Empty && line != null);
string [] split_request_line = request_line.Split ();
if (split_request_line.Length < 3) {
WriteResponse (client, HttpStatusCode.BadRequest, "Bad Request");
return keep_connection;
} else {
try {
HandleValidRequest (client, split_request_line, request_headers.ToArray () );
} catch (IOException) {
keep_connection = false;
} catch (Exception e) {
keep_connection = false;
Console.Error.WriteLine("Trouble handling request {0}: {1}", split_request_line[1], e);
}
}
}
return keep_connection;
}
protected abstract void HandleValidRequest(Socket client, string [] split_request, string [] request_headers);
protected void WriteResponse (Socket client, HttpStatusCode code, string body)
{
WriteResponse (client, code, Encoding.UTF8.GetBytes (body));
}
protected virtual void WriteResponse (Socket client, HttpStatusCode code, byte [] body)
{
if (client == null || !client.Connected) {
return;
}
else if (body == null) {
throw new ArgumentNullException ("body");
}
StringBuilder headers = new StringBuilder ();
headers.AppendFormat ("HTTP/1.1 {0} {1}\r\n", (int) code, code.ToString ());
headers.AppendFormat ("Content-Length: {0}\r\n", body.Length);
headers.Append ("Content-Type: text/html\r\n");
headers.Append ("Connection: close\r\n");
headers.Append ("\r\n");
using (BinaryWriter writer = new BinaryWriter (new NetworkStream (client, false))) {
writer.Write (Encoding.UTF8.GetBytes (headers.ToString ()));
writer.Write (body);
}
client.Close ();
}
protected void WriteResponseStream (Socket client, Stream response, long length, string filename)
{
WriteResponseStream (client, response, length, filename, 0);
}
protected virtual void WriteResponseStream (Socket client, Stream response, long length, string filename, long offset)
{
if (client == null || !client.Connected) {
return;
}
if (response == null) {
throw new ArgumentNullException ("response");
}
if (length < 1) {
throw new ArgumentOutOfRangeException ("length", "Must be > 0");
}
if (offset < 0) {
throw new ArgumentOutOfRangeException ("offset", "Must be positive.");
}
using (BinaryWriter writer = new BinaryWriter (new NetworkStream (client, false))) {
StringBuilder headers = new StringBuilder ();
if (offset > 0) {
headers.Append ("HTTP/1.1 206 Partial Content\r\n");
headers.AppendFormat ("Content-Range: {0}-{1}\r\n", offset, offset + length);
} else {
headers.Append ("HTTP/1.1 200 OK\r\n");
}
if (length > 0) {
headers.AppendFormat ("Content-Length: {0}\r\n", length);
}
if (filename != null) {
headers.AppendFormat ("Content-Disposition: attachment; filename=\"{0}\"\r\n",
filename.Replace ("\"", "\\\""));
}
headers.Append ("Connection: close\r\n");
headers.Append ("\r\n");
writer.Write (Encoding.UTF8.GetBytes (headers.ToString ()));
using (BinaryReader reader = new BinaryReader (response)) {
while (true) {
byte [] buffer = reader.ReadBytes (ChunkLength);
if (buffer == null) {
break;
}
writer.Write(buffer);
if (buffer.Length < ChunkLength) {
break;
}
}
}
}
}
protected static string Escape (string input)
{
return String.IsNullOrEmpty (input) ? "" : System.Web.HttpUtility.HtmlEncode (input);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_ASYNC
using System;
using System.Globalization;
using System.Threading;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
public partial class JsonTextReader
{
// It's not safe to perform the async methods here in a derived class as if the synchronous equivalent
// has been overriden then the asychronous method will no longer be doing the same operation
#if HAVE_ASYNC // Double-check this isn't included inappropriately.
private readonly bool _safeAsync;
#endif
/// <summary>
/// Asynchronously reads the next JSON token from the source.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns <c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool> ReadAsync(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsync(cancellationToken) : base.ReadAsync(cancellationToken);
}
internal Task<bool> DoReadAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
while (true)
{
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValueAsync(cancellationToken);
case State.Object:
case State.ObjectStart:
return ParseObjectAsync(cancellationToken);
case State.PostValue:
Task<bool> task = ParsePostValueAsync(false, cancellationToken);
if (task.IsCompletedSucessfully())
{
if (task.Result)
{
return AsyncUtils.True;
}
}
else
{
return DoReadAsync(task, cancellationToken);
}
break;
case State.Finished:
return ReadFromFinishedAsync(cancellationToken);
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
}
private async Task<bool> DoReadAsync(Task<bool> task, CancellationToken cancellationToken)
{
bool result = await task.ConfigureAwait(false);
if (result)
{
return true;
}
return await DoReadAsync(cancellationToken).ConfigureAwait(false);
}
private async Task<bool> ParsePostValueAsync(bool ignoreComments, CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_currentState = State.Finished;
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
_charPos++;
SetToken(JsonToken.EndObject);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case '/':
await ParseCommentAsync(!ignoreComments, cancellationToken).ConfigureAwait(false);
if (!ignoreComments)
{
return true;
}
break;
case ',':
_charPos++;
// finished parsing
SetStateBasedOnCurrent();
return false;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
// handle multiple content without comma delimiter
if (SupportMultipleContent && Depth == 0)
{
SetStateBasedOnCurrent();
return false;
}
throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
break;
}
}
}
private async Task<bool> ReadFromFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return false;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
}
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
SetToken(JsonToken.None);
return false;
}
private Task<int> ReadDataAsync(bool append, CancellationToken cancellationToken)
{
return ReadDataAsync(append, 0, cancellationToken);
}
private async Task<int> ReadDataAsync(bool append, int charsRequired, CancellationToken cancellationToken)
{
if (_isEndOfFile)
{
return 0;
}
PrepareBufferForReadData(append, charsRequired);
int charsRead = await _reader.ReadAsync(_chars, _charsUsed, _chars.Length - _charsUsed - 1, cancellationToken).ConfigureAwait(false);
_charsUsed += charsRead;
if (charsRead == 0)
{
_isEndOfFile = true;
}
_chars[_charsUsed] = '\0';
return charsRead;
}
private async Task<bool> ParseValueAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 't':
await ParseTrueAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'f':
await ParseFalseAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'n':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
switch (_chars[_charPos + 1])
{
case 'u':
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
break;
case 'e':
await ParseConstructorAsync(cancellationToken).ConfigureAwait(false);
break;
default:
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
}
else
{
_charPos++;
throw CreateUnexpectedEndException();
}
return true;
case 'N':
await ParseNumberNaNAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 'I':
await ParseNumberPositiveInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
await ParseNumberNegativeInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case 'u':
await ParseUndefinedAsync(cancellationToken).ConfigureAwait(false);
return true;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
return true;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ',':
// don't increment position, the next call to read will handle comma
// this is done to handle multiple empty comma values
SetToken(JsonToken.Undefined);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
break;
}
if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.')
{
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
}
throw CreateUnexpectedCharacterException(currentChar);
}
}
}
private async Task ReadStringIntoBufferAsync(char quote, CancellationToken cancellationToken)
{
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
_stringBuffer.Position = 0;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
}
break;
case '\\':
_charPos = charPos;
if (!await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
// start of escape sequence
int escapeStartPos = charPos - 1;
char currentChar = _chars[charPos];
charPos++;
char writeChar;
switch (currentChar)
{
case 'b':
writeChar = '\b';
break;
case 't':
writeChar = '\t';
break;
case 'n':
writeChar = '\n';
break;
case 'f':
writeChar = '\f';
break;
case 'r':
writeChar = '\r';
break;
case '\\':
writeChar = '\\';
break;
case '"':
case '\'':
case '/':
writeChar = currentChar;
break;
case 'u':
_charPos = charPos;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
if (StringUtils.IsLowSurrogate(writeChar))
{
// low surrogate with no preceding high surrogate; this char is replaced
writeChar = UnicodeReplacementChar;
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
bool anotherHighSurrogate;
// loop for handling situations where there are multiple consecutive high surrogates
do
{
anotherHighSurrogate = false;
// potential start of a surrogate pair
if (await EnsureCharsAsync(2, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u')
{
char highSurrogate = writeChar;
_charPos += 2;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
if (StringUtils.IsLowSurrogate(writeChar))
{
// a valid surrogate pair!
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
// another high surrogate; replace current and start check over
highSurrogate = UnicodeReplacementChar;
anotherHighSurrogate = true;
}
else
{
// high surrogate not followed by low surrogate; original char is replaced
highSurrogate = UnicodeReplacementChar;
}
EnsureBufferNotEmpty();
WriteCharToBuffer(highSurrogate, lastWritePosition, escapeStartPos);
lastWritePosition = _charPos;
}
else
{
// there are not enough remaining chars for the low surrogate or is not follow by unicode sequence
// replace high surrogate and continue on as usual
writeChar = UnicodeReplacementChar;
}
} while (anotherHighSurrogate);
}
charPos = _charPos;
break;
default:
_charPos = charPos;
throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
}
EnsureBufferNotEmpty();
WriteCharToBuffer(writeChar, lastWritePosition, escapeStartPos);
lastWritePosition = charPos;
break;
case StringUtils.CarriageReturn:
_charPos = charPos - 1;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
charPos = _charPos;
break;
case StringUtils.LineFeed:
_charPos = charPos - 1;
ProcessLineFeed();
charPos = _charPos;
break;
case '"':
case '\'':
if (_chars[charPos - 1] == quote)
{
FinishReadStringIntoBuffer(charPos - 1, initialPosition, lastWritePosition);
return;
}
break;
}
}
}
private Task ProcessCarriageReturnAsync(bool append, CancellationToken cancellationToken)
{
_charPos++;
Task<bool> task = EnsureCharsAsync(1, append, cancellationToken);
if (task.IsCompletedSucessfully())
{
SetNewLine(task.Result);
return AsyncUtils.CompletedTask;
}
return ProcessCarriageReturnAsync(task);
}
private async Task ProcessCarriageReturnAsync(Task<bool> task)
{
SetNewLine(await task.ConfigureAwait(false));
}
private async Task<char> ParseUnicodeAsync(CancellationToken cancellationToken)
{
return ConvertUnicode(await EnsureCharsAsync(4, true, cancellationToken).ConfigureAwait(false));
}
private Task<bool> EnsureCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
if (_charPos + relativePosition < _charsUsed)
{
return AsyncUtils.True;
}
if (_isEndOfFile)
{
return AsyncUtils.False;
}
return ReadCharsAsync(relativePosition, append, cancellationToken);
}
private async Task<bool> ReadCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
int charsRequired = _charPos + relativePosition - _charsUsed + 1;
// it is possible that the TextReader doesn't return all data at once
// repeat read until the required text is returned or the reader is out of content
do
{
int charsRead = await ReadDataAsync(append, charsRequired, cancellationToken).ConfigureAwait(false);
// no more content
if (charsRead == 0)
{
return false;
}
charsRequired -= charsRead;
} while (charsRequired > 0);
return true;
}
private async Task<bool> ParseObjectAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
SetToken(JsonToken.EndObject);
_charPos++;
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
return await ParsePropertyAsync(cancellationToken).ConfigureAwait(false);
}
break;
}
}
}
private async Task ParseCommentAsync(bool setToken, CancellationToken cancellationToken)
{
// should have already parsed / character before reaching this method
_charPos++;
if (!await EnsureCharsAsync(1, false, cancellationToken).ConfigureAwait(false))
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
bool singlelineComment;
if (_chars[_charPos] == '*')
{
singlelineComment = false;
}
else if (_chars[_charPos] == '/')
{
singlelineComment = true;
}
else
{
throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
int initialPosition = _charPos;
while (true)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
if (!singlelineComment)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
EndComment(setToken, initialPosition, _charPos);
return;
}
}
else
{
_charPos++;
}
break;
case '*':
_charPos++;
if (!singlelineComment)
{
if (await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos] == '/')
{
EndComment(setToken, initialPosition, _charPos - 1);
_charPos++;
return;
}
}
}
break;
case StringUtils.CarriageReturn:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
ProcessLineFeed();
break;
default:
_charPos++;
break;
}
}
}
private async Task EatWhitespaceAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
_charPos++;
}
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (currentChar == ' ' || char.IsWhiteSpace(currentChar))
{
_charPos++;
}
else
{
return;
}
break;
}
}
}
private async Task ParseStringAsync(char quote, ReadType readType, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
_charPos++;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quote, cancellationToken).ConfigureAwait(false);
ParseReadString(quote, readType);
}
private async Task<bool> MatchValueAsync(string value, CancellationToken cancellationToken)
{
return MatchValue(await EnsureCharsAsync(value.Length - 1, true, cancellationToken).ConfigureAwait(false), value);
}
private async Task<bool> MatchValueWithTrailingSeparatorAsync(string value, CancellationToken cancellationToken)
{
// will match value and then move to the next character, checking that it is a separator character
if (!await MatchValueAsync(value, cancellationToken).ConfigureAwait(false))
{
return false;
}
if (!await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
return true;
}
return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0';
}
private async Task MatchAndSetAsync(string value, JsonToken newToken, object tokenValue, CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync(value, cancellationToken).ConfigureAwait(false))
{
SetToken(newToken, tokenValue);
}
else
{
throw JsonReaderException.Create(this, "Error parsing " + newToken.ToString().ToLowerInvariant() + " value.");
}
}
private Task ParseTrueAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.True, JsonToken.Boolean, true, cancellationToken);
}
private Task ParseFalseAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.False, JsonToken.Boolean, false, cancellationToken);
}
private Task ParseNullAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Null, JsonToken.Null, null, cancellationToken);
}
private async Task ParseConstructorAsync(CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync("new", cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
int initialPosition = _charPos;
int endPosition;
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
}
}
else
{
endPosition = _charPos;
_charPos++;
break;
}
}
else if (char.IsLetterOrDigit(currentChar))
{
_charPos++;
}
else if (currentChar == StringUtils.CarriageReturn)
{
endPosition = _charPos;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
}
else if (currentChar == StringUtils.LineFeed)
{
endPosition = _charPos;
ProcessLineFeed();
break;
}
else if (char.IsWhiteSpace(currentChar))
{
endPosition = _charPos;
_charPos++;
break;
}
else if (currentChar == '(')
{
endPosition = _charPos;
break;
}
else
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
_stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition);
string constructorName = _stringReference.ToString();
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_chars[_charPos] != '(')
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
ClearRecentString();
SetToken(JsonToken.StartConstructor, constructorName);
}
else
{
throw JsonReaderException.Create(this, "Unexpected content while parsing JSON.");
}
}
private async Task<object> ParseNumberNaNAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNaN(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NaN, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberPositiveInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberPositiveInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.PositiveInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberNegativeInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNegativeInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NegativeInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task ParseNumberAsync(ReadType readType, CancellationToken cancellationToken)
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
await ReadNumberIntoBufferAsync(cancellationToken).ConfigureAwait(false);
ParseReadNumber(readType, firstChar, initialPosition);
}
private Task ParseUndefinedAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Undefined, JsonToken.Undefined, null, cancellationToken);
}
private async Task<bool> ParsePropertyAsync(CancellationToken cancellationToken)
{
char firstChar = _chars[_charPos];
char quoteChar;
if (firstChar == '"' || firstChar == '\'')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quoteChar, cancellationToken).ConfigureAwait(false);
}
else if (ValidIdentifierChar(firstChar))
{
quoteChar = '\0';
ShiftBufferIfNeeded();
await ParseUnquotedPropertyAsync(cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
string propertyName;
if (PropertyNameTable != null)
{
propertyName = PropertyNameTable.Get(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length)
// no match in name table
?? _stringReference.ToString();
}
else
{
propertyName = _stringReference.ToString();
}
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_chars[_charPos] != ':')
{
throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
SetToken(JsonToken.PropertyName, propertyName);
_quoteChar = quoteChar;
ClearRecentString();
return true;
}
private async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken)
{
int charPos = _charPos;
while (true)
{
char currentChar = _chars[charPos];
if (currentChar == '\0')
{
_charPos = charPos;
if (_charsUsed == charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
return;
}
}
else if (ReadNumberCharIntoBuffer(currentChar, charPos))
{
return;
}
else
{
charPos++;
}
}
}
private async Task ParseUnquotedPropertyAsync(CancellationToken cancellationToken)
{
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
}
continue;
}
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
}
if (ReadUnquotedPropertyReportIfDone(currentChar, initialPosition))
{
return;
}
}
}
private async Task<bool> ReadNullCharAsync(CancellationToken cancellationToken)
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_isEndOfFile = true;
return true;
}
}
else
{
_charPos++;
}
return false;
}
private async Task HandleNullAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos + 1] == 'u')
{
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
return;
}
_charPos += 2;
throw CreateUnexpectedCharacterException(_chars[_charPos - 1]);
}
_charPos = _charsUsed;
throw CreateUnexpectedEndException();
}
private async Task ReadFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
}
SetToken(JsonToken.None);
}
private async Task<object> ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.PostValue:
if (await ParsePostValueAsync(true, cancellationToken).ConfigureAwait(false))
{
return null;
}
goto case State.Start;
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedStringValue(readType);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return ParseNumberNegativeInfinity(readType);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
await ParseNumberAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
return Value;
case 't':
case 'f':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
string expected = currentChar == 't' ? JsonConvert.True : JsonConvert.False;
if (!await MatchValueWithTrailingSeparatorAsync(expected, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.String, expected);
return expected;
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task<object> ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.PostValue:
if (await ParsePostValueAsync(true, cancellationToken).ConfigureAwait(false))
{
return null;
}
goto case State.Start;
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedNumber(readType);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return await ParseNumberNegativeInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="bool"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="bool"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsBooleanAsync(cancellationToken) : base.ReadAsBooleanAsync(cancellationToken);
}
internal async Task<bool?> DoReadAsBooleanAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.PostValue:
if (await ParsePostValueAsync(true, cancellationToken).ConfigureAwait(false))
{
return null;
}
goto case State.Start;
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return ReadBooleanString(_stringReference.ToString());
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '-':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
bool b;
#if HAVE_BIG_INTEGER
if (Value is BigInteger i)
{
b = i != 0;
}
else
#endif
{
b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Boolean, b, false);
return b;
case 't':
case 'f':
bool isTrue = currentChar == 't';
if (!await MatchValueWithTrailingSeparatorAsync(isTrue ? JsonConvert.True : JsonConvert.False, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.Boolean, isTrue);
return isTrue;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="byte"/>[].
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="byte"/>[]. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<byte[]> ReadAsBytesAsync(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsBytesAsync(cancellationToken) : base.ReadAsBytesAsync(cancellationToken);
}
internal async Task<byte[]> DoReadAsBytesAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
bool isWrapped = false;
switch (_currentState)
{
case State.PostValue:
if (await ParsePostValueAsync(true, cancellationToken).ConfigureAwait(false))
{
return null;
}
goto case State.Start;
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.ReadAsBytes, cancellationToken).ConfigureAwait(false);
byte[] data = (byte[])Value;
if (isWrapped)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (TokenType != JsonToken.EndObject)
{
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
SetToken(JsonToken.Bytes, data, false);
}
return data;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
await ReadIntoWrappedTypeObjectAsync(cancellationToken).ConfigureAwait(false);
isWrapped = true;
break;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return await ReadArrayIntoByteArrayAsync(cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task ReadIntoWrappedTypeObjectAsync(CancellationToken cancellationToken)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsDateTimeAsync(cancellationToken) : base.ReadAsDateTimeAsync(cancellationToken);
}
internal async Task<DateTime?> DoReadAsDateTimeAsync(CancellationToken cancellationToken)
{
return (DateTime?)await ReadStringValueAsync(ReadType.ReadAsDateTime, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsDateTimeOffsetAsync(cancellationToken) : base.ReadAsDateTimeOffsetAsync(cancellationToken);
}
internal async Task<DateTimeOffset?> DoReadAsDateTimeOffsetAsync(CancellationToken cancellationToken)
{
return (DateTimeOffset?)await ReadStringValueAsync(ReadType.ReadAsDateTimeOffset, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="decimal"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="decimal"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsDecimalAsync(cancellationToken) : base.ReadAsDecimalAsync(cancellationToken);
}
internal async Task<decimal?> DoReadAsDecimalAsync(CancellationToken cancellationToken)
{
return (decimal?)await ReadNumberValueAsync(ReadType.ReadAsDecimal, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="double"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="double"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsDoubleAsync(cancellationToken) : base.ReadAsDoubleAsync(cancellationToken);
}
internal async Task<double?> DoReadAsDoubleAsync(CancellationToken cancellationToken)
{
return (double?)await ReadNumberValueAsync(ReadType.ReadAsDouble, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="int"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="int"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsInt32Async(cancellationToken) : base.ReadAsInt32Async(cancellationToken);
}
internal async Task<int?> DoReadAsInt32Async(CancellationToken cancellationToken)
{
return (int?)await ReadNumberValueAsync(ReadType.ReadAsInt32, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="string"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="string"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<string> ReadAsStringAsync(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsStringAsync(cancellationToken) : base.ReadAsStringAsync(cancellationToken);
}
internal async Task<string> DoReadAsStringAsync(CancellationToken cancellationToken)
{
return (string)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
}
}
}
#endif
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
using System.Numerics;
#endif
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
#if (DOTNET || PORTABLE || PORTABLE40)
internal enum MemberTypes
{
Property = 0,
Field = 1,
Event = 2,
Method = 3,
Other = 4
}
#endif
#if PORTABLE
[Flags]
internal enum BindingFlags
{
Default = 0,
IgnoreCase = 1,
DeclaredOnly = 2,
Instance = 4,
Static = 8,
Public = 16,
NonPublic = 32,
FlattenHierarchy = 64,
InvokeMethod = 256,
CreateInstance = 512,
GetField = 1024,
SetField = 2048,
GetProperty = 4096,
SetProperty = 8192,
PutDispProperty = 16384,
ExactBinding = 65536,
PutRefDispProperty = 32768,
SuppressChangeType = 131072,
OptionalParamBinding = 262144,
IgnoreReturn = 16777216
}
#endif
internal static class ReflectionUtils
{
public static readonly Type[] EmptyTypes;
static ReflectionUtils()
{
#if !(PORTABLE40 || PORTABLE)
EmptyTypes = Type.EmptyTypes;
#else
EmptyTypes = new Type[0];
#endif
}
public static bool IsVirtual(this PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
MethodInfo m = propertyInfo.GetGetMethod();
if (m != null && m.IsVirtual)
{
return true;
}
m = propertyInfo.GetSetMethod();
if (m != null && m.IsVirtual)
{
return true;
}
return false;
}
public static MethodInfo GetBaseDefinition(this PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
MethodInfo m = propertyInfo.GetGetMethod();
if (m != null)
{
return m.GetBaseDefinition();
}
m = propertyInfo.GetSetMethod();
if (m != null)
{
return m.GetBaseDefinition();
}
return null;
}
public static bool IsPublic(PropertyInfo property)
{
if (property.GetGetMethod() != null && property.GetGetMethod().IsPublic)
{
return true;
}
if (property.GetSetMethod() != null && property.GetSetMethod().IsPublic)
{
return true;
}
return false;
}
public static Type GetObjectType(object v)
{
return (v != null) ? v.GetType() : null;
}
public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat, SerializationBinder binder)
{
string fullyQualifiedTypeName;
#if !(NET20 || NET35)
if (binder != null)
{
string assemblyName, typeName;
binder.BindToName(t, out assemblyName, out typeName);
fullyQualifiedTypeName = typeName + (assemblyName == null ? "" : ", " + assemblyName);
}
else
{
fullyQualifiedTypeName = t.AssemblyQualifiedName;
}
#else
fullyQualifiedTypeName = t.AssemblyQualifiedName;
#endif
switch (assemblyFormat)
{
case FormatterAssemblyStyle.Simple:
return RemoveAssemblyDetails(fullyQualifiedTypeName);
case FormatterAssemblyStyle.Full:
return fullyQualifiedTypeName;
default:
throw new ArgumentOutOfRangeException();
}
}
private static string RemoveAssemblyDetails(string fullyQualifiedTypeName)
{
StringBuilder builder = new StringBuilder();
// loop through the type name and filter out qualified assembly details from nested type names
bool writingAssemblyName = false;
bool skippingAssemblyDetails = false;
for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
{
char current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(current);
break;
case ']':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(current);
break;
case ',':
if (!writingAssemblyName)
{
writingAssemblyName = true;
builder.Append(current);
}
else
{
skippingAssemblyDetails = true;
}
break;
default:
if (!skippingAssemblyDetails)
{
builder.Append(current);
}
break;
}
}
return builder.ToString();
}
public static bool HasDefaultConstructor(Type t, bool nonPublic)
{
ValidationUtils.ArgumentNotNull(t, nameof(t));
if (t.IsValueType())
{
return true;
}
return (GetDefaultConstructor(t, nonPublic) != null);
}
public static ConstructorInfo GetDefaultConstructor(Type t)
{
return GetDefaultConstructor(t, false);
}
public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic)
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
if (nonPublic)
{
bindingFlags = bindingFlags | BindingFlags.NonPublic;
}
return t.GetConstructors(bindingFlags).SingleOrDefault(c => !c.GetParameters().Any());
}
public static bool IsNullable(Type t)
{
ValidationUtils.ArgumentNotNull(t, nameof(t));
if (t.IsValueType())
{
return IsNullableType(t);
}
return true;
}
public static bool IsNullableType(Type t)
{
ValidationUtils.ArgumentNotNull(t, nameof(t));
return (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
public static Type EnsureNotNullableType(Type t)
{
return (IsNullableType(t))
? Nullable.GetUnderlyingType(t)
: t;
}
public static bool IsGenericDefinition(Type type, Type genericInterfaceDefinition)
{
if (!type.IsGenericType())
{
return false;
}
Type t = type.GetGenericTypeDefinition();
return (t == genericInterfaceDefinition);
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition)
{
Type implementingType;
return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType);
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, nameof(genericInterfaceDefinition));
if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition())
{
throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition));
}
if (type.IsInterface())
{
if (type.IsGenericType())
{
Type interfaceDefinition = type.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = type;
return true;
}
}
}
foreach (Type i in type.GetInterfaces())
{
if (i.IsGenericType())
{
Type interfaceDefinition = i.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = i;
return true;
}
}
}
implementingType = null;
return false;
}
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition)
{
Type implementingType;
return InheritsGenericDefinition(type, genericClassDefinition, out implementingType);
}
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
ValidationUtils.ArgumentNotNull(genericClassDefinition, nameof(genericClassDefinition));
if (!genericClassDefinition.IsClass() || !genericClassDefinition.IsGenericTypeDefinition())
{
throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition));
}
return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType);
}
private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType)
{
if (currentType.IsGenericType())
{
Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition();
if (genericClassDefinition == currentGenericClassDefinition)
{
implementingType = currentType;
return true;
}
}
if (currentType.BaseType() == null)
{
implementingType = null;
return false;
}
return InheritsGenericDefinitionInternal(currentType.BaseType(), genericClassDefinition, out implementingType);
}
/// <summary>
/// Gets the type of the typed collection's items.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The type of the typed collection's items.</returns>
public static Type GetCollectionItemType(Type type)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
Type genericListType;
if (type.IsArray)
{
return type.GetElementType();
}
if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType))
{
if (genericListType.IsGenericTypeDefinition())
{
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
}
return genericListType.GetGenericArguments()[0];
}
if (typeof(IEnumerable).IsAssignableFrom(type))
{
return null;
}
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
}
public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType)
{
ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType));
Type genericDictionaryType;
if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType))
{
if (genericDictionaryType.IsGenericTypeDefinition())
{
throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
}
Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments();
keyType = dictionaryGenericArguments[0];
valueType = dictionaryGenericArguments[1];
return;
}
if (typeof(IDictionary).IsAssignableFrom(dictionaryType))
{
keyType = null;
valueType = null;
return;
}
throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
}
/// <summary>
/// Gets the member's underlying type.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>The underlying type of the member.</returns>
public static Type GetMemberUnderlyingType(MemberInfo member)
{
ValidationUtils.ArgumentNotNull(member, nameof(member));
switch (member.MemberType())
{
case MemberTypes.Field:
return ((FieldInfo)member).FieldType;
case MemberTypes.Property:
return ((PropertyInfo)member).PropertyType;
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
case MemberTypes.Method:
return ((MethodInfo)member).ReturnType;
default:
throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo, EventInfo or MethodInfo", nameof(member));
}
}
/// <summary>
/// Determines whether the member is an indexed property.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>
/// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(MemberInfo member)
{
ValidationUtils.ArgumentNotNull(member, nameof(member));
PropertyInfo propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
{
return IsIndexedProperty(propertyInfo);
}
else
{
return false;
}
}
/// <summary>
/// Determines whether the property is an indexed property.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>
/// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(PropertyInfo property)
{
ValidationUtils.ArgumentNotNull(property, nameof(property));
return (property.GetIndexParameters().Length > 0);
}
/// <summary>
/// Gets the member's value on the object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target object.</param>
/// <returns>The member's value on the object.</returns>
public static object GetMemberValue(MemberInfo member, object target)
{
ValidationUtils.ArgumentNotNull(member, nameof(member));
ValidationUtils.ArgumentNotNull(target, nameof(target));
switch (member.MemberType())
{
case MemberTypes.Field:
return ((FieldInfo)member).GetValue(target);
case MemberTypes.Property:
try
{
return ((PropertyInfo)member).GetValue(target, null);
}
catch (TargetParameterCountException e)
{
throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e);
}
default:
throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), nameof(member));
}
}
/// <summary>
/// Sets the member's value on the target object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target.</param>
/// <param name="value">The value.</param>
public static void SetMemberValue(MemberInfo member, object target, object value)
{
ValidationUtils.ArgumentNotNull(member, nameof(member));
ValidationUtils.ArgumentNotNull(target, nameof(target));
switch (member.MemberType())
{
case MemberTypes.Field:
((FieldInfo)member).SetValue(target, value);
break;
case MemberTypes.Property:
((PropertyInfo)member).SetValue(target, value, null);
break;
default:
throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), nameof(member));
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be read.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be read.</param>
/// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>.
/// </returns>
public static bool CanReadMemberValue(MemberInfo member, bool nonPublic)
{
switch (member.MemberType())
{
case MemberTypes.Field:
FieldInfo fieldInfo = (FieldInfo)member;
if (nonPublic)
{
return true;
}
else if (fieldInfo.IsPublic)
{
return true;
}
return false;
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo)member;
if (!propertyInfo.CanRead)
{
return false;
}
if (nonPublic)
{
return true;
}
return (propertyInfo.GetGetMethod(nonPublic) != null);
default:
return false;
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be set.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be set.</param>
/// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param>
/// <param name="canSetReadOnly">if set to <c>true</c> then allow the member to be set if read-only.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>.
/// </returns>
public static bool CanSetMemberValue(MemberInfo member, bool nonPublic, bool canSetReadOnly)
{
switch (member.MemberType())
{
case MemberTypes.Field:
FieldInfo fieldInfo = (FieldInfo)member;
if (fieldInfo.IsLiteral)
{
return false;
}
if (fieldInfo.IsInitOnly && !canSetReadOnly)
{
return false;
}
if (nonPublic)
{
return true;
}
if (fieldInfo.IsPublic)
{
return true;
}
return false;
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo)member;
if (!propertyInfo.CanWrite)
{
return false;
}
if (nonPublic)
{
return true;
}
return (propertyInfo.GetSetMethod(nonPublic) != null);
default:
return false;
}
}
public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr)
{
List<MemberInfo> targetMembers = new List<MemberInfo>();
targetMembers.AddRange(GetFields(type, bindingAttr));
targetMembers.AddRange(GetProperties(type, bindingAttr));
// for some reason .NET returns multiple members when overriding a generic member on a base class
// http://social.msdn.microsoft.com/Forums/en-US/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/reflection-overriden-abstract-generic-properties?forum=netfxbcl
// filter members to only return the override on the topmost class
// update: I think this is fixed in .NET 3.5 SP1 - leave this in for now...
List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count);
foreach (var groupedMember in targetMembers.GroupBy(m => m.Name))
{
int count = groupedMember.Count();
IList<MemberInfo> members = groupedMember.ToList();
if (count == 1)
{
distinctMembers.Add(members.First());
}
else
{
IList<MemberInfo> resolvedMembers = new List<MemberInfo>();
foreach (MemberInfo memberInfo in members)
{
// this is a bit hacky
// if the hiding property is hiding a base property and it is virtual
// then this ensures the derived property gets used
if (resolvedMembers.Count == 0)
{
resolvedMembers.Add(memberInfo);
}
else if (!IsOverridenGenericMember(memberInfo, bindingAttr) || memberInfo.Name == "Item")
{
resolvedMembers.Add(memberInfo);
}
}
distinctMembers.AddRange(resolvedMembers);
}
}
return distinctMembers;
}
private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr)
{
if (memberInfo.MemberType() != MemberTypes.Property)
{
return false;
}
PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
if (!IsVirtual(propertyInfo))
{
return false;
}
Type declaringType = propertyInfo.DeclaringType;
if (!declaringType.IsGenericType())
{
return false;
}
Type genericTypeDefinition = declaringType.GetGenericTypeDefinition();
if (genericTypeDefinition == null)
{
return false;
}
MemberInfo[] members = genericTypeDefinition.GetMember(propertyInfo.Name, bindingAttr);
if (members.Length == 0)
{
return false;
}
Type memberUnderlyingType = GetMemberUnderlyingType(members[0]);
if (!memberUnderlyingType.IsGenericParameter)
{
return false;
}
return true;
}
public static T GetAttribute<T>(object attributeProvider) where T : Attribute
{
return GetAttribute<T>(attributeProvider, true);
}
public static T GetAttribute<T>(object attributeProvider, bool inherit) where T : Attribute
{
T[] attributes = GetAttributes<T>(attributeProvider, inherit);
return (attributes != null) ? attributes.FirstOrDefault() : null;
}
#if !(DOTNET || PORTABLE)
public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute
{
Attribute[] a = GetAttributes(attributeProvider, typeof(T), inherit);
T[] attributes = a as T[];
if (attributes != null)
{
return attributes;
}
return a.Cast<T>().ToArray();
}
public static Attribute[] GetAttributes(object attributeProvider, Type attributeType, bool inherit)
{
ValidationUtils.ArgumentNotNull(attributeProvider, nameof(attributeProvider));
object provider = attributeProvider;
// http://hyperthink.net/blog/getcustomattributes-gotcha/
// ICustomAttributeProvider doesn't do inheritance
if (provider is Type)
{
Type t = (Type)provider;
object[] a = (attributeType != null) ? t.GetCustomAttributes(attributeType, inherit) : t.GetCustomAttributes(inherit);
Attribute[] attributes = a.Cast<Attribute>().ToArray();
#if (NET20 || NET35)
// ye olde .NET GetCustomAttributes doesn't respect the inherit argument
if (inherit && t.BaseType != null)
{
attributes = attributes.Union(GetAttributes(t.BaseType, attributeType, inherit)).ToArray();
}
#endif
return attributes;
}
if (provider is Assembly)
{
Assembly a = (Assembly)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(a, attributeType) : Attribute.GetCustomAttributes(a);
}
if (provider is MemberInfo)
{
MemberInfo m = (MemberInfo)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit);
}
#if !PORTABLE40
if (provider is Module)
{
Module m = (Module)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit);
}
#endif
if (provider is ParameterInfo)
{
ParameterInfo p = (ParameterInfo)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(p, attributeType, inherit) : Attribute.GetCustomAttributes(p, inherit);
}
#if !PORTABLE40
ICustomAttributeProvider customAttributeProvider = (ICustomAttributeProvider)attributeProvider;
object[] result = (attributeType != null) ? customAttributeProvider.GetCustomAttributes(attributeType, inherit) : customAttributeProvider.GetCustomAttributes(inherit);
return (Attribute[])result;
#else
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
#endif
}
#else
public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute
{
return GetAttributes(attributeProvider, typeof(T), inherit).Cast<T>().ToArray();
}
public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit)
{
if (provider is Type)
{
Type t = (Type)provider;
return (attributeType != null)
? t.GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray()
: t.GetTypeInfo().GetCustomAttributes(inherit).ToArray();
}
if (provider is Assembly)
{
Assembly a = (Assembly)provider;
return (attributeType != null) ? a.GetCustomAttributes(attributeType).ToArray() : a.GetCustomAttributes().ToArray();
}
if (provider is MemberInfo)
{
MemberInfo m = (MemberInfo)provider;
return (attributeType != null) ? m.GetCustomAttributes(attributeType, inherit).ToArray() : m.GetCustomAttributes(inherit).ToArray();
}
if (provider is Module)
{
Module m = (Module)provider;
return (attributeType != null) ? m.GetCustomAttributes(attributeType).ToArray() : m.GetCustomAttributes().ToArray();
}
if (provider is ParameterInfo)
{
ParameterInfo p = (ParameterInfo)provider;
return (attributeType != null) ? p.GetCustomAttributes(attributeType, inherit).ToArray() : p.GetCustomAttributes(inherit).ToArray();
}
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
}
#endif
public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName)
{
int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName);
if (assemblyDelimiterIndex != null)
{
typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.GetValueOrDefault()).Trim();
assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.GetValueOrDefault() + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.GetValueOrDefault() - 1).Trim();
}
else
{
typeName = fullyQualifiedTypeName;
assemblyName = null;
}
}
private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName)
{
// we need to get the first comma following all surrounded in brackets because of generic types
// e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
int scope = 0;
for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
{
char current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
scope++;
break;
case ']':
scope--;
break;
case ',':
if (scope == 0)
{
return i;
}
break;
}
}
return null;
}
public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo)
{
const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
switch (memberInfo.MemberType())
{
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
Type[] types = propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray();
return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null);
default:
return targetType.GetMember(memberInfo.Name, memberInfo.MemberType(), bindingAttr).SingleOrDefault();
}
}
public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr)
{
ValidationUtils.ArgumentNotNull(targetType, nameof(targetType));
List<MemberInfo> fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr));
#if !PORTABLE
// Type.GetFields doesn't return inherited private fields
// manually find private fields from base class
GetChildPrivateFields(fieldInfos, targetType, bindingAttr);
#endif
return fieldInfos.Cast<FieldInfo>();
}
#if !PORTABLE
private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr)
{
// fix weirdness with private FieldInfos only being returned for the current Type
// find base type fields and add them to result
if ((bindingAttr & BindingFlags.NonPublic) != 0)
{
// modify flags to not search for public fields
BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public);
while ((targetType = targetType.BaseType()) != null)
{
// filter out protected fields
IEnumerable<MemberInfo> childPrivateFields =
targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>();
initialFields.AddRange(childPrivateFields);
}
}
}
#endif
public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr)
{
ValidationUtils.ArgumentNotNull(targetType, nameof(targetType));
List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr));
// GetProperties on an interface doesn't return properties from its interfaces
if (targetType.IsInterface())
{
foreach (Type i in targetType.GetInterfaces())
{
propertyInfos.AddRange(i.GetProperties(bindingAttr));
}
}
GetChildPrivateProperties(propertyInfos, targetType, bindingAttr);
// a base class private getter/setter will be inaccessable unless the property was gotten from the base class
for (int i = 0; i < propertyInfos.Count; i++)
{
PropertyInfo member = propertyInfos[i];
if (member.DeclaringType != targetType)
{
PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member);
propertyInfos[i] = declaredMember;
}
}
return propertyInfos;
}
public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag)
{
return ((bindingAttr & flag) == flag)
? bindingAttr ^ flag
: bindingAttr;
}
private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr)
{
// fix weirdness with private PropertyInfos only being returned for the current Type
// find base type properties and add them to result
// also find base properties that have been hidden by subtype properties with the same name
while ((targetType = targetType.BaseType()) != null)
{
foreach (PropertyInfo propertyInfo in targetType.GetProperties(bindingAttr))
{
PropertyInfo subTypeProperty = propertyInfo;
if (!IsPublic(subTypeProperty))
{
// have to test on name rather than reference because instances are different
// depending on the type that GetProperties was called on
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name);
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
else
{
PropertyInfo childProperty = initialProperties[index];
// don't replace public child with private base
if (!IsPublic(childProperty))
{
// replace nonpublic properties for a child, but gotten from
// the parent with the one from the child
// the property gotten from the child will have access to private getter/setter
initialProperties[index] = subTypeProperty;
}
}
}
else
{
if (!subTypeProperty.IsVirtual())
{
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name
&& p.DeclaringType == subTypeProperty.DeclaringType);
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
}
else
{
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name
&& p.IsVirtual()
&& p.GetBaseDefinition() != null
&& p.GetBaseDefinition().DeclaringType.IsAssignableFrom(subTypeProperty.GetBaseDefinition().DeclaringType));
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
}
}
}
}
}
public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method)
{
bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Any(info =>
info.Name == method &&
// check that the method overrides the original on DynamicObjectProxy
info.DeclaringType != methodDeclaringType
&& info.GetBaseDefinition().DeclaringType == methodDeclaringType
);
return isMethodOverriden;
}
public static object GetDefaultValue(Type type)
{
if (!type.IsValueType())
{
return null;
}
switch (ConvertUtils.GetTypeCode(type))
{
case PrimitiveTypeCode.Boolean:
return false;
case PrimitiveTypeCode.Char:
case PrimitiveTypeCode.SByte:
case PrimitiveTypeCode.Byte:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.UInt32:
return 0;
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
return 0L;
case PrimitiveTypeCode.Single:
return 0f;
case PrimitiveTypeCode.Double:
return 0.0;
case PrimitiveTypeCode.Decimal:
return 0m;
case PrimitiveTypeCode.DateTime:
return new DateTime();
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
case PrimitiveTypeCode.BigInteger:
return new BigInteger();
#endif
case PrimitiveTypeCode.Guid:
return new Guid();
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
return new DateTimeOffset();
#endif
}
if (IsNullable(type))
{
return null;
}
// possibly use IL initobj for perf here?
return Activator.CreateInstance(type);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace Aardvark.Base.Coder
{
public static class FieldCoderExtensions
{
public static IEnumerable<FieldCoder> CreateFieldCoders(this IFieldCodeable self, params string[] members)
{
return CreateFieldCoders(self.GetType(), members);
}
public static IEnumerable<FieldCoder> CreateFieldCoders(this Type type, IEnumerable<string> members)
{
return CreateFieldCoders(type, members.ToArray());
}
public static IEnumerable<FieldCoder> CreateFieldCoders(this Type type, params string[] members)
{
foreach (var member in members)
{
var tokens = member.Split(new[] { '|' });
if (tokens.Length == 1) yield return CreateFieldCoder(type, member, member);
else if (tokens.Length == 2) yield return CreateFieldCoder(type, tokens[0], tokens[1]);
else throw new ArgumentException();
}
}
public static FieldCoder CreateFieldCoder(this IFieldCodeable self, string member)
{
return CreateFieldCoder(self, member, member);
}
public static FieldCoder CreateFieldCoder(this IFieldCodeable self, string name, string memberName)
{
return CreateFieldCoder(self.GetType(), name, memberName);
}
public static FieldCoder CreateFieldCoder(this Type type, string name, string memberName)
{
var field = type.GetField(memberName);
if (field != null)
{
// template:
// (c, o) => c.Code(ref ((Foo)o).m_myField)
var argumentTypes = new[] { typeof(ICoder), typeof(object) };
// create debug method
var debugGen = EmitDebug.CreateDebugMethod(
string.Format("Field_{0}_{1}_{2}", s_fieldId++, type.Name, memberName), typeof(void), argumentTypes);
EmitFieldCoder(debugGen, type, field);
// create result lambda function
var m = new DynamicMethod("lambda", typeof(void), argumentTypes);
EmitFieldCoder(m.GetILGenerator(), type, field);
var code = (Action<ICoder, object>)m.CreateDelegate(typeof(Action<ICoder, object>));
return new FieldCoder(0, name, code);
}
var prop = type.GetProperty(memberName);
if (prop != null)
{
// template:
// (c, o) =>
// {
// if (c.IsWriting) { var v = ((Foo)o).MyProperty; c.Code(ref v); }
// else { var v = 0; c.Code(ref v); ((Foo)o).MyProperty = v; }
// }
var argumentTypes = new[] { typeof(ICoder), typeof(object) };
// create debug method
var debugGen = EmitDebug.CreateDebugMethod(
string.Format("Property_{0}_{1}_{2}", s_propId++, type.Name, memberName), typeof(void), argumentTypes);
EmitPropertyCoder(debugGen, type, prop);
// create result lambda function
var m = new DynamicMethod("lambda", typeof(void), argumentTypes);
EmitPropertyCoder(m.GetILGenerator(), type, prop);
var code = (Action<ICoder, object>)m.CreateDelegate(typeof(Action<ICoder, object>));
return new FieldCoder(0, name, code);
}
throw new NotImplementedException();
}
private static void EmitFieldCoder(ILGenerator gen, Type type, FieldInfo field)
{
var method_Code = GetCodeMethodOverloadFor(field.FieldType);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Castclass, type);
gen.Emit(OpCodes.Ldflda, field);
gen.Emit(OpCodes.Callvirt, method_Code);
gen.Emit(OpCodes.Ret);
}
private static void EmitPropertyCoder(ILGenerator gen, Type type, PropertyInfo prop)
{
var method_IsWriting = typeof(ICoder).GetMethod(
"get_IsWriting",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, new Type[] { }, null
);
var method_Code = GetCodeMethodOverloadFor(prop.PropertyType);
var typeOfCodeMethodArg = method_Code.GetParameters()[0].ParameterType;
//var c = m.DefineParameter(1, ParameterAttributes.None, "c");
//var o = m.DefineParameter(2, ParameterAttributes.None, "o");
/* var v = */ gen.DeclareLocal(prop.PropertyType);
var typeOfCodeMethodArdWithoutRef =
Type.GetType(typeOfCodeMethodArg.FullName.Substring(0, typeOfCodeMethodArg.FullName.Length - 1));
/* var v1 = */ gen.DeclareLocal(typeOfCodeMethodArdWithoutRef);
var label_isReading = gen.DefineLabel();
// if (c.IsWriting)
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Callvirt, method_IsWriting);
gen.Emit(OpCodes.Brfalse_S, label_isReading);
// then writing ...
gen.Emit(OpCodes.Ldarg_1); // var v = ((T)o).MyProperty; c.Code(ref v);
gen.Emit(OpCodes.Castclass, type);
gen.Emit(OpCodes.Callvirt, prop.GetGetMethod());
gen.Emit(OpCodes.Stloc_1);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldloca_S, 1);
gen.Emit(OpCodes.Callvirt, method_Code);
gen.Emit(OpCodes.Ret);
// else reading ...
gen.MarkLabel(label_isReading);
// var v = default(T);
gen.Emit(OpCodes.Ldloca, 0); // load address of local variable v
gen.Emit(OpCodes.Initobj, prop.PropertyType); // initialize v to default value
// c.Code(ref v);
gen.Emit(OpCodes.Ldarg_0); // c, used as this for following call
gen.Emit(OpCodes.Ldloca, 0); // ref v
gen.Emit(OpCodes.Callvirt, method_Code); // call ... c.code(ref v)
// ((T)o).MyProperty = v;
gen.Emit(OpCodes.Ldarg_1); // o
gen.Emit(OpCodes.Castclass, type); // cast to T
gen.Emit(OpCodes.Ldloc_0); // v
//gen.Emit(OpCodes.Castclass, prop.PropertyType);
gen.Emit(OpCodes.Callvirt, prop.GetSetMethod()); // call setter
gen.Emit(OpCodes.Ret);
}
private static int s_fieldId = 0;
private static int s_propId = 0;
private static MethodInfo GetCodeMethodOverloadFor(Type t)
{
// try non-generic Code overloads first
var mi = typeof(ICoder).GetMethod(
"Code", BindingFlags.Instance | BindingFlags.Public, null,
new Type[] { t.MakeByRefType() }, null
);
// if match exists and it is not Code(ref object obj) then we're done
if (mi != null && mi.GetParameters()[0].ParameterType != typeof(object).MakeByRefType())
{
return mi;
}
// try Code<T>(ref T[] obj) overload
if (t.IsArray)
{
var s = t.FullName.Substring(0, t.FullName.Length - 2);
var arrayOfWhat = Type.GetType(s);
return s_methodCodeArrayOfT.MakeGenericMethod(arrayOfWhat);
}
if (t.FullName.StartsWith("System.Collections.Generic.List"))
{
var i = t.FullName.IndexOf('[');
var s = t.FullName.Substring(i + 2, t.FullName.Length - i - 3);
var listOfWhat = Type.GetType(s);
return s_methodCodeListOfT.MakeGenericMethod(listOfWhat);
}
// finally use Code<T>(ref T obj) overload
return s_methodCodeT.MakeGenericMethod(t);
}
private static MethodInfo s_methodCodeT;
private static MethodInfo s_methodCodeArrayOfT;
private static MethodInfo s_methodCodeListOfT;
static FieldCoderExtensions()
{
var genericCodeMethods = (
from m in typeof(ICoder).GetMethods(
BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public)
where m.IsGenericMethod
where m.Name.StartsWith("Code")
select new
{
Method = m,
ParameterType = m.GetParameters()[0].ParameterType
}
).ToArray();
foreach (var m in genericCodeMethods)
{
switch (m.ParameterType.Name)
{
case "T&": s_methodCodeT = m.Method; break;
case "T[]&": s_methodCodeArrayOfT = m.Method; break;
case "List`1&": s_methodCodeListOfT = m.Method; break;
default: throw new NotImplementedException();
}
}
}
}
public static class EmitDebug
{
private static void BeginDebug(string debugAssemblyName)
{
var domain = AppDomain.CurrentDomain;
var aname = new AssemblyName(debugAssemblyName);
aname.Version = new Version(0, 0, 1);
s_assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(aname, AssemblyBuilderAccess.Run);
s_modBuilder = s_assemblyBuilder.DefineDynamicModule("MainModule");
s_typeBuilder = s_modBuilder.DefineType("Debug", TypeAttributes.Public);
}
public static ILGenerator CreateDebugMethod(string name, Type returnType, Type[] parameterTypes)
{
if (s_assemblyBuilder == null) BeginDebug("ReflectEmitDebug");
var mb = s_typeBuilder.DefineMethod(
name, MethodAttributes.Static | MethodAttributes.Public,
returnType, parameterTypes);
return mb.GetILGenerator();
}
[Obsolete("cannot save dynamic assemblies anymore")]
public static void SaveDebug()
{
s_assemblyBuilder = null;
s_modBuilder = null;
s_typeBuilder = null;
throw new NotSupportedException("cannot save dynamic assemblies anymore");
}
private static AssemblyBuilder s_assemblyBuilder;
private static ModuleBuilder s_modBuilder;
private static TypeBuilder s_typeBuilder;
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Client.Protocol.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Client.Protocol
{
/// <summary>
/// <para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/protocol/RequestTargetAuthentication
/// </java-name>
[Dot42.DexImport("org/apache/http/client/protocol/RequestTargetAuthentication", AccessFlags = 33)]
public partial class RequestTargetAuthentication : global::Org.Apache.Http.IHttpRequestInterceptor
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RequestTargetAuthentication() /* MethodBuilder.Create */
{
}
/// <java-name>
/// process
/// </java-name>
[Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)]
public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Request interceptor that matches cookies available in the current CookieStore to the request being executed and generates corresponding cookierequest headers.</para><para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/protocol/RequestAddCookies
/// </java-name>
[Dot42.DexImport("org/apache/http/client/protocol/RequestAddCookies", AccessFlags = 33)]
public partial class RequestAddCookies : global::Org.Apache.Http.IHttpRequestInterceptor
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RequestAddCookies() /* MethodBuilder.Create */
{
}
/// <java-name>
/// process
/// </java-name>
[Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)]
public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/protocol/RequestProxyAuthentication
/// </java-name>
[Dot42.DexImport("org/apache/http/client/protocol/RequestProxyAuthentication", AccessFlags = 33)]
public partial class RequestProxyAuthentication : global::Org.Apache.Http.IHttpRequestInterceptor
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RequestProxyAuthentication() /* MethodBuilder.Create */
{
}
/// <java-name>
/// process
/// </java-name>
[Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)]
public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// org/apache/http/client/protocol/ClientContextConfigurer
/// </java-name>
[Dot42.DexImport("org/apache/http/client/protocol/ClientContextConfigurer", AccessFlags = 33)]
public partial class ClientContextConfigurer : global::Org.Apache.Http.Client.Protocol.IClientContext
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)]
public ClientContextConfigurer(global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setCookieSpecRegistry
/// </java-name>
[Dot42.DexImport("setCookieSpecRegistry", "(Lorg/apache/http/cookie/CookieSpecRegistry;)V", AccessFlags = 1)]
public virtual void SetCookieSpecRegistry(global::Org.Apache.Http.Cookie.CookieSpecRegistry registry) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setAuthSchemeRegistry
/// </java-name>
[Dot42.DexImport("setAuthSchemeRegistry", "(Lorg/apache/http/auth/AuthSchemeRegistry;)V", AccessFlags = 1)]
public virtual void SetAuthSchemeRegistry(global::Org.Apache.Http.Auth.AuthSchemeRegistry registry) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setCookieStore
/// </java-name>
[Dot42.DexImport("setCookieStore", "(Lorg/apache/http/client/CookieStore;)V", AccessFlags = 1)]
public virtual void SetCookieStore(global::Org.Apache.Http.Client.ICookieStore store) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setCredentialsProvider
/// </java-name>
[Dot42.DexImport("setCredentialsProvider", "(Lorg/apache/http/client/CredentialsProvider;)V", AccessFlags = 1)]
public virtual void SetCredentialsProvider(global::Org.Apache.Http.Client.ICredentialsProvider provider) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setAuthSchemePref
/// </java-name>
[Dot42.DexImport("setAuthSchemePref", "(Ljava/util/List;)V", AccessFlags = 1, Signature = "(Ljava/util/List<Ljava/lang/String;>;)V")]
public virtual void SetAuthSchemePref(global::Java.Util.IList<string> list) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ClientContextConfigurer() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Request interceptor that adds default request headers.</para><para><para></para><para></para><title>Revision:</title><para>653041 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/protocol/RequestDefaultHeaders
/// </java-name>
[Dot42.DexImport("org/apache/http/client/protocol/RequestDefaultHeaders", AccessFlags = 33)]
public partial class RequestDefaultHeaders : global::Org.Apache.Http.IHttpRequestInterceptor
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RequestDefaultHeaders() /* MethodBuilder.Create */
{
}
/// <java-name>
/// process
/// </java-name>
[Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)]
public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Response interceptor that populates the current CookieStore with data contained in response cookies received in the given the HTTP response.</para><para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/protocol/ResponseProcessCookies
/// </java-name>
[Dot42.DexImport("org/apache/http/client/protocol/ResponseProcessCookies", AccessFlags = 33)]
public partial class ResponseProcessCookies : global::Org.Apache.Http.IHttpResponseInterceptor
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public ResponseProcessCookies() /* MethodBuilder.Create */
{
}
/// <java-name>
/// process
/// </java-name>
[Dot42.DexImport("process", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)]
public virtual void Process(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Context attribute names for client. </para>
/// </summary>
/// <java-name>
/// org/apache/http/client/protocol/ClientContext
/// </java-name>
[Dot42.DexImport("org/apache/http/client/protocol/ClientContext", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IClientContextConstants
/* scope: __dot42__ */
{
/// <java-name>
/// COOKIESPEC_REGISTRY
/// </java-name>
[Dot42.DexImport("COOKIESPEC_REGISTRY", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIESPEC_REGISTRY = "http.cookiespec-registry";
/// <java-name>
/// AUTHSCHEME_REGISTRY
/// </java-name>
[Dot42.DexImport("AUTHSCHEME_REGISTRY", "Ljava/lang/String;", AccessFlags = 25)]
public const string AUTHSCHEME_REGISTRY = "http.authscheme-registry";
/// <java-name>
/// COOKIE_STORE
/// </java-name>
[Dot42.DexImport("COOKIE_STORE", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE_STORE = "http.cookie-store";
/// <java-name>
/// COOKIE_SPEC
/// </java-name>
[Dot42.DexImport("COOKIE_SPEC", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE_SPEC = "http.cookie-spec";
/// <java-name>
/// COOKIE_ORIGIN
/// </java-name>
[Dot42.DexImport("COOKIE_ORIGIN", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE_ORIGIN = "http.cookie-origin";
/// <java-name>
/// CREDS_PROVIDER
/// </java-name>
[Dot42.DexImport("CREDS_PROVIDER", "Ljava/lang/String;", AccessFlags = 25)]
public const string CREDS_PROVIDER = "http.auth.credentials-provider";
/// <java-name>
/// TARGET_AUTH_STATE
/// </java-name>
[Dot42.DexImport("TARGET_AUTH_STATE", "Ljava/lang/String;", AccessFlags = 25)]
public const string TARGET_AUTH_STATE = "http.auth.target-scope";
/// <java-name>
/// PROXY_AUTH_STATE
/// </java-name>
[Dot42.DexImport("PROXY_AUTH_STATE", "Ljava/lang/String;", AccessFlags = 25)]
public const string PROXY_AUTH_STATE = "http.auth.proxy-scope";
/// <java-name>
/// AUTH_SCHEME_PREF
/// </java-name>
[Dot42.DexImport("AUTH_SCHEME_PREF", "Ljava/lang/String;", AccessFlags = 25)]
public const string AUTH_SCHEME_PREF = "http.auth.scheme-pref";
/// <java-name>
/// USER_TOKEN
/// </java-name>
[Dot42.DexImport("USER_TOKEN", "Ljava/lang/String;", AccessFlags = 25)]
public const string USER_TOKEN = "http.user-token";
}
/// <summary>
/// <para>Context attribute names for client. </para>
/// </summary>
/// <java-name>
/// org/apache/http/client/protocol/ClientContext
/// </java-name>
[Dot42.DexImport("org/apache/http/client/protocol/ClientContext", AccessFlags = 1537)]
public partial interface IClientContext
/* scope: __dot42__ */
{
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="FolderSchema.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the FolderSchema class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Represents the schema for folders.
/// </summary>
[Schema]
public class FolderSchema : ServiceObjectSchema
{
/// <summary>
/// Field URIs for folders.
/// </summary>
private static class FieldUris
{
public const string FolderId = "folder:FolderId";
public const string ParentFolderId = "folder:ParentFolderId";
public const string DisplayName = "folder:DisplayName";
public const string UnreadCount = "folder:UnreadCount";
public const string TotalCount = "folder:TotalCount";
public const string ChildFolderCount = "folder:ChildFolderCount";
public const string FolderClass = "folder:FolderClass";
public const string ManagedFolderInformation = "folder:ManagedFolderInformation";
public const string EffectiveRights = "folder:EffectiveRights";
public const string PermissionSet = "folder:PermissionSet";
public const string PolicyTag = "folder:PolicyTag";
public const string ArchiveTag = "folder:ArchiveTag";
public const string DistinguishedFolderId = "folder:DistinguishedFolderId";
}
/// <summary>
/// Defines the Id property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Id =
new ComplexPropertyDefinition<FolderId>(
XmlElementNames.FolderId,
FieldUris.FolderId,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new FolderId(); });
/// <summary>
/// Defines the FolderClass property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition FolderClass =
new StringPropertyDefinition(
XmlElementNames.FolderClass,
FieldUris.FolderClass,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the ParentFolderId property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ParentFolderId =
new ComplexPropertyDefinition<FolderId>(
XmlElementNames.ParentFolderId,
FieldUris.ParentFolderId,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new FolderId(); });
/// <summary>
/// Defines the ChildFolderCount property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ChildFolderCount =
new IntPropertyDefinition(
XmlElementNames.ChildFolderCount,
FieldUris.ChildFolderCount,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the DisplayName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition DisplayName =
new StringPropertyDefinition(
XmlElementNames.DisplayName,
FieldUris.DisplayName,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the UnreadCount property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition UnreadCount =
new IntPropertyDefinition(
XmlElementNames.UnreadCount,
FieldUris.UnreadCount,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the TotalCount property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition TotalCount =
new IntPropertyDefinition(
XmlElementNames.TotalCount,
FieldUris.TotalCount,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the ManagedFolderInformation property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ManagedFolderInformation =
new ComplexPropertyDefinition<ManagedFolderInformation>(
XmlElementNames.ManagedFolderInformation,
FieldUris.ManagedFolderInformation,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1,
delegate() { return new ManagedFolderInformation(); });
/// <summary>
/// Defines the EffectiveRights property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition EffectiveRights =
new EffectiveRightsPropertyDefinition(
XmlElementNames.EffectiveRights,
FieldUris.EffectiveRights,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the Permissions property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition Permissions =
new PermissionSetPropertyDefinition(
XmlElementNames.PermissionSet,
FieldUris.PermissionSet,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.MustBeExplicitlyLoaded,
ExchangeVersion.Exchange2007_SP1);
/// <summary>
/// Defines the WellKnownFolderName property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition WellKnownFolderName =
new GenericPropertyDefinition<WellKnownFolderName>(
XmlElementNames.DistinguishedFolderId,
FieldUris.DistinguishedFolderId,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013,
true);
/// <summary>
/// Defines the PolicyTag property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition PolicyTag =
new ComplexPropertyDefinition<PolicyTag>(
XmlElementNames.PolicyTag,
FieldUris.PolicyTag,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013,
delegate() { return new PolicyTag(); });
/// <summary>
/// Defines the ArchiveTag property.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")]
public static readonly PropertyDefinition ArchiveTag =
new ComplexPropertyDefinition<ArchiveTag>(
XmlElementNames.ArchiveTag,
FieldUris.ArchiveTag,
PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013,
delegate() { return new ArchiveTag(); });
// This must be declared after the property definitions
internal static readonly FolderSchema Instance = new FolderSchema();
/// <summary>
/// Registers properties.
/// </summary>
/// <remarks>
/// IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd)
/// </remarks>
internal override void RegisterProperties()
{
base.RegisterProperties();
this.RegisterProperty(Id);
this.RegisterProperty(ParentFolderId);
this.RegisterProperty(FolderClass);
this.RegisterProperty(DisplayName);
this.RegisterProperty(TotalCount);
this.RegisterProperty(ChildFolderCount);
this.RegisterProperty(ServiceObjectSchema.ExtendedProperties);
this.RegisterProperty(ManagedFolderInformation);
this.RegisterProperty(EffectiveRights);
this.RegisterProperty(Permissions);
this.RegisterProperty(UnreadCount);
this.RegisterProperty(WellKnownFolderName);
this.RegisterProperty(PolicyTag);
this.RegisterProperty(ArchiveTag);
}
}
}
| |
using J2N.Collections;
using Lucene.Net.Attributes;
using NUnit.Framework;
using System;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
[TestFixture]
public class TestOpenBitSet : BaseDocIdSetTestCase<OpenBitSet>
{
public override OpenBitSet CopyOf(BitSet bs, int length)
{
OpenBitSet set = new OpenBitSet(length);
for (int doc = bs.NextSetBit(0); doc != -1; doc = bs.NextSetBit(doc + 1))
{
set.Set(doc);
}
return set;
}
internal virtual void DoGet(BitSet a, OpenBitSet b)
{
int max = a.Length;
for (int i = 0; i < max; i++)
{
if (a.Get(i) != b.Get(i))
{
Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.Get(i));
}
if (a.Get(i) != b.Get((long)i))
{
Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.Get(i));
}
}
}
internal virtual void DoGetFast(BitSet a, OpenBitSet b, int max)
{
for (int i = 0; i < max; i++)
{
if (a.Get(i) != b.FastGet(i))
{
Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.Get(i));
}
if (a.Get(i) != b.FastGet((long)i))
{
Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.Get(i));
}
}
}
internal virtual void DoNextSetBit(BitSet a, OpenBitSet b)
{
int aa = -1, bb = -1;
do
{
aa = a.NextSetBit(aa + 1);
bb = b.NextSetBit(bb + 1);
Assert.AreEqual(aa, bb);
} while (aa >= 0);
}
internal virtual void DoNextSetBitLong(BitSet a, OpenBitSet b)
{
int aa = -1, bb = -1;
do
{
aa = a.NextSetBit(aa + 1);
bb = (int)b.NextSetBit((long)(bb + 1));
Assert.AreEqual(aa, bb);
} while (aa >= 0);
}
internal virtual void DoPrevSetBit(BitSet a, OpenBitSet b)
{
int aa = a.Length + Random.Next(100);
int bb = aa;
do
{
// aa = a.PrevSetBit(aa-1);
aa--;
while ((aa >= 0) && (!a.Get(aa)))
{
aa--;
}
bb = b.PrevSetBit(bb - 1);
Assert.AreEqual(aa, bb);
} while (aa >= 0);
}
internal virtual void DoPrevSetBitLong(BitSet a, OpenBitSet b)
{
int aa = a.Length + Random.Next(100);
int bb = aa;
do
{
// aa = a.PrevSetBit(aa-1);
aa--;
while ((aa >= 0) && (!a.Get(aa)))
{
aa--;
}
bb = (int)b.PrevSetBit((long)(bb - 1));
Assert.AreEqual(aa, bb);
} while (aa >= 0);
}
// test interleaving different OpenBitSetIterator.Next()/skipTo()
internal virtual void DoIterate(BitSet a, OpenBitSet b, int mode)
{
if (mode == 1)
{
DoIterate1(a, b);
}
if (mode == 2)
{
DoIterate2(a, b);
}
}
internal virtual void DoIterate1(BitSet a, OpenBitSet b)
{
int aa = -1, bb = -1;
OpenBitSetIterator iterator = new OpenBitSetIterator(b);
do
{
aa = a.NextSetBit(aa + 1);
bb = Random.NextBoolean() ? iterator.NextDoc() : iterator.Advance(bb + 1);
Assert.AreEqual(aa == -1 ? DocIdSetIterator.NO_MORE_DOCS : aa, bb);
} while (aa >= 0);
}
internal virtual void DoIterate2(BitSet a, OpenBitSet b)
{
int aa = -1, bb = -1;
OpenBitSetIterator iterator = new OpenBitSetIterator(b);
do
{
aa = a.NextSetBit(aa + 1);
bb = Random.NextBoolean() ? iterator.NextDoc() : iterator.Advance(bb + 1);
Assert.AreEqual(aa == -1 ? DocIdSetIterator.NO_MORE_DOCS : aa, bb);
} while (aa >= 0);
}
internal virtual void DoRandomSets(int maxSize, int iter, int mode)
{
BitSet a0 = null;
OpenBitSet b0 = null;
for (int i = 0; i < iter; i++)
{
int sz = Random.Next(maxSize);
BitSet a = new BitSet(sz);
OpenBitSet b = new OpenBitSet(sz);
// test the various ways of setting bits
if (sz > 0)
{
int nOper = Random.Next(sz);
for (int j = 0; j < nOper; j++)
{
int idx;
idx = Random.Next(sz);
a.Set(idx, true);
b.FastSet(idx);
idx = Random.Next(sz);
a.Set(idx, true);
b.FastSet((long)idx);
idx = Random.Next(sz);
a.Set(idx, false);
b.FastClear(idx);
idx = Random.Next(sz);
a.Set(idx, false);
b.FastClear((long)idx);
idx = Random.Next(sz);
a.Set(idx, !a.Get(idx));
b.FastFlip(idx);
bool val = b.FlipAndGet(idx);
bool val2 = b.FlipAndGet(idx);
Assert.IsTrue(val != val2);
idx = Random.Next(sz);
a.Set(idx, !a.Get(idx));
b.FastFlip((long)idx);
val = b.FlipAndGet((long)idx);
val2 = b.FlipAndGet((long)idx);
Assert.IsTrue(val != val2);
val = b.GetAndSet(idx);
Assert.IsTrue(val2 == val);
Assert.IsTrue(b.Get(idx));
if (!val)
{
b.FastClear(idx);
}
Assert.IsTrue(b.Get(idx) == val);
}
}
// test that the various ways of accessing the bits are equivalent
DoGet(a, b);
DoGetFast(a, b, sz);
// test ranges, including possible extension
int fromIndex, toIndex;
fromIndex = Random.Next(sz + 80);
toIndex = fromIndex + Random.Next((sz >> 1) + 1);
BitSet aa = (BitSet)a.Clone();
aa.Flip(fromIndex, toIndex);
OpenBitSet bb = (OpenBitSet)b.Clone();
bb.Flip(fromIndex, toIndex);
DoIterate(aa, bb, mode); // a problem here is from flip or doIterate
fromIndex = Random.Next(sz + 80);
toIndex = fromIndex + Random.Next((sz >> 1) + 1);
aa = (BitSet)a.Clone();
aa.Clear(fromIndex, toIndex);
bb = (OpenBitSet)b.Clone();
bb.Clear(fromIndex, toIndex);
DoNextSetBit(aa, bb); // a problem here is from clear() or nextSetBit
DoNextSetBitLong(aa, bb);
DoPrevSetBit(aa, bb);
DoPrevSetBitLong(aa, bb);
fromIndex = Random.Next(sz + 80);
toIndex = fromIndex + Random.Next((sz >> 1) + 1);
aa = (BitSet)a.Clone();
aa.Set(fromIndex, toIndex);
bb = (OpenBitSet)b.Clone();
bb.Set(fromIndex, toIndex);
DoNextSetBit(aa, bb); // a problem here is from set() or nextSetBit
DoNextSetBitLong(aa, bb);
DoPrevSetBit(aa, bb);
DoPrevSetBitLong(aa, bb);
if (a0 != null)
{
Assert.AreEqual(a.Equals(a0), b.Equals(b0));
Assert.AreEqual(a.Cardinality, b.Cardinality());
BitSet a_and = (BitSet)a.Clone();
a_and.And(a0);
BitSet a_or = (BitSet)a.Clone();
a_or.Or(a0);
BitSet a_xor = (BitSet)a.Clone();
a_xor.Xor(a0);
BitSet a_andn = (BitSet)a.Clone();
a_andn.AndNot(a0);
OpenBitSet b_and = (OpenBitSet)b.Clone();
Assert.AreEqual(b, b_and);
b_and.And(b0);
OpenBitSet b_or = (OpenBitSet)b.Clone();
b_or.Or(b0);
OpenBitSet b_xor = (OpenBitSet)b.Clone();
b_xor.Xor(b0);
OpenBitSet b_andn = (OpenBitSet)b.Clone();
b_andn.AndNot(b0);
DoIterate(a_and, b_and, mode);
DoIterate(a_or, b_or, mode);
DoIterate(a_xor, b_xor, mode);
DoIterate(a_andn, b_andn, mode);
Assert.AreEqual(a_and.Cardinality, b_and.Cardinality());
Assert.AreEqual(a_or.Cardinality, b_or.Cardinality());
Assert.AreEqual(a_xor.Cardinality, b_xor.Cardinality());
Assert.AreEqual(a_andn.Cardinality, b_andn.Cardinality());
// test non-mutating popcounts
Assert.AreEqual(b_and.Cardinality(), OpenBitSet.IntersectionCount(b, b0));
Assert.AreEqual(b_or.Cardinality(), OpenBitSet.UnionCount(b, b0));
Assert.AreEqual(b_xor.Cardinality(), OpenBitSet.XorCount(b, b0));
Assert.AreEqual(b_andn.Cardinality(), OpenBitSet.AndNotCount(b, b0));
}
a0 = a;
b0 = b;
}
}
// large enough to flush obvious bugs, small enough to run in <.5 sec as part of a
// larger testsuite.
[Test]
public virtual void TestSmall()
{
DoRandomSets(AtLeast(1200), AtLeast(1000), 1);
DoRandomSets(AtLeast(1200), AtLeast(1000), 2);
}
[Test, LuceneNetSpecific]
public void TestClearSmall()
{
OpenBitSet a = new OpenBitSet(30); // 0110010111001000101101001001110...0
int[] onesA = { 1, 2, 5, 7, 8, 9, 12, 16, 18, 19, 21, 24, 27, 28, 29 };
for (int i = 0; i < onesA.size(); i++)
{
a.Set(onesA[i]);
}
OpenBitSet b = new OpenBitSet(30); // 0110000001001000101101001001110...0
int[] onesB = { 1, 2, 9, 12, 16, 18, 19, 21, 24, 27, 28, 29 };
for (int i = 0; i < onesB.size(); i++)
{
b.Set(onesB[i]);
}
a.Clear(5, 9);
Assert.True(a.Equals(b));
a.Clear(9, 10);
Assert.False(a.Equals(b));
a.Set(9);
Assert.True(a.Equals(b));
}
[Test, LuceneNetSpecific]
public void TestClearLarge()
{
int iters = AtLeast(1000);
for (int it = 0; it < iters; it++)
{
Random random = new Random();
int sz = AtLeast(1200);
OpenBitSet a = new OpenBitSet(sz);
OpenBitSet b = new OpenBitSet(sz);
int from = random.Next(sz - 1);
int to = random.Next(from, sz);
for (int i = 0; i < sz / 2; i++)
{
int index = random.Next(sz - 1);
a.Set(index);
if (index < from || index >= to)
{
b.Set(index);
}
}
a.Clear(from, to);
Assert.True(a.Equals(b));
}
}
// uncomment to run a bigger test (~2 minutes).
/*
public void TestBig() {
doRandomSets(2000,200000, 1);
doRandomSets(2000,200000, 2);
}
*/
[Test]
public virtual void TestEquals()
{
OpenBitSet b1 = new OpenBitSet(1111);
OpenBitSet b2 = new OpenBitSet(2222);
Assert.IsTrue(b1.Equals(b2));
Assert.IsTrue(b2.Equals(b1));
b1.Set(10);
Assert.IsFalse(b1.Equals(b2));
Assert.IsFalse(b2.Equals(b1));
b2.Set(10);
Assert.IsTrue(b1.Equals(b2));
Assert.IsTrue(b2.Equals(b1));
b2.Set(2221);
Assert.IsFalse(b1.Equals(b2));
Assert.IsFalse(b2.Equals(b1));
b1.Set(2221);
Assert.IsTrue(b1.Equals(b2));
Assert.IsTrue(b2.Equals(b1));
// try different type of object
Assert.IsFalse(b1.Equals(new object()));
}
[Test]
public virtual void TestHashCodeEquals()
{
OpenBitSet bs1 = new OpenBitSet(200);
OpenBitSet bs2 = new OpenBitSet(64);
bs1.Set(3);
bs2.Set(3);
Assert.AreEqual(bs1, bs2);
Assert.AreEqual(bs1.GetHashCode(), bs2.GetHashCode());
}
private OpenBitSet MakeOpenBitSet(int[] a)
{
OpenBitSet bs = new OpenBitSet();
foreach (int e in a)
{
bs.Set(e);
}
return bs;
}
private BitSet MakeBitSet(int[] a)
{
BitSet bs = new BitSet(a.Length);
foreach (int e in a)
{
bs.Set(e);
}
return bs;
}
private void CheckPrevSetBitArray(int[] a)
{
OpenBitSet obs = MakeOpenBitSet(a);
BitSet bs = MakeBitSet(a);
DoPrevSetBit(bs, obs);
}
[Test]
public virtual void TestPrevSetBit()
{
CheckPrevSetBitArray(new int[] { });
CheckPrevSetBitArray(new int[] { 0 });
CheckPrevSetBitArray(new int[] { 0, 2 });
}
[Test]
public virtual void TestEnsureCapacity()
{
OpenBitSet bits = new OpenBitSet(1);
int bit = Random.Next(100) + 10;
bits.EnsureCapacity(bit); // make room for more bits
bits.FastSet(bit - 1);
Assert.IsTrue(bits.FastGet(bit - 1));
bits.EnsureCapacity(bit + 1);
bits.FastSet(bit);
Assert.IsTrue(bits.FastGet(bit));
bits.EnsureCapacity(3); // should not change numBits nor grow the array
bits.FastSet(3);
Assert.IsTrue(bits.FastGet(3));
bits.FastSet(bit - 1);
Assert.IsTrue(bits.FastGet(bit - 1));
// test ensureCapacityWords
int numWords = Random.Next(10) + 2; // make sure we grow the array (at least 128 bits)
bits.EnsureCapacityWords(numWords);
bit = TestUtil.NextInt32(Random, 127, (numWords << 6) - 1); // pick a bit >= to 128, but still within range
bits.FastSet(bit);
Assert.IsTrue(bits.FastGet(bit));
bits.FastClear(bit);
Assert.IsFalse(bits.FastGet(bit));
bits.FastFlip(bit);
Assert.IsTrue(bits.FastGet(bit));
bits.EnsureCapacityWords(2); // should not change numBits nor grow the array
bits.FastSet(3);
Assert.IsTrue(bits.FastGet(3));
bits.FastSet(bit - 1);
Assert.IsTrue(bits.FastGet(bit - 1));
}
[Test, LuceneNetSpecific] // https://github.com/apache/lucenenet/pull/154
public virtual void TestXorWithDifferentCapacity()
{
OpenBitSet smaller = new OpenBitSet(2);
OpenBitSet larger = new OpenBitSet(64 * 10000);
larger.Set(64 * 10000 - 1);
larger.Set(65);
larger.Set(3);
smaller.Set(3);
smaller.Set(66);
smaller.Xor(larger);
Assert.IsTrue(smaller.Get(64 * 10000 - 1));
Assert.IsTrue(smaller.Get(65));
Assert.IsFalse(smaller.Get(3));
Assert.IsTrue(smaller.Get(66));
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
internal class VS2005DockPaneCaption : DockPaneCaptionBase
{
private sealed class InertButton : InertButtonBase
{
private Bitmap m_image, m_imageAutoHide;
public InertButton(VS2005DockPaneCaption dockPaneCaption, Bitmap image, Bitmap imageAutoHide)
: base()
{
m_dockPaneCaption = dockPaneCaption;
m_image = image;
m_imageAutoHide = imageAutoHide;
RefreshChanges();
}
private VS2005DockPaneCaption m_dockPaneCaption;
private VS2005DockPaneCaption DockPaneCaption
{
get { return m_dockPaneCaption; }
}
public bool IsAutoHide
{
get { return DockPaneCaption.DockPane.IsAutoHide; }
}
public override Bitmap Image
{
get { return IsAutoHide ? m_imageAutoHide : m_image; }
}
protected override void OnRefreshChanges()
{
if (DockPaneCaption.DockPane.DockPanel != null)
{
if (DockPaneCaption.TextColor != ForeColor)
{
ForeColor = DockPaneCaption.TextColor;
Invalidate();
}
}
}
}
#region consts
private const int _TextGapTop = 2;
private const int _TextGapBottom = 0;
private const int _TextGapLeft = 3;
private const int _TextGapRight = 3;
private const int _ButtonGapTop = 2;
private const int _ButtonGapBottom = 1;
private const int _ButtonGapBetween = 1;
private const int _ButtonGapLeft = 1;
private const int _ButtonGapRight = 2;
#endregion
private static Bitmap _imageButtonClose;
private static Bitmap ImageButtonClose
{
get
{
if (_imageButtonClose == null)
_imageButtonClose = Resources.DockPane_Close;
return _imageButtonClose;
}
}
private InertButton m_buttonClose;
private InertButton ButtonClose
{
get
{
if (m_buttonClose == null)
{
m_buttonClose = new InertButton(this, ImageButtonClose, ImageButtonClose);
m_toolTip.SetToolTip(m_buttonClose, ToolTipClose);
m_buttonClose.Click += new EventHandler(Close_Click);
Controls.Add(m_buttonClose);
}
return m_buttonClose;
}
}
private static Bitmap _imageButtonAutoHide;
private static Bitmap ImageButtonAutoHide
{
get
{
if (_imageButtonAutoHide == null)
_imageButtonAutoHide = Resources.DockPane_AutoHide;
return _imageButtonAutoHide;
}
}
private static Bitmap _imageButtonDock;
private static Bitmap ImageButtonDock
{
get
{
if (_imageButtonDock == null)
_imageButtonDock = Resources.DockPane_Dock;
return _imageButtonDock;
}
}
private InertButton m_buttonAutoHide;
private InertButton ButtonAutoHide
{
get
{
if (m_buttonAutoHide == null)
{
m_buttonAutoHide = new InertButton(this, ImageButtonDock, ImageButtonAutoHide);
m_toolTip.SetToolTip(m_buttonAutoHide, ToolTipAutoHide);
m_buttonAutoHide.Click += new EventHandler(AutoHide_Click);
Controls.Add(m_buttonAutoHide);
}
return m_buttonAutoHide;
}
}
private static Bitmap _imageButtonOptions;
private static Bitmap ImageButtonOptions
{
get
{
if (_imageButtonOptions == null)
_imageButtonOptions = Resources.DockPane_Option;
return _imageButtonOptions;
}
}
private InertButton m_buttonOptions;
private InertButton ButtonOptions
{
get
{
if (m_buttonOptions == null)
{
m_buttonOptions = new InertButton(this, ImageButtonOptions, ImageButtonOptions);
m_toolTip.SetToolTip(m_buttonOptions, ToolTipOptions);
m_buttonOptions.Click += new EventHandler(Options_Click);
Controls.Add(m_buttonOptions);
}
return m_buttonOptions;
}
}
private IContainer m_components;
private IContainer Components
{
get { return m_components; }
}
private ToolTip m_toolTip;
public VS2005DockPaneCaption(DockPane pane) : base(pane)
{
SuspendLayout();
m_components = new Container();
m_toolTip = new ToolTip(Components);
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
Components.Dispose();
base.Dispose(disposing);
}
private static int TextGapTop
{
get { return _TextGapTop; }
}
public Font TextFont
{
get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; }
}
private static int TextGapBottom
{
get { return _TextGapBottom; }
}
private static int TextGapLeft
{
get { return _TextGapLeft; }
}
private static int TextGapRight
{
get { return _TextGapRight; }
}
private static int ButtonGapTop
{
get { return _ButtonGapTop; }
}
private static int ButtonGapBottom
{
get { return _ButtonGapBottom; }
}
private static int ButtonGapLeft
{
get { return _ButtonGapLeft; }
}
private static int ButtonGapRight
{
get { return _ButtonGapRight; }
}
private static int ButtonGapBetween
{
get { return _ButtonGapBetween; }
}
private static string _toolTipClose;
private static string ToolTipClose
{
get
{
if (_toolTipClose == null)
_toolTipClose = Strings.DockPaneCaption_ToolTipClose;
return _toolTipClose;
}
}
private static string _toolTipOptions;
private static string ToolTipOptions
{
get
{
if (_toolTipOptions == null)
_toolTipOptions = Strings.DockPaneCaption_ToolTipOptions;
return _toolTipOptions;
}
}
private static string _toolTipAutoHide;
private static string ToolTipAutoHide
{
get
{
if (_toolTipAutoHide == null)
_toolTipAutoHide = Strings.DockPaneCaption_ToolTipAutoHide;
return _toolTipAutoHide;
}
}
private static Blend _activeBackColorGradientBlend;
private static Blend ActiveBackColorGradientBlend
{
get
{
if (_activeBackColorGradientBlend == null)
{
Blend blend = new Blend(2);
blend.Factors = new float[]{0.5F, 1.0F};
blend.Positions = new float[]{0.0F, 1.0F};
_activeBackColorGradientBlend = blend;
}
return _activeBackColorGradientBlend;
}
}
private Color TextColor
{
get
{
if (DockPane.IsActivated)
return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor;
else
return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor;
}
}
private static TextFormatFlags _textFormat =
TextFormatFlags.SingleLine |
TextFormatFlags.EndEllipsis |
TextFormatFlags.VerticalCenter;
private TextFormatFlags TextFormat
{
get
{
if (RightToLeft == RightToLeft.No)
return _textFormat;
else
return _textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right;
}
}
protected internal override int MeasureHeight()
{
int height = TextFont.Height + TextGapTop + TextGapBottom;
if (height < ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom)
height = ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom;
return height;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint (e);
DrawCaption(e.Graphics);
}
private void DrawCaption(Graphics g)
{
if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0)
return;
if (DockPane.IsActivated)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode))
{
brush.Blend = ActiveBackColorGradientBlend;
g.FillRectangle(brush, ClientRectangle);
}
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode))
{
g.FillRectangle(brush, ClientRectangle);
}
}
Rectangle rectCaption = ClientRectangle;
Rectangle rectCaptionText = rectCaption;
rectCaptionText.X += TextGapLeft;
rectCaptionText.Width -= TextGapLeft + TextGapRight;
rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight;
if (ShouldShowAutoHideButton)
rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween;
if (HasTabPageContextMenu)
rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween;
rectCaptionText.Y += TextGapTop;
rectCaptionText.Height -= TextGapTop + TextGapBottom;
Color colorText;
if (DockPane.IsActivated)
colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor;
else
colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor;
TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, DrawHelper.RtlTransform(this, rectCaptionText), colorText, TextFormat);
}
protected override void OnLayout(LayoutEventArgs levent)
{
SetButtonsPosition();
base.OnLayout (levent);
}
protected override void OnRefreshChanges()
{
SetButtons();
Invalidate();
}
private bool CloseButtonEnabled
{
get { return (DockPane.ActiveContent != null)? DockPane.ActiveContent.DockHandler.CloseButton : false; }
}
/// <summary>
/// Determines whether the close button is visible on the content
/// </summary>
private bool CloseButtonVisible
{
get { return (DockPane.ActiveContent != null) ? DockPane.ActiveContent.DockHandler.CloseButtonVisible : false; }
}
private bool ShouldShowAutoHideButton
{
get { return !DockPane.IsFloat; }
}
private void SetButtons()
{
ButtonClose.Enabled = CloseButtonEnabled;
ButtonClose.Visible = CloseButtonVisible;
ButtonAutoHide.Visible = ShouldShowAutoHideButton;
ButtonOptions.Visible = HasTabPageContextMenu;
ButtonClose.RefreshChanges();
ButtonAutoHide.RefreshChanges();
ButtonOptions.RefreshChanges();
SetButtonsPosition();
}
private void SetButtonsPosition()
{
// set the size and location for close and auto-hide buttons
Rectangle rectCaption = ClientRectangle;
int buttonWidth = ButtonClose.Image.Width;
int buttonHeight = ButtonClose.Image.Height;
int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom;
if (buttonHeight < height)
{
buttonWidth = buttonWidth * (height / buttonHeight);
buttonHeight = height;
}
Size buttonSize = new Size(buttonWidth, buttonHeight);
int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width;
int y = rectCaption.Y + ButtonGapTop;
Point point = new Point(x, y);
ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
// If the close button is not visible draw the auto hide button overtop.
// Otherwise it is drawn to the left of the close button.
if (CloseButtonVisible)
point.Offset(-(buttonWidth + ButtonGapBetween), 0);
ButtonAutoHide.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
if (ShouldShowAutoHideButton)
point.Offset(-(buttonWidth + ButtonGapBetween), 0);
ButtonOptions.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
}
private void Close_Click(object sender, EventArgs e)
{
DockPane.CloseActiveContent();
}
private void AutoHide_Click(object sender, EventArgs e)
{
DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState);
if (DockHelper.IsDockStateAutoHide(DockPane.DockState))
{
DockPane.DockPanel.ActiveAutoHideContent = null;
DockPane.NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(DockPane);
}
}
private void Options_Click(object sender, EventArgs e)
{
ShowTabPageContextMenu(PointToClient(Control.MousePosition));
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
PerformLayout();
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXWSMTGS
{
using System;
using System.Xml.XPath;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// The adapter class of IMS_OXWSMTGSAdapter.
/// </summary>
public partial class MS_OXWSMTGSAdapter : ManagedAdapterBase, IMS_OXWSMTGSAdapter
{
#region Fields
/// <summary>
/// The exchange service binding.
/// </summary>
private ExchangeServiceBinding exchangeServiceBinding;
/// <summary>
/// The user name used to access web service.
/// </summary>
private string username;
/// <summary>
/// The password for username used to access web service.
/// </summary>
private string password;
/// <summary>
/// The domain of server.
/// </summary>
private string domain;
/// <summary>
/// The endpoint url of Exchange Web Service.
/// </summary>
private string url;
#endregion
#region IMS_OXWSMTGSAdapter Properties
/// <summary>
/// Gets the raw XML request sent to protocol SUT
/// </summary>
public IXPathNavigable LastRawRequestXml
{
get { return this.exchangeServiceBinding.LastRawRequestXml; }
}
/// <summary>
/// Gets the raw XML response received from protocol SUT
/// </summary>
public IXPathNavigable LastRawResponseXml
{
get { return this.exchangeServiceBinding.LastRawResponseXml; }
}
#endregion
#region Initialize TestSuite
/// <summary>
/// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite.
/// </summary>
/// <param name="testSite">Pass ITestSite to adapter, make adapter can use ITestSite's function.</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
Site.DefaultProtocolDocShortName = "MS-OXWSMTGS";
Common.MergeConfiguration(testSite);
this.username = Common.GetConfigurationPropertyValue("OrganizerName", this.Site);
this.password = Common.GetConfigurationPropertyValue("OrganizerPassword", this.Site);
this.domain = Common.GetConfigurationPropertyValue("Domain", this.Site);
this.url = Common.GetConfigurationPropertyValue("ServiceUrl", this.Site);
this.exchangeServiceBinding = new ExchangeServiceBinding(this.url, this.username, this.password, this.domain, this.Site);
Common.InitializeServiceBinding(this.exchangeServiceBinding, this.Site);
}
#endregion
#region IMS_OXWSMTGSAdapter Operations
/// <summary>
/// Get the calendar related item elements.
/// </summary>
/// <param name="request">A request to the GetReminder operation.</param>
/// <returns>The response message returned by GetReminder operation.</returns>
public GetRemindersResponseMessageType GetReminders(GetRemindersType request)
{
if (request == null)
{
throw new ArgumentException("The request of operation 'GetReminders' should not be null.");
}
GetRemindersResponseMessageType getRemindersResponse = this.exchangeServiceBinding.GetReminders(request);
Site.Assert.IsNotNull(getRemindersResponse, "If the operation is successful, the response should not be null.");
this.VerifySoapVersion();
this.VerifyTransportType();
this.VerifyGetReminderResponseMessageType(getRemindersResponse, this.exchangeServiceBinding.IsSchemaValidated);
return getRemindersResponse;
}
/// <summary>
/// Get the calendar related item elements.
/// </summary>
/// <param name="request">A request to the PerformReminderAction operation.</param>
/// <returns>The response message returned by PerformReminderAction operation.</returns>
public PerformReminderActionResponseMessageType PerformReminderAction(PerformReminderActionType request)
{
if (request == null)
{
throw new ArgumentException("The request of operation 'PerformReminderAction' should not be null.");
}
PerformReminderActionResponseMessageType performReminderActionResponse = this.exchangeServiceBinding.PerformReminderAction(request);
Site.Assert.IsNotNull(performReminderActionResponse, "If the operation is successful, the response should not be null.");
this.VerifySoapVersion();
this.VerifyTransportType();
this.VerifyPerformReminderActionResponseMessageType(performReminderActionResponse, this.exchangeServiceBinding.IsSchemaValidated);
return performReminderActionResponse;
}
/// <summary>
/// Get the calendar related item elements.
/// </summary>
/// <param name="request">A request to the GetItem operation.</param>
/// <returns>The response message returned by GetItem operation.</returns>
public GetItemResponseType GetItem(GetItemType request)
{
if (request == null)
{
throw new ArgumentException("The request of operation 'GetItem' should not be null.");
}
GetItemResponseType getItemResponse = this.exchangeServiceBinding.GetItem(request);
Site.Assert.IsNotNull(getItemResponse, "If the operation is successful, the response should not be null.");
this.VerifySoapVersion();
this.VerifyTransportType();
this.VerifyGetItemOperation(getItemResponse, this.exchangeServiceBinding.IsSchemaValidated);
return getItemResponse;
}
/// <summary>
/// Delete the calendar related item elements.
/// </summary>
/// <param name="request">A request to the DeleteItem operation.</param>
/// <returns>The response message returned by DeleteItem operation.</returns>
public DeleteItemResponseType DeleteItem(DeleteItemType request)
{
if (request == null)
{
throw new ArgumentException("The request of operation 'DeleteItem' should not be null.");
}
DeleteItemResponseType deleteItemResponse = this.exchangeServiceBinding.DeleteItem(request);
this.VerifySoapVersion();
this.VerifyTransportType();
this.VerifyDeleteItemOperation(this.exchangeServiceBinding.IsSchemaValidated);
return deleteItemResponse;
}
/// <summary>
/// Update the calendar related item elements.
/// </summary>
/// <param name="request">A request to the UpdateItem operation.</param>
/// <returns>The response message returned by UpdateItem operation.</returns>
public UpdateItemResponseType UpdateItem(UpdateItemType request)
{
if (request == null)
{
throw new ArgumentException("The request of operation 'UpdateItem' should not be null.");
}
UpdateItemResponseType updateItemResponse = this.exchangeServiceBinding.UpdateItem(request);
Site.Assert.IsNotNull(updateItemResponse, "If the operation is successful, the response should not be null.");
this.VerifySoapVersion();
this.VerifyTransportType();
this.VerifyUpdateItemOperation(updateItemResponse, this.exchangeServiceBinding.IsSchemaValidated);
return updateItemResponse;
}
/// <summary>
/// Move the calendar related item elements.
/// </summary>
/// <param name="request">A request to the MoveItem operation.</param>
/// <returns>The response message returned by MoveItem operation.</returns>
public MoveItemResponseType MoveItem(MoveItemType request)
{
if (request == null)
{
throw new ArgumentException("The request of operation 'MoveItem' should not be null.");
}
MoveItemResponseType moveItemResponse = this.exchangeServiceBinding.MoveItem(request);
Site.Assert.IsNotNull(moveItemResponse, "If the operation is successful, the response should not be null.");
this.VerifySoapVersion();
this.VerifyTransportType();
this.VerifyMoveItemOperation(moveItemResponse, this.exchangeServiceBinding.IsSchemaValidated);
return moveItemResponse;
}
/// <summary>
/// Copy the calendar related item elements.
/// </summary>
/// <param name="request">A request to the CopyItem operation.</param>
/// <returns>The response message returned by CopyItem operation.</returns>
public CopyItemResponseType CopyItem(CopyItemType request)
{
if (request == null)
{
throw new ArgumentException("The request of operation 'CopyItem' should not be null.");
}
CopyItemResponseType copyItemResponse = this.exchangeServiceBinding.CopyItem(request);
Site.Assert.IsNotNull(copyItemResponse, "If the operation is successful, the response should not be null.");
this.VerifySoapVersion();
this.VerifyTransportType();
this.VerifyCopyItemOperation(copyItemResponse, this.exchangeServiceBinding.IsSchemaValidated);
return copyItemResponse;
}
/// <summary>
/// Create the calendar related item elements.
/// </summary>
/// <param name="request">A request to the CreateItem operation.</param>
/// <returns>The response message returned by CreateItem operation.</returns>
public CreateItemResponseType CreateItem(CreateItemType request)
{
if (request == null)
{
throw new ArgumentException("The request of operation 'CreateItem' should not be null.");
}
CreateItemResponseType createItemResponse = this.exchangeServiceBinding.CreateItem(request);
Site.Assert.IsNotNull(createItemResponse, "If the operation is successful, the response should not be null.");
this.VerifySoapVersion();
this.VerifyTransportType();
this.VerifyCreateItemOperation(createItemResponse, this.exchangeServiceBinding.IsSchemaValidated);
return createItemResponse;
}
/// <summary>
/// Switch the current user to the new one, with the identity of the new user to communicate with Exchange Web Service.
/// </summary>
/// <param name="userName">The name of a user</param>
/// <param name="userPassword">The password of a user</param>
/// <param name="userDomain">The domain, in which a user is</param>
public void SwitchUser(string userName, string userPassword, string userDomain)
{
this.username = userName;
this.password = userPassword;
this.domain = userDomain;
this.exchangeServiceBinding.Credentials = new System.Net.NetworkCredential(this.username, this.password, this.domain);
}
#endregion
}
}
| |
using System;
using System.Linq;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Common;
using Nop.Services.Directory;
using Nop.Services.Events;
namespace Nop.Services.Common
{
/// <summary>
/// Address service
/// </summary>
public partial class AddressService : IAddressService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : address ID
/// </remarks>
private const string ADDRESSES_BY_ID_KEY = "Nop.address.id-{0}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string ADDRESSES_PATTERN_KEY = "Nop.address.";
#endregion
#region Fields
private readonly IRepository<Address> _addressRepository;
private readonly ICountryService _countryService;
private readonly IStateProvinceService _stateProvinceService;
private readonly IAddressAttributeService _addressAttributeService;
private readonly IEventPublisher _eventPublisher;
private readonly AddressSettings _addressSettings;
private readonly ICacheManager _cacheManager;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="addressRepository">Address repository</param>
/// <param name="countryService">Country service</param>
/// <param name="stateProvinceService">State/province service</param>
/// <param name="addressAttributeService">Address attribute service</param>
/// <param name="eventPublisher">Event publisher</param>
/// <param name="addressSettings">Address settings</param>
public AddressService(ICacheManager cacheManager,
IRepository<Address> addressRepository,
ICountryService countryService,
IStateProvinceService stateProvinceService,
IAddressAttributeService addressAttributeService,
IEventPublisher eventPublisher,
AddressSettings addressSettings)
{
this._cacheManager = cacheManager;
this._addressRepository = addressRepository;
this._countryService = countryService;
this._stateProvinceService = stateProvinceService;
this._addressAttributeService = addressAttributeService;
this._eventPublisher = eventPublisher;
this._addressSettings = addressSettings;
}
#endregion
#region Methods
/// <summary>
/// Deletes an address
/// </summary>
/// <param name="address">Address</param>
public virtual void DeleteAddress(Address address)
{
if (address == null)
throw new ArgumentNullException("address");
_addressRepository.Delete(address);
//cache
_cacheManager.RemoveByPattern(ADDRESSES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(address);
}
/// <summary>
/// Gets total number of addresses by country identifier
/// </summary>
/// <param name="countryId">Country identifier</param>
/// <returns>Number of addresses</returns>
public virtual int GetAddressTotalByCountryId(int countryId)
{
if (countryId == 0)
return 0;
var query = from a in _addressRepository.Table
where a.CountryId == countryId
select a;
return query.Count();
}
/// <summary>
/// Gets total number of addresses by state/province identifier
/// </summary>
/// <param name="stateProvinceId">State/province identifier</param>
/// <returns>Number of addresses</returns>
public virtual int GetAddressTotalByStateProvinceId(int stateProvinceId)
{
if (stateProvinceId == 0)
return 0;
var query = from a in _addressRepository.Table
where a.StateProvinceId == stateProvinceId
select a;
return query.Count();
}
/// <summary>
/// Gets an address by address identifier
/// </summary>
/// <param name="addressId">Address identifier</param>
/// <returns>Address</returns>
public virtual Address GetAddressById(int addressId)
{
if (addressId == 0)
return null;
string key = string.Format(ADDRESSES_BY_ID_KEY, addressId);
return _cacheManager.Get(key, () => _addressRepository.GetById(addressId));
}
/// <summary>
/// Inserts an address
/// </summary>
/// <param name="address">Address</param>
public virtual void InsertAddress(Address address)
{
if (address == null)
throw new ArgumentNullException("address");
address.CreatedOnUtc = DateTime.UtcNow;
//some validation
if (address.CountryId == 0)
address.CountryId = null;
if (address.StateProvinceId == 0)
address.StateProvinceId = null;
_addressRepository.Insert(address);
//cache
_cacheManager.RemoveByPattern(ADDRESSES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(address);
}
/// <summary>
/// Updates the address
/// </summary>
/// <param name="address">Address</param>
public virtual void UpdateAddress(Address address)
{
if (address == null)
throw new ArgumentNullException("address");
//some validation
if (address.CountryId == 0)
address.CountryId = null;
if (address.StateProvinceId == 0)
address.StateProvinceId = null;
_addressRepository.Update(address);
//cache
_cacheManager.RemoveByPattern(ADDRESSES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(address);
}
/// <summary>
/// Gets a value indicating whether address is valid (can be saved)
/// </summary>
/// <param name="address">Address to validate</param>
/// <returns>Result</returns>
public virtual bool IsAddressValid(Address address)
{
if (address == null)
throw new ArgumentNullException("address");
if (String.IsNullOrWhiteSpace(address.FirstName))
return false;
if (String.IsNullOrWhiteSpace(address.LastName))
return false;
if (String.IsNullOrWhiteSpace(address.Email))
return false;
if (_addressSettings.CompanyEnabled &&
_addressSettings.CompanyRequired &&
String.IsNullOrWhiteSpace(address.Company))
return false;
if (_addressSettings.StreetAddressEnabled &&
_addressSettings.StreetAddressRequired &&
String.IsNullOrWhiteSpace(address.Address1))
return false;
if (_addressSettings.StreetAddress2Enabled &&
_addressSettings.StreetAddress2Required &&
String.IsNullOrWhiteSpace(address.Address2))
return false;
if (_addressSettings.ZipPostalCodeEnabled &&
_addressSettings.ZipPostalCodeRequired &&
String.IsNullOrWhiteSpace(address.ZipPostalCode))
return false;
if (_addressSettings.CountryEnabled)
{
if (address.CountryId == null || address.CountryId.Value == 0)
return false;
var country = _countryService.GetCountryById(address.CountryId.Value);
if (country == null)
return false;
if (_addressSettings.StateProvinceEnabled)
{
var states = _stateProvinceService.GetStateProvincesByCountryId(country.Id);
if (states.Count > 0)
{
if (address.StateProvinceId == null || address.StateProvinceId.Value == 0)
return false;
var state = states.FirstOrDefault(x => x.Id == address.StateProvinceId.Value);
if (state == null)
return false;
}
}
}
if (_addressSettings.CityEnabled &&
_addressSettings.CityRequired &&
String.IsNullOrWhiteSpace(address.City))
return false;
if (_addressSettings.PhoneEnabled &&
_addressSettings.PhoneRequired &&
String.IsNullOrWhiteSpace(address.PhoneNumber))
return false;
if (_addressSettings.FaxEnabled &&
_addressSettings.FaxRequired &&
String.IsNullOrWhiteSpace(address.FaxNumber))
return false;
var attributes = _addressAttributeService.GetAllAddressAttributes();
if (attributes.Any(x => x.IsRequired))
return false;
return true;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Events;
namespace ExtendedLibrary.Events
{
[Serializable]
public partial class ExtendedEvent : ISerializationCallbackReceiver
{
[HideInInspector]
[SerializeField]
protected List<Listener> listeners;
[HideInInspector]
[SerializeField]
protected string returnTypeName = string.Empty;
protected readonly List<ExtendedDelegate> callbacks = new List<ExtendedDelegate>();
private readonly List<object> results = new List<object>();
public bool IsEmpty
{
get
{
return this.listeners.Count <= 0 && (this.callbacks == null || this.callbacks.Count <= 0);
}
}
public void Invoke()
{
for (var i = 0; i < this.listeners.Count; ++i)
{
if (this.listeners[i] != null)
this.listeners[i].Invoke();
}
for (var i = 0; i < this.callbacks.Count; ++i)
{
if (this.callbacks[i] != null)
this.callbacks[i].Invoke();
}
}
public void Invoke(out object[] results)
{
this.results.Clear();
for (var i = 0; i < this.listeners.Count; ++i)
{
if (this.listeners[i] != null)
this.results.Add(this.listeners[i].Invoke());
}
for (var i = 0; i < this.callbacks.Count; ++i)
{
if (this.callbacks[i] != null)
this.results.Add(this.callbacks[i].Invoke());
}
results = this.results.ToArray();
}
public void Invoke(Action<object> resultReceiver)
{
if (resultReceiver == null)
{
Debug.LogWarning("Result receiver cannot be null.");
return;
}
for (var i = 0; i < this.listeners.Count; ++i)
{
if (this.listeners[i] != null)
resultReceiver(this.listeners[i].Invoke());
}
for (var i = 0; i < this.callbacks.Count; ++i)
{
if (this.callbacks[i] != null)
resultReceiver(this.callbacks[i].Invoke());
}
}
public void Invoke<T>(Func<object, T> resultReceiver)
{
if (resultReceiver == null)
{
Debug.LogWarning("Result receiver cannot be null.");
return;
}
for (var i = 0; i < this.listeners.Count; ++i)
{
if (this.listeners[i] != null)
resultReceiver(this.listeners[i].Invoke());
}
for (var i = 0; i < this.callbacks.Count; ++i)
{
if (this.callbacks[i] != null)
resultReceiver(this.callbacks[i].Invoke());
}
}
public void AddListeners(ExtendedEvent listeners)
{
if (listeners != null)
this.callbacks.AddRange(listeners.callbacks);
}
public void AddListeners(IEnumerable<ExtendedDelegate> listeners)
{
if (listeners != null)
this.callbacks.AddRange(listeners);
}
public void AddListener(ExtendedDelegate listener)
{
if (listener != null)
this.callbacks.Add(listener);
}
public void AddListener(Action callback)
{
AddListener(callback.ToExtendedDelegate());
}
public void AddListener<T>(Action<T> callback, T param)
{
AddListener(callback.ToExtendedDelegate(param));
}
public void AddListener<T1, T2>(Action<T1, T2> callback, T1 param1, T2 param2)
{
AddListener(callback.ToExtendedDelegate(param1, param2));
}
public void AddListener<T1, T2, T3>(Action<T1, T2, T3> callback, T1 param1, T2 param2, T3 param3)
{
AddListener(callback.ToExtendedDelegate(param1, param2, param3));
}
public void AddListener<T1, T2, T3, T4>(Action<T1, T2, T3, T4> callback, T1 param1, T2 param2, T3 param3, T4 param4)
{
AddListener(callback.ToExtendedDelegate(param1, param2, param3, param4));
}
public void AddListener<TResult>(Func<TResult> callback)
{
AddListener(callback.ToExtendedDelegate());
}
public void AddListener<T, TResult>(Func<T, TResult> callback, T param)
{
AddListener(callback.ToExtendedDelegate(param));
}
public void AddListener<T1, T2, TResult>(Func<T1, T2, TResult> callback, T1 param1, T2 param2)
{
AddListener(callback.ToExtendedDelegate(param1, param2));
}
public void AddListener<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> callback, T1 param1, T2 param2, T3 param3)
{
AddListener(callback.ToExtendedDelegate(param1, param2, param3));
}
public void AddListener<T1, T2, T3, T4, TResult>(Func<T1, T2, T3, T4, TResult> callback, T1 param1, T2 param2, T3 param3, T4 param4)
{
AddListener(callback.ToExtendedDelegate(param1, param2, param3, param4));
}
public void RemoveListener(Action callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T>(Action<T> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T1, T2>(Action<T1, T2> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T1, T2, T3>(Action<T1, T2, T3> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T1, T2, T3, T4>(Action<T1, T2, T3, T4> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener(UnityAction callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T>(UnityAction<T> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T1, T2>(UnityAction<T1, T2> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T1, T2, T3>(UnityAction<T1, T2, T3> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T1, T2, T3, T4>(UnityAction<T1, T2, T3, T4> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<TResult>(Func<TResult> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T, TResult>(Func<T, TResult> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T1, T2, TResult>(Func<T1, T2, TResult> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveListener<T1, T2, T3, T4, TResult>(Func<T1, T2, T3, T4, TResult> callback)
{
RemoveByMethodInfo(callback.Method);
}
public void RemoveAll()
{
this.listeners.Clear();
this.callbacks.Clear();
}
protected void RemoveByMethodInfo(MethodInfo method)
{
var index = -1;
for (var i = 0; i < this.callbacks.Count; i++)
{
if (this.callbacks[i].Method.Equals(method))
{
index = i;
break;
}
}
if (index >= 0)
this.callbacks.RemoveAt(index);
}
public void OnBeforeSerialize()
{
}
public void OnAfterDeserialize()
{
#if !UNITY_EDITOR
for (var i = 0; i < this.listeners.Count; ++i)
{
if (this.listeners[i] != null)
this.listeners[i].Initialize();
}
#endif // !UNITY_EDITOR
}
}
}
| |
#region Using directives
#define USE_TRACING
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Xml;
#endregion
//////////////////////////////////////////////////////////////////////
// <summary>Contains AtomFeed, an object to represent the atom:feed
// element.</summary>
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Client
{
//////////////////////////////////////////////////////////////////////
/// <summary>Base class to read gData feeds in Atom</summary>
/// <remarks>
/// <para>
/// Version 1.0 changed to:
/// <code>
/// AtomFeed =
/// element atom:feed {
/// atomCommonAttributes,
/// (atomAuthor*
/// atomCategory*
/// atomContributor*
/// atomGenerator?
/// atomIcon?
/// atomId
/// atomLink*
/// atomLogo?
/// atomRights?
/// atomSubtitle?
/// atomTitle
/// atomUpdated
/// extensionElement*),
/// atomEntry*
/// }
/// </code>
/// In addition it holds:
/// <list type="bullet">
/// <item>
/// <term><c>opensearch:totalResults</c></term>
/// <description>Total number of search results available (not necessarily all present in the feed).</description>
/// </item>
/// <item>
/// <term><c>opensearch:startIndex</c></term>
/// <description>The 1-based index of the first result.</description>
/// </item>
/// <item>
/// <term><c>opensearch:itemsPerPage</c></term>
/// <description>The maximum number of items that appear on one page. This allows clients to generate direct links to any set of subsequent pages.</description>
/// </item>
/// </list>
/// </para>
/// <para>
/// In addition to these OpenSearch tags, the response also includes the following Atom and gData tags:
/// <list type="bullet">
/// <item>
/// <term><c>atom:link rel="service.feed" type="application/atom+xml" href="..."/></c></term>
/// <description>Specifies the URI where the complete Atom feed can be retrieved.</description>
/// </item>
/// <item>
/// <term><c>atom:link rel="service.feed" type="application/rss+xml" href="..."/></c></term>
/// <description>Specifies the URI where the complete RSS feed can be retrieved.</description>
/// </item>
/// <item>
/// <term><c>atom:link rel="service.post" type="application/atom+xml" href="..."/></c></term>
/// <description>Specifies the Atom feed PostURI (where new entries can be posted).</description>
/// </item>
/// <item>
/// <term><c>atom:link rel="self" type="..." href="..."/></c></term>
/// <description>Contains the URI of this search request. The type attribute depends on the requested format. If no data changes, issuing a <c>GET</c> to this URI returns the same response.</description>
/// </item>
/// <item>
/// <term><c>atom:link rel="previous" type="application/atom+xml" href="..."/></c></term>
/// <description>Specifies the URI of the previous chunk of this query resultset, if it is chunked.</description>
/// </item>
/// <item>
/// <term><c>atom:link rel="next" type="application/atom+xml" href="..."/></c></term>
/// <description>Specifies the URI of the next chunk of this query resultset, if it is chunked.</description>
/// </item>
/// <item>
/// <term><c>gdata:processed parameter="..."/></c></term>
/// <description>One of these tags is inserted for each parameter understood and processed by the service, e.g. <c>gdata:processed parameter="author"</c>.</description>
/// </item>
/// </list>
/// </para>
/// </remarks>
//////////////////////////////////////////////////////////////////////
[TypeConverter(typeof (AtomSourceConverter)), Description("Expand to see the options for the feed")]
public class AtomFeed : AtomSource
{
/// <summary>collection of feed entries</summary>
private AtomEntryCollection feedEntries;
//////////////////////////////////////////////////////////////////////
/// <summary>default constructor</summary>
//////////////////////////////////////////////////////////////////////
private AtomFeed()
{
Tracing.Assert(false, "privately Constructing AtomFeed - should not happen");
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>default constructor</summary>
/// <param name="uriBase">the location the feed was loaded from</param>
/// <param name="service">the service used to create this feed</param>
//////////////////////////////////////////////////////////////////////
public AtomFeed(Uri uriBase, IService service)
{
Tracing.TraceCall("Constructing AtomFeed");
if (uriBase != null)
{
ImpliedBase = new AtomUri(uriBase.AbsoluteUri);
}
Service = service;
NewExtensionElement += OnNewExtensionsElement;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>default constructor</summary>
/// <param name="originalFeed">if you want to create a copy feed, for batch use, e.g</param>
//////////////////////////////////////////////////////////////////////
public AtomFeed(AtomFeed originalFeed)
{
if (originalFeed == null)
{
throw new ArgumentNullException("originalFeed");
}
Tracing.TraceCall("Constructing AtomFeed");
Batch = originalFeed.Batch;
Post = originalFeed.Post;
Self = originalFeed.Self;
Feed = originalFeed.Feed;
Service = originalFeed.Service;
ImpliedBase = originalFeed.ImpliedBase;
}
/// <summary>eventhandler, when the parser creates a new feed entry-> mirrored from underlying parser</summary>
public event FeedParserEventHandler NewAtomEntry;
/// <summary>eventhandler, when the parser finds a new extension element-> mirrored from underlying parser</summary>
public event ExtensionElementEventHandler NewExtensionElement;
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>tries to determine if the two feeds derive from the same source</summary>
/// <param name="feedOne">the first feed</param>
/// <param name="feedTwo">the second feed</param>
/// <returns>true if believed to be the same source</returns>
//////////////////////////////////////////////////////////////////////
public static bool IsFeedIdentical(AtomFeed feedOne, AtomFeed feedTwo)
{
if (feedOne == feedTwo)
{
Tracing.TraceMsg("TRUE : testing for identical feeds, feedpointers equal: ");
return true;
}
if (feedOne == null || feedTwo == null)
{
Tracing.TraceMsg("FALSE : testing for identical feeds, one feed is NULL: ");
return false;
}
if (string.Compare(feedOne.Post, feedTwo.Post) != 0)
{
Tracing.TraceMsg("FALSE : testing for identical feeds: " + feedOne.Post + " vs. : " + feedTwo.Post);
return false;
}
if (string.Compare(feedOne.Feed, feedTwo.Feed) != 0)
{
Tracing.TraceMsg("FALSE : testing for identical feeds: " + feedOne.Feed + " vs. : " + feedTwo.Feed);
return false;
}
Tracing.TraceMsg("TRUE : testing for identical feeds: " + feedOne.Post + " vs. : " + feedTwo.Post);
return true;
}
//////////////////////////////////////////////////////////////////////
/// <summary>given a stream, parses it to construct the Feed object out of it</summary>
/// <param name="stream"> a stream representing hopefully valid XML</param>
/// <param name="format"> indicates if the stream is Atom or Rss</param>
//////////////////////////////////////////////////////////////////////
public void Parse(Stream stream, AlternativeFormat format)
{
Tracing.TraceCall("parsing stream -> Start:" + format);
BaseFeedParser feedParser = null;
// make sure we reset our collections
Authors.Clear();
Contributors.Clear();
Links.Clear();
Categories.Clear();
feedParser = new AtomFeedParser(this);
// create a new delegate for the parser
feedParser.NewAtomEntry += OnParsedNewEntry;
feedParser.NewExtensionElement += OnNewExtensionElement;
feedParser.Parse(stream, this);
Tracing.TraceInfo("Parsing stream -> Done");
// done parsing
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Event chaining. We catch this by the baseFeedParsers, which
/// would not do anything with the gathered data. We pass the event up
/// to the user; if the user doesn't discard it, we add the entry to our
/// collection</summary>
/// <param name="sender"> the object which send the event</param>
/// <param name="e">FeedParserEventArguments, holds the feed entry</param>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
protected void OnParsedNewEntry(object sender, FeedParserEventArgs e)
{
// by default, if our event chain is not hooked, add it to the collection
Tracing.TraceCall("received new item notification");
Tracing.Assert(e != null, "e should not be null");
if (e == null)
{
throw new ArgumentNullException("e");
}
if (NewAtomEntry != null)
{
Tracing.TraceMsg("\t calling event dispatcher");
NewAtomEntry(this, e);
}
// now check the return
if (!e.DiscardEntry)
{
if (!e.CreatingEntry)
{
if (e.Entry != null)
{
// add it to the collection
Tracing.TraceMsg("\t new AtomEntry found, adding to collection");
e.Entry.Service = Service;
Entries.Add(e.Entry);
}
else if (e.Feed != null)
{
// parsed a feed, set ourselves to it...
Tracing.TraceMsg("\t Feed parsed found, parsing is done...");
}
}
else
{
IVersionAware v = e.Entry;
if (v != null)
{
v.ProtocolMajor = ProtocolMajor;
v.ProtocolMinor = ProtocolMinor;
}
}
}
if (e.DoneParsing)
{
BaseUriChanged(ImpliedBase);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Event chaining. We catch this by the baseFeedParsers, which
/// would not do anything with the gathered data. We pass the event up
/// to the user; if the user doesn't discard it, we add the entry to our
/// collection</summary>
/// <param name="sender"> the object which send the event</param>
/// <param name="e">FeedParserEventArguments, holds the feed entry</param>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
protected void OnNewExtensionElement(object sender, ExtensionElementEventArgs e)
{
// by default, if our event chain is not hooked, the underlying parser will add it
Tracing.TraceCall("received new extension element notification");
Tracing.Assert(e != null, "e should not be null");
if (e == null)
{
throw new ArgumentNullException("e");
}
if (NewExtensionElement != null)
{
Tracing.TraceMsg("\t calling event dispatcher");
NewExtensionElement(sender, e);
}
}
/////////////////////////////////////////////////////////////////////////////
#region overloaded for property changes, xml:base
//////////////////////////////////////////////////////////////////////
/// <summary>just go down the child collections</summary>
/// <param name="uriBase"> as currently calculated</param>
//////////////////////////////////////////////////////////////////////
internal override void BaseUriChanged(AtomUri uriBase)
{
base.BaseUriChanged(uriBase);
// now walk over the entries and forward...
uriBase = new AtomUri(Utilities.CalculateUri(Base, uriBase, null));
foreach (AtomEntry entry in Entries)
{
entry.BaseUriChanged(uriBase);
}
}
/////////////////////////////////////////////////////////////////////////////
#endregion
/// <summary>eventhandler - called for event extension element
/// </summary>
/// <param name="sender">the object which send the event</param>
/// <param name="e">FeedParserEventArguments, holds the feedEntry</param>
/// <returns> </returns>
protected void OnNewExtensionsElement(object sender, ExtensionElementEventArgs e)
{
if (e == null)
{
throw new ArgumentNullException("e");
}
AtomFeedParser parser = sender as AtomFeedParser;
if (e.Base.XmlName == AtomParserNameTable.XmlAtomEntryElement)
{
// the base is the Entry of the feed, let's call our parsing on the Entry
AtomEntry entry = e.Base as AtomEntry;
if (entry != null)
{
entry.Parse(e, parser);
}
}
else
{
HandleExtensionElements(e, parser);
}
}
/// <summary>
/// event on the Feed to handle extension elements during parsing
/// </summary>
/// <param name="e">the event arguments</param>
/// <param name="parser">the parser that caused this</param>
protected virtual void HandleExtensionElements(ExtensionElementEventArgs e, AtomFeedParser parser)
{
Tracing.TraceMsg("Entering HandleExtensionElements on AbstractFeed");
XmlNode node = e.ExtensionElement;
if (ExtensionFactories != null && ExtensionFactories.Count > 0)
{
Tracing.TraceMsg("Entring default Parsing for AbstractFeed");
foreach (IExtensionElementFactory f in ExtensionFactories)
{
Tracing.TraceMsg("Found extension Factories");
if (string.Compare(node.NamespaceURI, f.XmlNameSpace, true, CultureInfo.InvariantCulture) == 0)
{
if (string.Compare(node.LocalName, f.XmlName, true, CultureInfo.InvariantCulture) == 0)
{
e.Base.ExtensionElements.Add(f.CreateInstance(node, parser));
e.DiscardEntry = true;
break;
}
}
}
}
}
#region properties
/// <summary>holds the total results</summary>
private int totalResults;
/// <summary>holds the start-index parameter</summary>
private int startIndex;
/// <summary>holds number of items per page</summary>
private int itemsPerPage;
/// <summary>holds the service interface to use</summary>
private IService service;
#endregion
/////////////////////////////////////////////////////////////////////////////
#region Property Accessors
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string Post</summary>
/// <returns>the Uri as string to the Post Service</returns>
//////////////////////////////////////////////////////////////////////
public string Post
{
get
{
// scan the link collection
AtomLink link = Links.FindService(BaseNameTable.ServicePost, AtomLink.ATOM_TYPE);
return link == null ? null : Utilities.CalculateUri(Base, ImpliedBase, link.HRef.ToString());
}
set
{
AtomLink link = Links.FindService(BaseNameTable.ServicePost, AtomLink.ATOM_TYPE);
if (link == null)
{
link = new AtomLink(AtomLink.ATOM_TYPE, BaseNameTable.ServicePost);
Links.Add(link);
}
link.HRef = new AtomUri(value);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor to the batchdata for the entry</summary>
/// <returns> GDataBatch object </returns>
//////////////////////////////////////////////////////////////////////
public GDataBatchFeedData BatchData { get; set; }
// end of accessor public GDataBatch BatchData
//////////////////////////////////////////////////////////////////////
/// <summary>Retrieves the batch link for the current feed.</summary>
/// <returns>The URI of the batch support for the feed. </returns>
//////////////////////////////////////////////////////////////////////
public string Batch
{
get
{
// scan the link collection
AtomLink link = Links.FindService(BaseNameTable.ServiceBatch, AtomLink.ATOM_TYPE);
return link == null ? null : Utilities.CalculateUri(Base, ImpliedBase, link.HRef.ToString());
}
set
{
AtomLink link = Links.FindService(BaseNameTable.ServiceBatch, AtomLink.ATOM_TYPE);
if (link == null)
{
link = new AtomLink(AtomLink.ATOM_TYPE, BaseNameTable.ServiceBatch);
Links.Add(link);
}
link.HRef = new AtomUri(value);
}
}
/////////////////////////////////////////////////////////////////////////////
/// <summary>
/// returns a new batchfeed with all the currently dirty entries in it
/// </summary>
/// <param name="defaultOperation">the default operation to execute</param>
/// <returns>AtomFeed</returns>
public AtomFeed CreateBatchFeed(GDataBatchOperationType defaultOperation)
{
AtomFeed batchFeed = null;
if (Batch != null)
{
batchFeed = new AtomFeed(this);
// set the default operation.
batchFeed.BatchData = new GDataBatchFeedData();
batchFeed.BatchData.Type = defaultOperation;
int id = 1;
foreach (AtomEntry entry in Entries)
{
if (entry.Dirty)
{
AtomEntry batchEntry = batchFeed.Entries.CopyOrMove(entry);
batchEntry.BatchData = new GDataBatchEntryData();
batchEntry.BatchData.Id = id.ToString(CultureInfo.InvariantCulture);
id++;
entry.Dirty = false;
}
}
}
return batchFeed;
}
//////////////////////////////////////////////////////////////////////
/// <summary>returns whether or not the entry is read-only </summary>
//////////////////////////////////////////////////////////////////////
public bool ReadOnly
{
get { return Post == null ? true : false; }
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string NextChunk</summary>
/// <returns>the Uri as string to the next chunk of the result</returns>
//////////////////////////////////////////////////////////////////////
public string NextChunk
{
get
{
AtomLink link = Links.FindService(BaseNameTable.ServiceNext, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : Utilities.CalculateUri(Base, ImpliedBase, link.HRef.ToString());
}
set
{
AtomLink link = Links.FindService(BaseNameTable.ServiceNext, AtomLink.ATOM_TYPE);
if (link == null)
{
link = new AtomLink(AtomLink.ATOM_TYPE, BaseNameTable.ServiceNext);
Links.Add(link);
}
link.HRef = new AtomUri(value);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string PrevChunk</summary>
/// <returns>the Uri as a string to the previous chunk of the result</returns>
//////////////////////////////////////////////////////////////////////
public string PrevChunk
{
get
{
AtomLink link = Links.FindService(BaseNameTable.ServicePrev, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : Utilities.CalculateUri(Base, ImpliedBase, link.HRef.ToString());
}
set
{
AtomLink link = Links.FindService(BaseNameTable.ServicePrev, AtomLink.ATOM_TYPE);
if (link == null)
{
link = new AtomLink(AtomLink.ATOM_TYPE, BaseNameTable.ServicePrev);
Links.Add(link);
}
link.HRef = new AtomUri(value);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string Feed</summary>
/// <returns>returns the Uri as string for the feed service </returns>
//////////////////////////////////////////////////////////////////////
public string Feed
{
get
{
AtomLink link = Links.FindService(BaseNameTable.ServiceFeed, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : Utilities.CalculateUri(Base, ImpliedBase, link.HRef.ToString());
}
set
{
AtomLink link = Links.FindService(BaseNameTable.ServiceFeed, AtomLink.ATOM_TYPE);
if (link == null)
{
link = new AtomLink(AtomLink.ATOM_TYPE, BaseNameTable.ServiceFeed);
Links.Add(link);
}
link.HRef = new AtomUri(value);
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string Self</summary>
/// <returns>returns the Uri as string for the feed with the Query Parameters </returns>
//////////////////////////////////////////////////////////////////////
public string Self
{
get
{
AtomLink link = Links.FindService(BaseNameTable.ServiceSelf, AtomLink.ATOM_TYPE);
// scan the link collection
return link == null ? null : Utilities.CalculateUri(Base, ImpliedBase, link.HRef.ToString());
}
set
{
AtomLink link = Links.FindService(BaseNameTable.ServiceSelf, AtomLink.ATOM_TYPE);
if (link == null)
{
link = new AtomLink(AtomLink.ATOM_TYPE, BaseNameTable.ServiceSelf);
Links.Add(link);
}
link.HRef = new AtomUri(value);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method for the gData Service to use</summary>
//////////////////////////////////////////////////////////////////////
public IService Service
{
get { return service; }
set
{
Dirty = true;
service = value;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public int TotalResults</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public int TotalResults
{
get { return totalResults; }
set
{
Dirty = true;
totalResults = value;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public int StartIndex</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public int StartIndex
{
get { return startIndex; }
set
{
Dirty = true;
startIndex = value;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public int ItemsPerPage</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public int ItemsPerPage
{
get { return itemsPerPage; }
set
{
Dirty = true;
itemsPerPage = value;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public ExtensionList Entries</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public AtomEntryCollection Entries
{
get
{
if (feedEntries == null)
{
feedEntries = new AtomEntryCollection(this);
}
return feedEntries;
}
}
/////////////////////////////////////////////////////////////////////////////
#endregion
#region Persistence overloads
//////////////////////////////////////////////////////////////////////
/// <summary>checks to see if we are a batch feed, if so, adds the batchNS</summary>
/// <param name="writer">the xmlwriter, where we want to add default namespaces to</param>
//////////////////////////////////////////////////////////////////////
protected override void AddOtherNamespaces(XmlWriter writer)
{
base.AddOtherNamespaces(writer);
if (BatchData != null)
{
Utilities.EnsureGDataBatchNamespace(writer);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>checks if this is a namespace
/// decl that we already added</summary>
/// <param name="node">XmlNode to check</param>
/// <returns>true if this node should be skipped </returns>
//////////////////////////////////////////////////////////////////////
protected override bool SkipNode(XmlNode node)
{
if (base.SkipNode(node))
{
return true;
}
Tracing.TraceMsg("in skipnode for node: " + node.Name + "--" + node.Value);
if (BatchData != null)
{
if (node.NodeType == XmlNodeType.Attribute &&
node.Name.StartsWith("xmlns") &&
(string.Compare(node.Value, BaseNameTable.gBatchNamespace) == 0))
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////
/// <summary>just returns the constant representing this xml element</summary>
//////////////////////////////////////////////////////////////////////
public override string XmlName
{
get { return AtomParserNameTable.XmlFeedElement; }
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>saves the inner state of the element</summary>
/// <param name="writer">the xmlWriter to save into </param>
//////////////////////////////////////////////////////////////////////
protected override void SaveInnerXml(XmlWriter writer)
{
// first let the source save it self
base.SaveInnerXml(writer);
// now we need to save the entries
if (BatchData != null)
{
BatchData.Save(writer);
}
foreach (AtomEntry entry in Entries)
{
entry.SaveToXml(writer);
}
}
/////////////////////////////////////////////////////////////////////////////
#endregion
#region Editing APIs
//////////////////////////////////////////////////////////////////////
/// <summary>uses the set service to insert a new entry. </summary>
/// <param name="newEntry">the atomEntry to insert into the feed</param>
/// <returns>the entry as echoed back from the server. The entry is NOT added
/// to the feeds collection</returns>
//////////////////////////////////////////////////////////////////////
public TEntry Insert<TEntry>(TEntry newEntry) where TEntry : AtomEntry
{
Tracing.Assert(newEntry != null, "newEntry should not be null");
if (newEntry == null)
{
throw new ArgumentNullException("newEntry");
}
AtomEntry echoedEntry = null;
if (newEntry.Feed == this)
{
// same object, already in here.
throw new ArgumentException("The entry is already part of this colleciton");
}
// now we need to see if this is the same feed. If not, copy
if (newEntry.Feed == null)
{
newEntry.setFeed(this);
}
else if (!IsFeedIdentical(newEntry.Feed, this))
{
newEntry = AtomEntry.ImportFromFeed(newEntry) as TEntry;
newEntry.setFeed(this);
}
if (Service != null)
{
echoedEntry = Service.Insert(this, newEntry);
}
return echoedEntry as TEntry;
}
//////////////////////////////////////////////////////////////////////
/// <summary>goes over all entries, and updates the ones that are dirty</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public virtual void Publish()
{
if (Service != null)
{
for (int i = 0; i < Entries.Count; i++)
{
AtomEntry entry = Entries[i];
if (entry.IsDirty())
{
if (entry.Id.Uri == null)
{
// new guy
Tracing.TraceInfo("adding new entry: " + entry.Title.Text);
Entries[i] = Service.Insert(this, entry);
}
else
{
// update the entry
Tracing.TraceInfo("updating entry: " + entry.Title.Text);
entry.Update();
}
}
}
}
MarkElementDirty(false);
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>calls the action on this object and all children</summary>
/// <param name="action">an IAtomBaseAction interface to call </param>
/// <returns>true or false, pending outcome</returns>
//////////////////////////////////////////////////////////////////////
public override bool WalkTree(IBaseWalkerAction action)
{
if (base.WalkTree(action))
{
return true;
}
foreach (AtomEntry entry in Entries)
{
if (entry.WalkTree(action))
return true;
}
return false;
}
#endregion
}
/////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Threading;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace System.Net
{
[Serializable]
public class FileWebRequest : WebRequest, ISerializable
{
private readonly WebHeaderCollection _headers = new WebHeaderCollection();
private string _method = WebRequestMethods.File.DownloadFile;
private FileAccess _fileAccess = FileAccess.Read;
private ManualResetEventSlim _blockReaderUntilRequestStreamDisposed;
private WebResponse _response;
private WebFileStream _stream;
private Uri _uri;
private long _contentLength;
private int _timeout = DefaultTimeoutMilliseconds;
private bool _readPending;
private bool _writePending;
private bool _writing;
private bool _syncHint;
private int _aborted;
internal FileWebRequest(Uri uri)
{
if (uri.Scheme != (object)Uri.UriSchemeFile)
{
throw new ArgumentOutOfRangeException(nameof(uri));
}
_uri = uri;
}
[Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?linkid=14202")]
protected FileWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
_headers = (WebHeaderCollection)serializationInfo.GetValue("headers", typeof(WebHeaderCollection));
Proxy = (IWebProxy)serializationInfo.GetValue("proxy", typeof(IWebProxy));
_uri = (Uri)serializationInfo.GetValue("uri", typeof(Uri));
ConnectionGroupName = serializationInfo.GetString("connectionGroupName");
_method = serializationInfo.GetString("method");
_contentLength = serializationInfo.GetInt64("contentLength");
_timeout = serializationInfo.GetInt32("timeout");
_fileAccess = (FileAccess)serializationInfo.GetInt32("fileAccess");
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) =>
GetObjectData(serializationInfo, streamingContext);
protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
serializationInfo.AddValue("headers", _headers, typeof(WebHeaderCollection));
serializationInfo.AddValue("proxy", Proxy, typeof(IWebProxy));
serializationInfo.AddValue("uri", _uri, typeof(Uri));
serializationInfo.AddValue("connectionGroupName", ConnectionGroupName);
serializationInfo.AddValue("method", _method);
serializationInfo.AddValue("contentLength", _contentLength);
serializationInfo.AddValue("timeout", _timeout);
serializationInfo.AddValue("fileAccess", _fileAccess);
serializationInfo.AddValue("preauthenticate", false);
base.GetObjectData(serializationInfo, streamingContext);
}
internal bool Aborted => _aborted != 0;
public override string ConnectionGroupName { get; set; }
public override long ContentLength
{
get { return _contentLength; }
set
{
if (value < 0)
{
throw new ArgumentException(SR.net_clsmall, nameof(value));
}
_contentLength = value;
}
}
public override string ContentType
{
get { return _headers["Content-Type"]; }
set { _headers["Content-Type"] = value; }
}
public override ICredentials Credentials { get; set; }
public override WebHeaderCollection Headers => _headers;
public override string Method
{
get { return _method; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
_method = value;
}
}
public override bool PreAuthenticate { get; set; }
public override IWebProxy Proxy { get; set; }
public override int Timeout
{
get { return _timeout; }
set
{
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_timeout = value;
}
}
public override Uri RequestUri => _uri;
private static Exception CreateRequestAbortedException() =>
new WebException(SR.Format(SR.net_requestaborted, WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
private void CheckAndMarkAsyncGetRequestStreamPending()
{
if (Aborted)
{
throw CreateRequestAbortedException();
}
if (string.Equals(_method, "GET", StringComparison.OrdinalIgnoreCase) ||
string.Equals(_method, "HEAD", StringComparison.OrdinalIgnoreCase))
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
if (_response != null)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
lock (this)
{
if (_writePending)
{
throw new InvalidOperationException(SR.net_repcall);
}
_writePending = true;
}
}
private Stream CreateWriteStream()
{
try
{
if (_stream == null)
{
_stream = new WebFileStream(this, _uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.Read);
_fileAccess = FileAccess.Write;
_writing = true;
}
return _stream;
}
catch (Exception e) { throw new WebException(e.Message, e); }
}
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
CheckAndMarkAsyncGetRequestStreamPending();
Task<Stream> t = Task.Factory.StartNew(s => ((FileWebRequest)s).CreateWriteStream(),
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
return TaskToApm.Begin(t, callback, state);
}
public override Task<Stream> GetRequestStreamAsync()
{
CheckAndMarkAsyncGetRequestStreamPending();
return Task.Factory.StartNew(s =>
{
FileWebRequest thisRef = (FileWebRequest)s;
Stream writeStream = thisRef.CreateWriteStream();
thisRef._writePending = false;
return writeStream;
}, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
private void CheckAndMarkAsyncGetResponsePending()
{
if (Aborted)
{
throw CreateRequestAbortedException();
}
lock (this)
{
if (_readPending)
{
throw new InvalidOperationException(SR.net_repcall);
}
_readPending = true;
}
}
private WebResponse CreateResponse()
{
if (_writePending || _writing)
{
lock (this)
{
if (_writePending || _writing)
{
_blockReaderUntilRequestStreamDisposed = new ManualResetEventSlim();
}
}
}
_blockReaderUntilRequestStreamDisposed?.Wait();
try
{
return _response ?? (_response = new FileWebResponse(this, _uri, _fileAccess, !_syncHint));
}
catch (Exception e)
{
throw new WebException(e.Message, e);
}
}
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
CheckAndMarkAsyncGetResponsePending();
Task<WebResponse> t = Task.Factory.StartNew(s => ((FileWebRequest)s).CreateResponse(),
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
return TaskToApm.Begin(t, callback, state);
}
public override Task<WebResponse> GetResponseAsync()
{
CheckAndMarkAsyncGetResponsePending();
return Task.Factory.StartNew(s =>
{
var thisRef = (FileWebRequest)s;
WebResponse response = thisRef.CreateResponse();
_readPending = false;
return response;
}, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
Stream stream = TaskToApm.End<Stream>(asyncResult);
_writePending = false;
return stream;
}
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
WebResponse response = TaskToApm.End<WebResponse>(asyncResult);
_readPending = false;
return response;
}
public override Stream GetRequestStream()
{
IAsyncResult result = BeginGetRequestStream(null, null);
if (Timeout != Threading.Timeout.Infinite &&
!result.IsCompleted &&
(!result.AsyncWaitHandle.WaitOne(Timeout, false) || !result.IsCompleted))
{
_stream?.Close();
throw new WebException(SR.net_webstatus_Timeout, WebExceptionStatus.Timeout);
}
return EndGetRequestStream(result);
}
public override WebResponse GetResponse()
{
_syncHint = true;
IAsyncResult result = BeginGetResponse(null, null);
if (Timeout != Threading.Timeout.Infinite &&
!result.IsCompleted &&
(!result.AsyncWaitHandle.WaitOne(Timeout, false) || !result.IsCompleted))
{
_response?.Close();
throw new WebException(SR.net_webstatus_Timeout, WebExceptionStatus.Timeout);
}
return EndGetResponse(result);
}
internal void UnblockReader()
{
lock (this) { _blockReaderUntilRequestStreamDisposed?.Set(); }
_writing = false;
}
public override bool UseDefaultCredentials
{
get { throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException); }
set { throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException); }
}
public override void Abort()
{
if (Interlocked.Increment(ref _aborted) == 1)
{
_stream?.Abort();
_response?.Close();
}
}
}
internal sealed class FileWebRequestCreator : IWebRequestCreate
{
public WebRequest Create(Uri uri) => new FileWebRequest(uri);
}
internal sealed class WebFileStream : FileStream
{
private readonly FileWebRequest _request;
public WebFileStream(FileWebRequest request, string path, FileMode mode, FileAccess access, FileShare sharing) :
base(path, mode, access, sharing)
{
_request = request;
}
public WebFileStream(FileWebRequest request, string path, FileMode mode, FileAccess access, FileShare sharing, int length, bool async) :
base(path, mode, access, sharing, length, async)
{
_request = request;
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
_request?.UnblockReader();
}
}
finally { base.Dispose(disposing); }
}
internal void Abort() => SafeFileHandle.Close();
public override int Read(byte[] buffer, int offset, int size)
{
CheckAborted();
try
{
return base.Read(buffer, offset, size);
}
catch
{
CheckAborted();
throw;
}
}
public override void Write(byte[] buffer, int offset, int size)
{
CheckAborted();
try
{
base.Write(buffer, offset, size);
}
catch
{
CheckAborted();
throw;
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
CheckAborted();
try
{
return base.BeginRead(buffer, offset, size, callback, state);
}
catch
{
CheckAborted();
throw;
}
}
public override int EndRead(IAsyncResult ar)
{
try
{
return base.EndRead(ar);
}
catch
{
CheckAborted();
throw;
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
CheckAborted();
try
{
return base.BeginWrite(buffer, offset, size, callback, state);
}
catch
{
CheckAborted();
throw;
}
}
public override void EndWrite(IAsyncResult ar)
{
try
{
base.EndWrite(ar);
}
catch
{
CheckAborted();
throw;
}
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckAborted();
try
{
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
catch
{
CheckAborted();
throw;
}
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckAborted();
try
{
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
catch
{
CheckAborted();
throw;
}
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
CheckAborted();
try
{
return base.CopyToAsync(destination, bufferSize, cancellationToken);
}
catch
{
CheckAborted();
throw;
}
}
private void CheckAborted()
{
if (_request.Aborted)
{
throw new WebException(SR.Format(SR.net_requestaborted, WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
}
}
}
}
| |
using System;
using BigMath;
using NUnit.Framework;
using Raksha.Crypto;
using Raksha.Crypto.Digests;
using Raksha.Crypto.Engines;
using Raksha.Crypto.Generators;
using Raksha.Crypto.Parameters;
using Raksha.Crypto.Signers;
using Raksha.Math;
using Raksha.Security;
using Raksha.Utilities.Encoders;
using Raksha.Tests.Utilities;
namespace Raksha.Tests.Crypto
{
/*
* RSA PSS test vectors for PKCS#1 V2.1 with blinding
*/
[TestFixture]
public class PssBlindTest
: SimpleTest
{
private readonly int DATA_LENGTH = 1000;
private readonly int NUM_TESTS = 50;
private readonly int NUM_TESTS_WITH_KEY_GENERATION = 10;
private class FixedRandom
: SecureRandom
{
private readonly byte[] vals;
public FixedRandom(
byte[] vals)
{
this.vals = vals;
}
public override void NextBytes(
byte[] bytes)
{
Array.Copy(vals, 0, bytes, 0, vals.Length);
}
}
//
// Example 1: A 1024-bit RSA keypair
//
private RsaKeyParameters pub1 = new RsaKeyParameters(false,
new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16),
new BigInteger("010001",16));
private RsaKeyParameters prv1 = new RsaPrivateCrtKeyParameters(
new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16),
new BigInteger("010001",16),
new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325",16),
new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443",16),
new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd",16),
new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979",16),
new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729",16),
new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d",16));
// PSSExample1.1
private byte[] msg1a = Hex.Decode("cdc87da223d786df3b45e0bbbc721326d1ee2af806cc315475cc6f0d9c66e1b62371d45ce2392e1ac92844c310102f156a0d8d52c1f4c40ba3aa65095786cb769757a6563ba958fed0bcc984e8b517a3d5f515b23b8a41e74aa867693f90dfb061a6e86dfaaee64472c00e5f20945729cbebe77f06ce78e08f4098fba41f9d6193c0317e8b60d4b6084acb42d29e3808a3bc372d85e331170fcbf7cc72d0b71c296648b3a4d10f416295d0807aa625cab2744fd9ea8fd223c42537029828bd16be02546f130fd2e33b936d2676e08aed1b73318b750a0167d0");
private byte[] slt1a = Hex.Decode("dee959c7e06411361420ff80185ed57f3e6776af");
private byte[] sig1a = Hex.Decode("9074308fb598e9701b2294388e52f971faac2b60a5145af185df5287b5ed2887e57ce7fd44dc8634e407c8e0e4360bc226f3ec227f9d9e54638e8d31f5051215df6ebb9c2f9579aa77598a38f914b5b9c1bd83c4e2f9f382a0d0aa3542ffee65984a601bc69eb28deb27dca12c82c2d4c3f66cd500f1ff2b994d8a4e30cbb33c");
// PSSExample1.2
private byte[] msg1b = Hex.Decode("851384cdfe819c22ed6c4ccb30daeb5cf059bc8e1166b7e3530c4c233e2b5f8f71a1cca582d43ecc72b1bca16dfc7013226b9e");
private byte[] slt1b = Hex.Decode("ef2869fa40c346cb183dab3d7bffc98fd56df42d");
private byte[] sig1b = Hex.Decode("3ef7f46e831bf92b32274142a585ffcefbdca7b32ae90d10fb0f0c729984f04ef29a9df0780775ce43739b97838390db0a5505e63de927028d9d29b219ca2c4517832558a55d694a6d25b9dab66003c4cccd907802193be5170d26147d37b93590241be51c25055f47ef62752cfbe21418fafe98c22c4d4d47724fdb5669e843");
//
// Example 2: A 1025-bit RSA keypair
//
private RsaKeyParameters pub2 = new RsaKeyParameters(false,
new BigInteger("01d40c1bcf97a68ae7cdbd8a7bf3e34fa19dcca4ef75a47454375f94514d88fed006fb829f8419ff87d6315da68a1ff3a0938e9abb3464011c303ad99199cf0c7c7a8b477dce829e8844f625b115e5e9c4a59cf8f8113b6834336a2fd2689b472cbb5e5cabe674350c59b6c17e176874fb42f8fc3d176a017edc61fd326c4b33c9", 16),
new BigInteger("010001", 16));
private RsaKeyParameters prv2 = new RsaPrivateCrtKeyParameters(
new BigInteger("01d40c1bcf97a68ae7cdbd8a7bf3e34fa19dcca4ef75a47454375f94514d88fed006fb829f8419ff87d6315da68a1ff3a0938e9abb3464011c303ad99199cf0c7c7a8b477dce829e8844f625b115e5e9c4a59cf8f8113b6834336a2fd2689b472cbb5e5cabe674350c59b6c17e176874fb42f8fc3d176a017edc61fd326c4b33c9", 16),
new BigInteger("010001", 16),
new BigInteger("027d147e4673057377fd1ea201565772176a7dc38358d376045685a2e787c23c15576bc16b9f444402d6bfc5d98a3e88ea13ef67c353eca0c0ddba9255bd7b8bb50a644afdfd1dd51695b252d22e7318d1b6687a1c10ff75545f3db0fe602d5f2b7f294e3601eab7b9d1cecd767f64692e3e536ca2846cb0c2dd486a39fa75b1", 16),
new BigInteger("016601e926a0f8c9e26ecab769ea65a5e7c52cc9e080ef519457c644da6891c5a104d3ea7955929a22e7c68a7af9fcad777c3ccc2b9e3d3650bce404399b7e59d1", 16),
new BigInteger("014eafa1d4d0184da7e31f877d1281ddda625664869e8379e67ad3b75eae74a580e9827abd6eb7a002cb5411f5266797768fb8e95ae40e3e8a01f35ff89e56c079", 16),
new BigInteger("e247cce504939b8f0a36090de200938755e2444b29539a7da7a902f6056835c0db7b52559497cfe2c61a8086d0213c472c78851800b171f6401de2e9c2756f31", 16),
new BigInteger("b12fba757855e586e46f64c38a70c68b3f548d93d787b399999d4c8f0bbd2581c21e19ed0018a6d5d3df86424b3abcad40199d31495b61309f27c1bf55d487c1", 16),
new BigInteger("564b1e1fa003bda91e89090425aac05b91da9ee25061e7628d5f51304a84992fdc33762bd378a59f030a334d532bd0dae8f298ea9ed844636ad5fb8cbdc03cad", 16));
// PSS Example 2.1
private byte[] msg2a = Hex.Decode("daba032066263faedb659848115278a52c44faa3a76f37515ed336321072c40a9d9b53bc05014078adf520875146aae70ff060226dcb7b1f1fc27e9360");
private byte[] slt2a = Hex.Decode("57bf160bcb02bb1dc7280cf0458530b7d2832ff7");
private byte[] sig2a = Hex.Decode("014c5ba5338328ccc6e7a90bf1c0ab3fd606ff4796d3c12e4b639ed9136a5fec6c16d8884bdd99cfdc521456b0742b736868cf90de099adb8d5ffd1deff39ba4007ab746cefdb22d7df0e225f54627dc65466131721b90af445363a8358b9f607642f78fab0ab0f43b7168d64bae70d8827848d8ef1e421c5754ddf42c2589b5b3");
// PSS Example 2.2
private byte[] msg2b = Hex.Decode("e4f8601a8a6da1be34447c0959c058570c3668cfd51dd5f9ccd6ad4411fe8213486d78a6c49f93efc2ca2288cebc2b9b60bd04b1e220d86e3d4848d709d032d1e8c6a070c6af9a499fcf95354b14ba6127c739de1bb0fd16431e46938aec0cf8ad9eb72e832a7035de9b7807bdc0ed8b68eb0f5ac2216be40ce920c0db0eddd3860ed788efaccaca502d8f2bd6d1a7c1f41ff46f1681c8f1f818e9c4f6d91a0c7803ccc63d76a6544d843e084e363b8acc55aa531733edb5dee5b5196e9f03e8b731b3776428d9e457fe3fbcb3db7274442d785890e9cb0854b6444dace791d7273de1889719338a77fe");
private byte[] slt2b = Hex.Decode("7f6dd359e604e60870e898e47b19bf2e5a7b2a90");
private byte[] sig2b = Hex.Decode("010991656cca182b7f29d2dbc007e7ae0fec158eb6759cb9c45c5ff87c7635dd46d150882f4de1e9ae65e7f7d9018f6836954a47c0a81a8a6b6f83f2944d6081b1aa7c759b254b2c34b691da67cc0226e20b2f18b42212761dcd4b908a62b371b5918c5742af4b537e296917674fb914194761621cc19a41f6fb953fbcbb649dea");
//
// Example 4: A 1027-bit RSA key pair
//
private RsaKeyParameters pub4 = new RsaKeyParameters(false,
new BigInteger("054adb7886447efe6f57e0368f06cf52b0a3370760d161cef126b91be7f89c421b62a6ec1da3c311d75ed50e0ab5fff3fd338acc3aa8a4e77ee26369acb81ba900fa83f5300cf9bb6c53ad1dc8a178b815db4235a9a9da0c06de4e615ea1277ce559e9c108de58c14a81aa77f5a6f8d1335494498848c8b95940740be7bf7c3705", 16),
new BigInteger("010001", 16));
private RsaKeyParameters prv4 = new RsaPrivateCrtKeyParameters(
new BigInteger("054adb7886447efe6f57e0368f06cf52b0a3370760d161cef126b91be7f89c421b62a6ec1da3c311d75ed50e0ab5fff3fd338acc3aa8a4e77ee26369acb81ba900fa83f5300cf9bb6c53ad1dc8a178b815db4235a9a9da0c06de4e615ea1277ce559e9c108de58c14a81aa77f5a6f8d1335494498848c8b95940740be7bf7c3705", 16),
new BigInteger("010001", 16),
new BigInteger("fa041f8cd9697ceed38ec8caa275523b4dd72b09a301d3541d72f5d31c05cbce2d6983b36183af10690bd46c46131e35789431a556771dd0049b57461bf060c1f68472e8a67c25f357e5b6b4738fa541a730346b4a07649a2dfa806a69c975b6aba64678acc7f5913e89c622f2d8abb1e3e32554e39df94ba60c002e387d9011", 16),
new BigInteger("029232336d2838945dba9dd7723f4e624a05f7375b927a87abe6a893a1658fd49f47f6c7b0fa596c65fa68a23f0ab432962d18d4343bd6fd671a5ea8d148413995", 16),
new BigInteger("020ef5efe7c5394aed2272f7e81a74f4c02d145894cb1b3cab23a9a0710a2afc7e3329acbb743d01f680c4d02afb4c8fde7e20930811bb2b995788b5e872c20bb1", 16),
new BigInteger("026e7e28010ecf2412d9523ad704647fb4fe9b66b1a681581b0e15553a89b1542828898f27243ebab45ff5e1acb9d4df1b051fbc62824dbc6f6c93261a78b9a759", 16),
new BigInteger("012ddcc86ef655998c39ddae11718669e5e46cf1495b07e13b1014cd69b3af68304ad2a6b64321e78bf3bbca9bb494e91d451717e2d97564c6549465d0205cf421", 16),
new BigInteger("010600c4c21847459fe576703e2ebecae8a5094ee63f536bf4ac68d3c13e5e4f12ac5cc10ab6a2d05a199214d1824747d551909636b774c22cac0b837599abcc75", 16));
// PSS Example 4.1
private byte[] msg4a = Hex.Decode("9fb03b827c8217d9");
private byte[] slt4a = Hex.Decode("ed7c98c95f30974fbe4fbddcf0f28d6021c0e91d");
private byte[] sig4a = Hex.Decode("0323d5b7bf20ba4539289ae452ae4297080feff4518423ff4811a817837e7d82f1836cdfab54514ff0887bddeebf40bf99b047abc3ecfa6a37a3ef00f4a0c4a88aae0904b745c846c4107e8797723e8ac810d9e3d95dfa30ff4966f4d75d13768d20857f2b1406f264cfe75e27d7652f4b5ed3575f28a702f8c4ed9cf9b2d44948");
// PSS Example 4.2
private byte[] msg4b = Hex.Decode("0ca2ad77797ece86de5bf768750ddb5ed6a3116ad99bbd17edf7f782f0db1cd05b0f677468c5ea420dc116b10e80d110de2b0461ea14a38be68620392e7e893cb4ea9393fb886c20ff790642305bf302003892e54df9f667509dc53920df583f50a3dd61abb6fab75d600377e383e6aca6710eeea27156e06752c94ce25ae99fcbf8592dbe2d7e27453cb44de07100ebb1a2a19811a478adbeab270f94e8fe369d90b3ca612f9f");
private byte[] slt4b = Hex.Decode("22d71d54363a4217aa55113f059b3384e3e57e44");
private byte[] sig4b = Hex.Decode("049d0185845a264d28feb1e69edaec090609e8e46d93abb38371ce51f4aa65a599bdaaa81d24fba66a08a116cb644f3f1e653d95c89db8bbd5daac2709c8984000178410a7c6aa8667ddc38c741f710ec8665aa9052be929d4e3b16782c1662114c5414bb0353455c392fc28f3db59054b5f365c49e1d156f876ee10cb4fd70598");
//
// Example 8: A 1031-bit RSA key pair
//
private RsaKeyParameters pub8 = new RsaKeyParameters(false,
new BigInteger("495370a1fb18543c16d3631e3163255df62be6eee890d5f25509e4f778a8ea6fbbbcdf85dff64e0d972003ab3681fbba6dd41fd541829b2e582de9f2a4a4e0a2d0900bef4753db3cee0ee06c7dfae8b1d53b5953218f9cceea695b08668edeaadced9463b1d790d5ebf27e9115b46cad4d9a2b8efab0561b0810344739ada0733f", 16),
new BigInteger("010001", 16));
private RsaKeyParameters prv8 = new RsaPrivateCrtKeyParameters(
new BigInteger("495370a1fb18543c16d3631e3163255df62be6eee890d5f25509e4f778a8ea6fbbbcdf85dff64e0d972003ab3681fbba6dd41fd541829b2e582de9f2a4a4e0a2d0900bef4753db3cee0ee06c7dfae8b1d53b5953218f9cceea695b08668edeaadced9463b1d790d5ebf27e9115b46cad4d9a2b8efab0561b0810344739ada0733f", 16),
new BigInteger("010001", 16),
new BigInteger("6c66ffe98980c38fcdeab5159898836165f4b4b817c4f6a8d486ee4ea9130fe9b9092bd136d184f95f504a607eac565846d2fdd6597a8967c7396ef95a6eeebb4578a643966dca4d8ee3de842de63279c618159c1ab54a89437b6a6120e4930afb52a4ba6ced8a4947ac64b30a3497cbe701c2d6266d517219ad0ec6d347dbe9", 16),
new BigInteger("08dad7f11363faa623d5d6d5e8a319328d82190d7127d2846c439b0ab72619b0a43a95320e4ec34fc3a9cea876422305bd76c5ba7be9e2f410c8060645a1d29edb", 16),
new BigInteger("0847e732376fc7900f898ea82eb2b0fc418565fdae62f7d9ec4ce2217b97990dd272db157f99f63c0dcbb9fbacdbd4c4dadb6df67756358ca4174825b48f49706d", 16),
new BigInteger("05c2a83c124b3621a2aa57ea2c3efe035eff4560f33ddebb7adab81fce69a0c8c2edc16520dda83d59a23be867963ac65f2cc710bbcfb96ee103deb771d105fd85", 16),
new BigInteger("04cae8aa0d9faa165c87b682ec140b8ed3b50b24594b7a3b2c220b3669bb819f984f55310a1ae7823651d4a02e99447972595139363434e5e30a7e7d241551e1b9", 16),
new BigInteger("07d3e47bf686600b11ac283ce88dbb3f6051e8efd04680e44c171ef531b80b2b7c39fc766320e2cf15d8d99820e96ff30dc69691839c4b40d7b06e45307dc91f3f", 16));
// PSS Example 8.1
private byte[] msg8a = Hex.Decode("81332f4be62948415ea1d899792eeacf6c6e1db1da8be13b5cea41db2fed467092e1ff398914c714259775f595f8547f735692a575e6923af78f22c6997ddb90fb6f72d7bb0dd5744a31decd3dc3685849836ed34aec596304ad11843c4f88489f209735f5fb7fdaf7cec8addc5818168f880acbf490d51005b7a8e84e43e54287977571dd99eea4b161eb2df1f5108f12a4142a83322edb05a75487a3435c9a78ce53ed93bc550857d7a9fb");
private byte[] slt8a = Hex.Decode("1d65491d79c864b373009be6f6f2467bac4c78fa");
private byte[] sig8a = Hex.Decode("0262ac254bfa77f3c1aca22c5179f8f040422b3c5bafd40a8f21cf0fa5a667ccd5993d42dbafb409c520e25fce2b1ee1e716577f1efa17f3da28052f40f0419b23106d7845aaf01125b698e7a4dfe92d3967bb00c4d0d35ba3552ab9a8b3eef07c7fecdbc5424ac4db1e20cb37d0b2744769940ea907e17fbbca673b20522380c5");
// PSS Example 8.2
private byte[] msg8b = Hex.Decode("e2f96eaf0e05e7ba326ecca0ba7fd2f7c02356f3cede9d0faabf4fcc8e60a973e5595fd9ea08");
private byte[] slt8b = Hex.Decode("435c098aa9909eb2377f1248b091b68987ff1838");
private byte[] sig8b = Hex.Decode("2707b9ad5115c58c94e932e8ec0a280f56339e44a1b58d4ddcff2f312e5f34dcfe39e89c6a94dcee86dbbdae5b79ba4e0819a9e7bfd9d982e7ee6c86ee68396e8b3a14c9c8f34b178eb741f9d3f121109bf5c8172fada2e768f9ea1433032c004a8aa07eb990000a48dc94c8bac8aabe2b09b1aa46c0a2aa0e12f63fbba775ba7e");
//
// Example 9: A 1536-bit RSA key pair
//
private RsaKeyParameters pub9 = new RsaKeyParameters(false,
new BigInteger("e6bd692ac96645790403fdd0f5beb8b9bf92ed10007fc365046419dd06c05c5b5b2f48ecf989e4ce269109979cbb40b4a0ad24d22483d1ee315ad4ccb1534268352691c524f6dd8e6c29d224cf246973aec86c5bf6b1401a850d1b9ad1bb8cbcec47b06f0f8c7f45d3fc8f319299c5433ddbc2b3053b47ded2ecd4a4caefd614833dc8bb622f317ed076b8057fe8de3f84480ad5e83e4a61904a4f248fb397027357e1d30e463139815c6fd4fd5ac5b8172a45230ecb6318a04f1455d84e5a8b", 16),
new BigInteger("010001", 16));
private RsaKeyParameters prv9 = new RsaPrivateCrtKeyParameters(
new BigInteger("e6bd692ac96645790403fdd0f5beb8b9bf92ed10007fc365046419dd06c05c5b5b2f48ecf989e4ce269109979cbb40b4a0ad24d22483d1ee315ad4ccb1534268352691c524f6dd8e6c29d224cf246973aec86c5bf6b1401a850d1b9ad1bb8cbcec47b06f0f8c7f45d3fc8f319299c5433ddbc2b3053b47ded2ecd4a4caefd614833dc8bb622f317ed076b8057fe8de3f84480ad5e83e4a61904a4f248fb397027357e1d30e463139815c6fd4fd5ac5b8172a45230ecb6318a04f1455d84e5a8b", 16),
new BigInteger("010001", 16),
new BigInteger("6a7fd84fb85fad073b34406db74f8d61a6abc12196a961dd79565e9da6e5187bce2d980250f7359575359270d91590bb0e427c71460b55d51410b191bcf309fea131a92c8e702738fa719f1e0041f52e40e91f229f4d96a1e6f172e15596b4510a6daec26105f2bebc53316b87bdf21311666070e8dfee69d52c71a976caae79c72b68d28580dc686d9f5129d225f82b3d615513a882b3db91416b48ce08888213e37eeb9af800d81cab328ce420689903c00c7b5fd31b75503a6d419684d629", 16),
new BigInteger("f8eb97e98df12664eefdb761596a69ddcd0e76daece6ed4bf5a1b50ac086f7928a4d2f8726a77e515b74da41988f220b1cc87aa1fc810ce99a82f2d1ce821edced794c6941f42c7a1a0b8c4d28c75ec60b652279f6154a762aed165d47dee367", 16),
new BigInteger("ed4d71d0a6e24b93c2e5f6b4bbe05f5fb0afa042d204fe3378d365c2f288b6a8dad7efe45d153eef40cacc7b81ff934002d108994b94a5e4728cd9c963375ae49965bda55cbf0efed8d6553b4027f2d86208a6e6b489c176128092d629e49d3d", 16),
new BigInteger("2bb68bddfb0c4f56c8558bffaf892d8043037841e7fa81cfa61a38c5e39b901c8ee71122a5da2227bd6cdeeb481452c12ad3d61d5e4f776a0ab556591befe3e59e5a7fddb8345e1f2f35b9f4cee57c32414c086aec993e9353e480d9eec6289f", 16),
new BigInteger("4ff897709fad079746494578e70fd8546130eeab5627c49b080f05ee4ad9f3e4b7cba9d6a5dff113a41c3409336833f190816d8a6bc42e9bec56b7567d0f3c9c696db619b245d901dd856db7c8092e77e9a1cccd56ee4dba42c5fdb61aec2669", 16),
new BigInteger("77b9d1137b50404a982729316efafc7dfe66d34e5a182600d5f30a0a8512051c560d081d4d0a1835ec3d25a60f4e4d6aa948b2bf3dbb5b124cbbc3489255a3a948372f6978496745f943e1db4f18382ceaa505dfc65757bb3f857a58dce52156", 16));
// PSS Example 9.1
private byte[] msg9a = Hex.Decode("a88e265855e9d7ca36c68795f0b31b591cd6587c71d060a0b3f7f3eaef43795922028bc2b6ad467cfc2d7f659c5385aa70ba3672cdde4cfe4970cc7904601b278872bf51321c4a972f3c95570f3445d4f57980e0f20df54846e6a52c668f1288c03f95006ea32f562d40d52af9feb32f0fa06db65b588a237b34e592d55cf979f903a642ef64d2ed542aa8c77dc1dd762f45a59303ed75e541ca271e2b60ca709e44fa0661131e8d5d4163fd8d398566ce26de8730e72f9cca737641c244159420637028df0a18079d6208ea8b4711a2c750f5");
private byte[] slt9a = Hex.Decode("c0a425313df8d7564bd2434d311523d5257eed80");
private byte[] sig9a = Hex.Decode("586107226c3ce013a7c8f04d1a6a2959bb4b8e205ba43a27b50f124111bc35ef589b039f5932187cb696d7d9a32c0c38300a5cdda4834b62d2eb240af33f79d13dfbf095bf599e0d9686948c1964747b67e89c9aba5cd85016236f566cc5802cb13ead51bc7ca6bef3b94dcbdbb1d570469771df0e00b1a8a06777472d2316279edae86474668d4e1efff95f1de61c6020da32ae92bbf16520fef3cf4d88f61121f24bbd9fe91b59caf1235b2a93ff81fc403addf4ebdea84934a9cdaf8e1a9e");
// PSS Example 9.2
private byte[] msg9b = Hex.Decode("c8c9c6af04acda414d227ef23e0820c3732c500dc87275e95b0d095413993c2658bc1d988581ba879c2d201f14cb88ced153a01969a7bf0a7be79c84c1486bc12b3fa6c59871b6827c8ce253ca5fefa8a8c690bf326e8e37cdb96d90a82ebab69f86350e1822e8bd536a2e");
private byte[] slt9b = Hex.Decode("b307c43b4850a8dac2f15f32e37839ef8c5c0e91");
private byte[] sig9b = Hex.Decode("80b6d643255209f0a456763897ac9ed259d459b49c2887e5882ecb4434cfd66dd7e1699375381e51cd7f554f2c271704b399d42b4be2540a0eca61951f55267f7c2878c122842dadb28b01bd5f8c025f7e228418a673c03d6bc0c736d0a29546bd67f786d9d692ccea778d71d98c2063b7a71092187a4d35af108111d83e83eae46c46aa34277e06044589903788f1d5e7cee25fb485e92949118814d6f2c3ee361489016f327fb5bc517eb50470bffa1afa5f4ce9aa0ce5b8ee19bf5501b958");
public override string Name
{
get { return "PssBlindTest"; }
}
private void testSig(
int id,
RsaKeyParameters pub,
RsaKeyParameters prv,
byte[] slt,
byte[] msg,
byte[] sig)
{
RsaBlindingFactorGenerator blindFactorGen = new RsaBlindingFactorGenerator();
RsaBlindingEngine blindingEngine = new RsaBlindingEngine();
PssSigner blindSigner = new PssSigner(blindingEngine, new Sha1Digest(), 20);
PssSigner signer = new PssSigner(new RsaEngine(), new Sha1Digest(), 20);
blindFactorGen.Init(pub);
BigInteger blindFactor = blindFactorGen.GenerateBlindingFactor();
RsaBlindingParameters parameters = new RsaBlindingParameters(pub, blindFactor);
// generate a blind signature
blindSigner.Init(true, new ParametersWithRandom(parameters, new FixedRandom(slt)));
blindSigner.BlockUpdate(msg, 0, msg.Length);
byte[] blindedData = blindSigner.GenerateSignature();
RsaEngine signerEngine = new RsaEngine();
signerEngine.Init(true, prv);
byte[] blindedSig = signerEngine.ProcessBlock(blindedData, 0, blindedData.Length);
// unblind the signature
blindingEngine.Init(false, parameters);
byte[] s = blindingEngine.ProcessBlock(blindedSig, 0, blindedSig.Length);
//signature verification
if (!AreEqual(s, sig))
{
Fail("test " + id + " failed generation");
}
//verify signature with PssSigner
signer.Init(false, pub);
signer.BlockUpdate(msg, 0, msg.Length);
if (!signer.VerifySignature(s))
{
Fail("test " + id + " failed PssSigner verification");
}
}
private bool isProcessingOkay(
RsaKeyParameters pub,
RsaKeyParameters prv,
byte[] data,
SecureRandom random)
{
RsaBlindingFactorGenerator blindFactorGen = new RsaBlindingFactorGenerator();
RsaBlindingEngine blindingEngine = new RsaBlindingEngine();
PssSigner blindSigner = new PssSigner(blindingEngine, new Sha1Digest(), 20);
PssSigner pssEng = new PssSigner(new RsaEngine(), new Sha1Digest(), 20);
random.NextBytes(data);
blindFactorGen.Init(pub);
BigInteger blindFactor = blindFactorGen.GenerateBlindingFactor();
RsaBlindingParameters parameters = new RsaBlindingParameters(pub, blindFactor);
// generate a blind signature
blindSigner.Init(true, new ParametersWithRandom(parameters, random));
blindSigner.BlockUpdate(data, 0, data.Length);
byte[] blindedData = blindSigner.GenerateSignature();
RsaEngine signerEngine = new RsaEngine();
signerEngine.Init(true, prv);
byte[] blindedSig = signerEngine.ProcessBlock(blindedData, 0, blindedData.Length);
// unblind the signature
blindingEngine.Init(false, parameters);
byte[] s = blindingEngine.ProcessBlock(blindedSig, 0, blindedSig.Length);
//verify signature with PssSigner
pssEng.Init(false, pub);
pssEng.BlockUpdate(data, 0, data.Length);
return pssEng.VerifySignature(s);
}
public override void PerformTest()
{
testSig(1, pub1, prv1, slt1a, msg1a, sig1a);
testSig(2, pub1, prv1, slt1b, msg1b, sig1b);
testSig(3, pub2, prv2, slt2a, msg2a, sig2a);
testSig(4, pub2, prv2, slt2b, msg2b, sig2b);
testSig(5, pub4, prv4, slt4a, msg4a, sig4a);
testSig(6, pub4, prv4, slt4b, msg4b, sig4b);
testSig(7, pub8, prv8, slt8a, msg8a, sig8a);
testSig(8, pub8, prv8, slt8b, msg8b, sig8b);
testSig(9, pub9, prv9, slt9a, msg9a, sig9a);
testSig(10, pub9, prv9, slt9b, msg9b, sig9b);
//
// loop test
//
int failed = 0;
byte[] data = new byte[DATA_LENGTH];
SecureRandom random = new SecureRandom();
RsaKeyParameters[] kprv ={prv1, prv2, prv4, prv8, prv9};
RsaKeyParameters[] kpub ={pub1, pub2, pub4, pub8, pub9};
for (int j = 0, i = 0; j < NUM_TESTS; j++, i++)
{
if (i == kprv.Length)
{
i = 0;
}
if (!isProcessingOkay(kpub[i], kprv[i], data, random))
{
failed++;
}
}
if (failed != 0)
{
Fail("loop test failed - failures: " + failed);
}
//
// key generation test
//
RsaKeyPairGenerator pGen = new RsaKeyPairGenerator();
RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25);
pGen.Init(genParam);
failed = 0;
for (int k = 0; k < NUM_TESTS_WITH_KEY_GENERATION; k++)
{
AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();
for (int j = 0; j < NUM_TESTS; j++)
{
if (!isProcessingOkay((RsaKeyParameters)pair.Public, (RsaKeyParameters)pair.Private, data, random))
{
failed++;
}
}
}
if (failed != 0)
{
Fail("loop test with key generation failed - failures: " + failed);
}
}
public static void Main(
string[] args)
{
RunTest(new PssBlindTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="JavaScriptSerializer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Script.Serialization {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Resources;
public class JavaScriptSerializer {
internal const string ServerTypeFieldName = "__type";
internal const int DefaultRecursionLimit = 100;
internal const int DefaultMaxJsonLength = 2097152;
internal static string SerializeInternal(object o) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(o);
}
internal static object Deserialize(JavaScriptSerializer serializer, string input, Type type, int depthLimit) {
if (input == null) {
throw new ArgumentNullException("input");
}
if (input.Length > serializer.MaxJsonLength) {
throw new ArgumentException(AtlasWeb.JSON_MaxJsonLengthExceeded, "input");
}
object o = JavaScriptObjectDeserializer.BasicDeserialize(input, depthLimit, serializer);
return ObjectConverter.ConvertObjectToType(o, type, serializer);
}
// INSTANCE fields/methods
private JavaScriptTypeResolver _typeResolver;
private int _recursionLimit;
private int _maxJsonLength;
public JavaScriptSerializer() : this(null) { }
public JavaScriptSerializer(JavaScriptTypeResolver resolver) {
_typeResolver = resolver;
RecursionLimit = DefaultRecursionLimit;
MaxJsonLength = DefaultMaxJsonLength;
}
public int MaxJsonLength {
get {
return _maxJsonLength;
}
set {
if (value < 1) {
throw new ArgumentOutOfRangeException(AtlasWeb.JSON_InvalidMaxJsonLength);
}
_maxJsonLength = value;
}
}
public int RecursionLimit {
get {
return _recursionLimit;
}
set {
if (value < 1) {
throw new ArgumentOutOfRangeException(AtlasWeb.JSON_InvalidRecursionLimit);
}
_recursionLimit = value;
}
}
internal JavaScriptTypeResolver TypeResolver {
get {
return _typeResolver;
}
}
private Dictionary<Type, JavaScriptConverter> _converters;
private Dictionary<Type, JavaScriptConverter> Converters {
get {
if (_converters == null) {
_converters = new Dictionary<Type, JavaScriptConverter>();
}
return _converters;
}
}
[SuppressMessage("Microsoft.Usage", "CA2301:EmbeddableTypesInContainersRule", MessageId = "Converters", Justification = "This is for managed types which need to have custom type converters for JSon serialization, I don't think there will be any com interop types for this scenario.")]
public void RegisterConverters(IEnumerable<JavaScriptConverter> converters)
{
if (converters == null) {
throw new ArgumentNullException("converters");
}
foreach (JavaScriptConverter converter in converters) {
IEnumerable<Type> supportedTypes = converter.SupportedTypes;
if (supportedTypes != null) {
foreach (Type supportedType in supportedTypes) {
Converters[supportedType] = converter;
}
}
}
}
[SuppressMessage("Microsoft.Usage", "CA2301:EmbeddableTypesInContainersRule", MessageId = "_converters", Justification = "This is for managed types which need to have custom type converters for JSon serialization, I don't think there will be any com interop types for this scenario.")]
private JavaScriptConverter GetConverter(Type t)
{
if (_converters != null) {
while (t != null) {
if (_converters.ContainsKey(t)) {
return _converters[t];
}
t = t.BaseType;
}
}
return null;
}
internal bool ConverterExistsForType(Type t, out JavaScriptConverter converter) {
converter = GetConverter(t);
return converter != null;
}
public object DeserializeObject(string input) {
return Deserialize(this, input, null /*type*/, RecursionLimit);
}
[
SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter",
Justification = "Generic parameter is preferable to forcing caller to downcast. " +
"Has has been approved by API review board. " +
"Dev10 701126: Overload added afterall, to allow runtime determination of the type.")
]
public T Deserialize<T>(string input) {
return (T)Deserialize(this, input, typeof(T), RecursionLimit);
}
public object Deserialize(string input, Type targetType) {
return Deserialize(this, input, targetType, RecursionLimit);
}
[
SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter",
Justification = "Generic parameter is preferable to forcing caller to downcast. " +
"Has has been approved by API review board. " +
"Dev10 701126: Overload added afterall, to allow runtime determination of the type."),
SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj",
Justification = "Cannot change parameter name as would break binary compatibility with legacy apps.")
]
public T ConvertToType<T>(object obj) {
return (T)ObjectConverter.ConvertObjectToType(obj, typeof(T), this);
}
[
SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj",
Justification = "Consistent with previously existing overload which cannot be changed.")
]
public object ConvertToType(object obj, Type targetType) {
return ObjectConverter.ConvertObjectToType(obj, targetType, this);
}
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj",
Justification = "Cannot change parameter name as would break binary compatibility with legacy apps.")]
public string Serialize(object obj) {
return Serialize(obj, SerializationFormat.JSON);
}
internal string Serialize(object obj, SerializationFormat serializationFormat) {
StringBuilder sb = new StringBuilder();
Serialize(obj, sb, serializationFormat);
return sb.ToString();
}
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj",
Justification = "Cannot change parameter name as would break binary compatibility with legacy apps.")]
public void Serialize(object obj, StringBuilder output) {
Serialize(obj, output, SerializationFormat.JSON);
}
internal void Serialize(object obj, StringBuilder output, SerializationFormat serializationFormat) {
SerializeValue(obj, output, 0, null, serializationFormat);
// DevDiv Bugs 96574: Max JSON length does not apply when serializing to Javascript for ScriptDescriptors
if (serializationFormat == SerializationFormat.JSON && output.Length > MaxJsonLength) {
throw new InvalidOperationException(AtlasWeb.JSON_MaxJsonLengthExceeded);
}
}
private static void SerializeBoolean(bool o, StringBuilder sb) {
if (o) {
sb.Append("true");
}
else {
sb.Append("false");
}
}
private static void SerializeUri(Uri uri, StringBuilder sb) {
sb.Append("\"").Append(uri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped)).Append("\"");
}
private static void SerializeGuid(Guid guid, StringBuilder sb) {
sb.Append("\"").Append(guid.ToString()).Append("\"");
}
internal static readonly long DatetimeMinTimeTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;
private static void SerializeDateTime(DateTime datetime, StringBuilder sb, SerializationFormat serializationFormat) {
Debug.Assert(serializationFormat == SerializationFormat.JSON || serializationFormat == SerializationFormat.JavaScript);
if (serializationFormat == SerializationFormat.JSON) {
// DevDiv 41127: Never confuse atlas serialized strings with dates
// Serialized date: "\/Date(123)\/"
sb.Append(@"""\/Date(");
sb.Append((datetime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
sb.Append(@")\/""");
}
else {
// DevDiv 96574: Need to be able to serialize to javascript dates for script descriptors
// new Date(ticks)
sb.Append("new Date(");
sb.Append((datetime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
sb.Append(@")");
}
}
// Serialize custom object graph
private void SerializeCustomObject(object o, StringBuilder sb, int depth, Hashtable objectsInUse, SerializationFormat serializationFormat) {
bool first = true;
Type type = o.GetType();
sb.Append('{');
// Serialize the object type if we have a type resolver
if (TypeResolver != null) {
// Only do this if the context is actually aware of this type
string typeString = TypeResolver.ResolveTypeId(type);
if (typeString != null) {
SerializeString(ServerTypeFieldName, sb);
sb.Append(':');
SerializeValue(typeString, sb, depth, objectsInUse, serializationFormat);
first = false;
}
}
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo fieldInfo in fields) {
// Ignore all fields marked as [ScriptIgnore]
if (CheckScriptIgnoreAttribute(fieldInfo)) {
continue;
}
if (!first) sb.Append(',');
SerializeString(fieldInfo.Name, sb);
sb.Append(':');
SerializeValue(SecurityUtils.FieldInfoGetValue(fieldInfo, o), sb, depth, objectsInUse, serializationFormat, currentMember: fieldInfo);
first = false;
}
PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);
foreach (PropertyInfo propInfo in props) {
// Ignore all properties marked as [ScriptIgnore]
if (CheckScriptIgnoreAttribute(propInfo))
continue;
MethodInfo getMethodInfo = propInfo.GetGetMethod();
// Skip property if it has no get
if (getMethodInfo == null) {
continue;
}
// Ignore indexed properties
if (getMethodInfo.GetParameters().Length > 0) continue;
if (!first) sb.Append(',');
SerializeString(propInfo.Name, sb);
sb.Append(':');
SerializeValue(SecurityUtils.MethodInfoInvoke(getMethodInfo, o, null), sb, depth, objectsInUse, serializationFormat, currentMember: propInfo);
first = false;
}
sb.Append('}');
}
private bool CheckScriptIgnoreAttribute(MemberInfo memberInfo) {
// Ignore all members marked as [ScriptIgnore]
if (memberInfo.IsDefined(typeof(ScriptIgnoreAttribute), true /*inherits*/)) return true;
//The above API does not consider the inherit boolean and the right API for that is Attribute.IsDefined.
//However, to keep the backward compatibility with 4.0, we decided to define an opt-in mechanism (ApplyToOverrides property on ScriptIgnoreAttribute)
//to consider the inherit boolean.
ScriptIgnoreAttribute scriptIgnoreAttr = (ScriptIgnoreAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(ScriptIgnoreAttribute), inherit: true);
if (scriptIgnoreAttr != null && scriptIgnoreAttr.ApplyToOverrides) {
return true;
}
return false;
}
private void SerializeDictionary(IDictionary o, StringBuilder sb, int depth, Hashtable objectsInUse, SerializationFormat serializationFormat) {
sb.Append('{');
bool isFirstElement = true;
bool isTypeEntrySet = false;
//make sure __type field is the first to be serialized if it exists
if (o.Contains(ServerTypeFieldName)) {
isFirstElement = false;
isTypeEntrySet = true;
SerializeDictionaryKeyValue(ServerTypeFieldName, o[ServerTypeFieldName], sb, depth, objectsInUse, serializationFormat);
}
foreach (DictionaryEntry entry in (IDictionary)o) {
string key = entry.Key as string;
if (key == null) {
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_DictionaryTypeNotSupported, o.GetType().FullName));
}
if (isTypeEntrySet && String.Equals(key, ServerTypeFieldName, StringComparison.Ordinal)) {
// The dictionay only contains max one entry for __type key, and it has been iterated
// through, so don't need to check for is anymore.
isTypeEntrySet = false;
continue;
}
if (!isFirstElement) {
sb.Append(',');
}
SerializeDictionaryKeyValue(key, entry.Value, sb, depth, objectsInUse, serializationFormat);
isFirstElement = false;
}
sb.Append('}');
}
private void SerializeDictionaryKeyValue(string key, object value, StringBuilder sb, int depth, Hashtable objectsInUse, SerializationFormat serializationFormat) {
SerializeString(key, sb);
sb.Append(':');
SerializeValue(value, sb, depth, objectsInUse, serializationFormat);
}
private void SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, int depth, Hashtable objectsInUse, SerializationFormat serializationFormat) {
sb.Append('[');
bool isFirstElement = true;
foreach (object o in enumerable) {
if (!isFirstElement) {
sb.Append(',');
}
SerializeValue(o, sb, depth, objectsInUse, serializationFormat);
isFirstElement = false;
}
sb.Append(']');
}
private static void SerializeString(string input, StringBuilder sb) {
sb.Append('"');
sb.Append(HttpUtility.JavaScriptStringEncode(input));
sb.Append('"');
}
private void SerializeValue(object o, StringBuilder sb, int depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember = null) {
if (++depth > _recursionLimit) {
throw new ArgumentException(AtlasWeb.JSON_DepthLimitExceeded);
}
// Check whether a custom converter is available for this type.
JavaScriptConverter converter = null;
if (o != null && ConverterExistsForType(o.GetType(), out converter)) {
IDictionary<string, object> dict = converter.Serialize(o, this);
if (TypeResolver != null) {
string typeString = TypeResolver.ResolveTypeId(o.GetType());
if (typeString != null) {
dict[ServerTypeFieldName] = typeString;
}
}
sb.Append(Serialize(dict, serializationFormat));
return;
}
SerializeValueInternal(o, sb, depth, objectsInUse, serializationFormat, currentMember);
}
// We use this for our cycle detection for the case where objects override equals/gethashcode
private class ReferenceComparer : IEqualityComparer {
bool IEqualityComparer.Equals(object x, object y) {
return x == y;
}
int IEqualityComparer.GetHashCode(object obj) {
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
}
private void SerializeValueInternal(object o, StringBuilder sb, int depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) {
// 'null' is a special JavaScript token
if (o == null || DBNull.Value.Equals(o)) {
sb.Append("null");
return;
}
// Strings and chars are represented as quoted (single or double) in Javascript.
string os = o as String;
if (os != null) {
SerializeString(os, sb);
return;
}
if (o is Char) {
// Special case the null char as we don't want it to turn into a null string
if ((char)o == '\0') {
sb.Append("null");
return;
}
SerializeString(o.ToString(), sb);
return;
}
// Bools are represented as 'true' and 'false' (no quotes) in Javascript.
if (o is bool) {
SerializeBoolean((bool)o, sb);
return;
}
if (o is DateTime) {
SerializeDateTime((DateTime)o, sb, serializationFormat);
return;
}
if (o is DateTimeOffset) {
// DateTimeOffset is converted to a UTC DateTime and serialized as usual.
SerializeDateTime(((DateTimeOffset)o).UtcDateTime, sb, serializationFormat);
return;
}
if (o is Guid) {
SerializeGuid((Guid)o, sb);
return;
}
Uri uri = o as Uri;
if (uri != null) {
SerializeUri(uri, sb);
return;
}
// Have to special case floats to get full precision
if (o is double) {
sb.Append(((double)o).ToString("r", CultureInfo.InvariantCulture));
return;
}
if (o is float) {
sb.Append(((float)o).ToString("r", CultureInfo.InvariantCulture));
return;
}
// Deal with any server type that can be represented as a number in JavaScript
if (o.GetType().IsPrimitive || o is Decimal) {
IConvertible convertible = o as IConvertible;
if (convertible != null) {
sb.Append(convertible.ToString(CultureInfo.InvariantCulture));
}
else {
// In theory, all primitive types implement IConvertible
Debug.Assert(false);
sb.Append(o.ToString());
}
return;
}
// Serialize enums as their integer value
Type type = o.GetType();
if (type.IsEnum) {
// Int64 and UInt64 result in numbers too big for JavaScript
Type underlyingType = Enum.GetUnderlyingType(type);
if ((underlyingType == typeof(Int64)) || (underlyingType == typeof(UInt64))) {
// DevDiv #286382 - Try to provide a better error message by saying exactly what property failed.
string errorMessage = (currentMember != null)
? String.Format(CultureInfo.CurrentCulture, AtlasWeb.JSON_CannotSerializeMemberGeneric, currentMember.Name, currentMember.ReflectedType.FullName) + " " + AtlasWeb.JSON_InvalidEnumType
: AtlasWeb.JSON_InvalidEnumType;
throw new InvalidOperationException(errorMessage);
}
// DevDiv Bugs 154763: call ToString("D") rather than cast to int
// to support enums that are based on other integral types
sb.Append(((Enum)o).ToString("D"));
return;
}
try {
// The following logic performs circular reference detection
if (objectsInUse == null) {
// Create the table on demand
objectsInUse = new Hashtable(new ReferenceComparer());
}
else if (objectsInUse.ContainsKey(o)) {
// If the object is already there, we have a circular reference!
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.JSON_CircularReference, type.FullName));
}
// Add the object to the objectsInUse
objectsInUse.Add(o, null);
// Dictionaries are represented as Javascript objects. e.g. { name1: val1, name2: val2 }
IDictionary od = o as IDictionary;
if (od != null) {
SerializeDictionary(od, sb, depth, objectsInUse, serializationFormat);
return;
}
// Enumerations are represented as Javascript arrays. e.g. [ val1, val2 ]
IEnumerable oenum = o as IEnumerable;
if (oenum != null) {
SerializeEnumerable(oenum, sb, depth, objectsInUse, serializationFormat);
return;
}
// Serialize all public fields and properties.
SerializeCustomObject(o, sb, depth, objectsInUse, serializationFormat);
}
finally {
// Remove the object from the circular reference detection table
if (objectsInUse != null) {
objectsInUse.Remove(o);
}
}
}
internal enum SerializationFormat {
JSON,
JavaScript
}
}
}
| |
using System;
using UnityEditor;
using UnityEngine;
namespace DFTGames.Tools.EditorTools
{
public class GameDataEditor : EditorWindow
{
public const int NON_ESISTE = -1;
public GameData gameData;
// public const string STR_PercorsoConfig = "PercorsoConfigurazione";
// public const string STR_DatabaseDiGioco = "/dataBaseDiGioco.asset";
private Color OriginalBg = GUI.backgroundColor;
private Color OriginalCont = GUI.contentColor;
private Color OriginalColor = GUI.color;
private static bool preferenzeCaricate = false;
private static string percorso;
private Vector2 posizioneScroll;
Texture icon1 = EditorGUIUtility.LoadRequired(string.Format("{0}/icon1.png", ResourceHelper.DFTGamesFolderPath)) as Texture; //Amico
Texture icon2 = EditorGUIUtility.LoadRequired(string.Format("{0}/icon2.png", ResourceHelper.DFTGamesFolderPath)) as Texture; //Nemico
Texture icon3 = EditorGUIUtility.LoadRequired(string.Format("{0}/icon3.png", ResourceHelper.DFTGamesFolderPath)) as Texture; //Neutro
[PreferenceItem("Alleanze")]
private static void preferenzeDiGameGUI()
{
if (!preferenzeCaricate)
{
percorso = EditorPrefs.GetString(Statici.STR_PercorsoConfig);
preferenzeCaricate = true;
}
GUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
if (GUILayout.Button("...", GUILayout.Width(30)))
{
string tmpStr = "Assets";
string tmpPercosro = EditorUtility.OpenFolderPanel("Percorso del Database", tmpStr, "");
if (tmpPercosro != string.Empty)
{
percorso = "Assets" + tmpPercosro.Substring(Application.dataPath.Length);
EditorPrefs.SetString(Statici.STR_PercorsoConfig, percorso);
}
}
GUILayout.Label(percorso);
GUILayout.EndHorizontal();
}
[MenuItem("Window/ToolsGame/Configurazione Diplomazia %&D")]
private static void Init()
{
EditorWindow.GetWindow<GameDataEditor>("Editor Alleanze");
}
private void OnEnable()
{
if (EditorPrefs.HasKey(Statici.STR_PercorsoConfig))
{
percorso = EditorPrefs.GetString(Statici.STR_PercorsoConfig);
gameData = AssetDatabase.LoadAssetAtPath<GameData>(percorso + Statici.STR_DatabaseDiGioco);
}
}
private void OnGUI()
{
if (gameData != null)
{
GUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
GUILayout.Label("Editor by DFT Students", GUI.skin.GetStyle("Label"));
GUILayout.EndHorizontal();
EditorGUILayout.Separator();
GestisciDiplomazia();
}
else
{
GUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
if (GUILayout.Button("Crea il DataBase"))
{
gameData = CreaDatabase();
}
EditorGUILayout.HelpBox("DataBase Mancante", MessageType.Error);
GUILayout.EndHorizontal();
}
}
public static GameData CreaDatabase()
{
string tmpStr = "Assets";
GameData gameData = null;
if (percorso == null || percorso == string.Empty)
{
string tmpPercosro = EditorUtility.OpenFolderPanel("Percorso per Database", tmpStr, "");
if (tmpPercosro != string.Empty)
{
percorso = "Assets" + tmpPercosro.Substring(Application.dataPath.Length);
EditorPrefs.SetString(Statici.STR_PercorsoConfig, percorso);
}
}
if (percorso != string.Empty)
{
gameData = ScriptableObject.CreateInstance<GameData>();
AssetDatabase.CreateAsset(gameData, percorso + Statici.STR_DatabaseDiGioco);
AssetDatabase.Refresh();
ProjectWindowUtil.ShowCreatedAsset(gameData);
}
resettaParametri(gameData);
return gameData;
}
private void GestisciDiplomazia()
{
GUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
GUIStyle stileEtichetta = new GUIStyle(GUI.skin.GetStyle("Label"));
stileEtichetta.alignment = TextAnchor.MiddleCenter;
stileEtichetta.fontStyle = FontStyle.Bold;
stileEtichetta.fontSize = 14;
GUIStyle stileEtichetta2 = new GUIStyle(GUI.skin.GetStyle("Label"));
stileEtichetta2.alignment = TextAnchor.MiddleLeft;
stileEtichetta2.fontStyle = FontStyle.Bold;
stileEtichetta2.fontSize = 11;
GUILayout.Label("Gestione Diplomazia", stileEtichetta);
GUILayout.EndHorizontal();
GUILayout.BeginVertical(EditorStyles.objectFieldThumb);
GUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
if (GUILayout.Button("Resetta", GUILayout.Width(100f)))
{
resettaParametri(gameData);
EditorUtility.SetDirty(gameData);
AssetDatabase.SaveAssets();
}
GUILayout.EndHorizontal();
GUILayout.BeginVertical(EditorStyles.objectFieldThumb);
GUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
GUILayout.Label(new GUIContent("Matrice Amicizie"), stileEtichetta, GUILayout.Width(140));
//codice necessario in caso di aggiunta o rimozione di un tag:
if (gameData.classiEssere.Length != Enum.GetValues(typeof(classiPersonaggi)).Length)
{
int vecchio = gameData.classiEssere.Length;
int differenzaLunghezze = Enum.GetValues(typeof(classiPersonaggi)).Length - gameData.classiEssere.Length;
Array.Resize<string>(ref gameData.classiEssere, Enum.GetValues(typeof(classiPersonaggi)).Length);
Array.Resize<classiAmicizie>(ref gameData.matriceAmicizie, Enum.GetValues(typeof(classiPersonaggi)).Length);
for (int i = 0; i < gameData.classiEssere.Length; i++)
{
if (gameData.matriceAmicizie[i] == null)
gameData.matriceAmicizie[i] = new classiAmicizie();
Array.Resize<Amicizie>(ref gameData.matriceAmicizie[i].elementoAmicizia, Enum.GetValues(typeof(classiPersonaggi)).Length);
}
if (differenzaLunghezze > 0)
{
Array tmpClassi = Enum.GetValues(typeof(classiPersonaggi));
for (int i = vecchio; i < tmpClassi.Length; i++)
{
gameData.classiEssere[i] = tmpClassi.GetValue(i).ToString();
for (int j = 0; j < tmpClassi.Length; j++)
{
gameData.matriceAmicizie[i].elementoAmicizia[j] = Amicizie.Neutro;
EditorUtility.SetDirty(gameData);
AssetDatabase.SaveAssets();
}
}
}
}
//codice necessario per l'aggiornamento dei dati in caso qualcosa venga modificato
for (int i = 0; i < gameData.classiEssere.Length; i++)
{
EditorGUILayout.LabelField(gameData.classiEssere[gameData.classiEssere.Length - i - 1], stileEtichetta2, GUILayout.Width(140));
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.BeginVertical((EditorStyles.objectFieldThumb));
for (int i = 0; i < gameData.classiEssere.Length; i++)
{
GUILayout.BeginHorizontal(EditorStyles.objectFieldThumb);
EditorGUILayout.LabelField(gameData.classiEssere[i], stileEtichetta2, GUILayout.Width(140));
for (int j = 0; j < (gameData.classiEssere.Length - i); j++)
{
//Qui recupera la texture da mettere al bottone che si sta mostrando
Texture tmp = new Texture();
switch (gameData.matriceAmicizie[i].elementoAmicizia[j])
{
case Amicizie.Neutro:
tmp = icon3;
break;
case Amicizie.Alleato:
tmp = icon1;
break;
case Amicizie.Nemico:
tmp = icon2;
break;
default:
tmp = icon3;
break;
}
//qui mostra il bottone con la texture recuperata in base al valore dell'Enum della matriceAmicizie
//Qui se clicchiamo il bottone deve assegnare un icona differente in base all'indice "di click"
if (GUILayout.Button(new GUIContent(tmp), GUIStyle.none, GUILayout.Width(140), GUILayout.Height(80)))
{
//valore dell'Enum usato come indice per l'icona
int numIcona = (int)gameData.matriceAmicizie[i].elementoAmicizia[j];
//Debug.Log("Letto da matrice: " + gameData.matriceAmicizie[i].elementoAmicizia[j] + " = a " + numIcona);
numIcona++;
numIcona = numIcona <= 3 ? numIcona : 1;
gameData.matriceAmicizie[i].elementoAmicizia[j] = (Amicizie)numIcona;
// gameData.matriceAmicizie[j].elementoAmicizia[i] = (Amicizie)numIcona;
EditorUtility.SetDirty(gameData);
AssetDatabase.SaveAssets();
//Debug.Log("cliccato bottone: " + i + "," + j + " - ValEnum: " + (Amicizie)numIcona);
}
}
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
}
private static void resettaParametri(GameData gameData)
{
Array tmpClassi = Enum.GetValues(typeof(classiPersonaggi));
for (int r = 0; r < tmpClassi.Length; r++)
{
gameData.classiEssere[r] = tmpClassi.GetValue(r).ToString();
}
for (int r = 0; r < Enum.GetValues(typeof(classiPersonaggi)).Length; r++)
{
for (int c = 0; c < Enum.GetValues(typeof(classiPersonaggi)).Length; c++)
{
gameData.matriceAmicizie[r].elementoAmicizia[c] = Amicizie.Neutro;
}
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A movie theater.
/// </summary>
public class MovieTheater_Core : TypeCore, IEntertainmentBusiness
{
public MovieTheater_Core()
{
this._TypeId = 171;
this._Id = "MovieTheater";
this._Schema_Org_Url = "http://schema.org/MovieTheater";
string label = "";
GetLabel(out label, "MovieTheater", typeof(MovieTheater_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,96};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{62,96};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152,47,75,77,94,95,130,137,36,60,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApiExternalAuth.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);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Globalization;
using System.Runtime.InteropServices;
using TrackRoamer.Robotics.Utility.LibSystem;
using TrackRoamer.Robotics.Utility.LibLvrGenericHid;
namespace TrackRoamer.Robotics.Utility.LibPicSensors
{
public class ProximityModuleEventArgs : System.EventArgs
{
public string description;
}
public partial class ProximityModule
{
// see http://msdn.microsoft.com/en-us/magazine/cc163417.aspx
private static object _lock = new object();
private static MessageWindow _window;
public static IntPtr WindowHandle;
internal class MessageWindow : Form
{
internal ProximityModule picpxmod;
protected override void WndProc(ref Message m)
{
try
{
// The OnDeviceChange routine processes WM_DEVICECHANGE messages.
if (m.Msg == DeviceManagement.WM_DEVICECHANGE)
{
picpxmod.OnDeviceChange(m);
}
// Let the base form process the message.
base.WndProc(ref m);
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
}
/// <summary>
/// we need this to catch device change events in a non-Winforms environment, which we have in MRDS DSS host.
/// </summary>
private void EnsureEventsWindowInitialized()
{
lock (_lock)
{
if (_window == null)
{
using (ManualResetEvent mre =
new ManualResetEvent(false))
{
Thread t = new Thread((ThreadStart)delegate
{
_window = new MessageWindow();
_window.picpxmod = this;
WindowHandle = _window.Handle;
mre.Set();
Application.Run();
});
t.Name = "MessageEvents";
t.IsBackground = true;
t.Start();
mre.WaitOne();
}
}
}
}
public event EventHandler<ProximityModuleEventArgs> DeviceAttachedEvent;
// Invoke the DeviceAttachedEvent event; called whenever the device is attached:
protected virtual void OnDeviceAttached(ProximityModuleEventArgs e)
{
if (DeviceAttachedEvent != null)
{
DeviceAttachedEvent(this, e);
}
}
public event EventHandler<ProximityModuleEventArgs> DeviceDetachedEvent;
// Invoke the DeviceDetachedEvent event; called whenever the device is detached:
protected virtual void OnDeviceDetached(ProximityModuleEventArgs e)
{
if (DeviceDetachedEvent != null)
{
DeviceDetachedEvent(this, e);
}
}
private IntPtr deviceNotificationHandle;
private Boolean exclusiveAccess;
private SafeFileHandle hidHandle;
private String hidUsage;
private Boolean myDeviceDetected;
private String myDevicePathName;
private SafeFileHandle readHandle;
private SafeFileHandle writeHandle;
private Debugging MyDebugging = new Debugging(); // For viewing results of API calls via Tracer.Write.
private DeviceManagement MyDeviceManagement = new DeviceManagement();
private Hid MyHid = null;
public readonly Int32 vendorId = 0; //0x0925; // see PIC Firmware - usb_descriptors.c lines 178,179
public readonly Int32 productId = 0; //0x7001;
bool UseControlTransfersOnly = false;
/// <summary>
/// Define a class of delegates that point to the Hid.ReportIn.Read function.
/// The delegate has the same parameters as Hid.ReportIn.Read.
/// Used for asynchronous reads from the device.
/// </summary>
private delegate void ReadInputReportDelegate(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, ref Boolean myDeviceDetected, ref Byte[] readBuffer, ref Boolean success);
// This delegate has the same parameters as AccessForm.
// Used in accessing the application's form from a different thread.
private delegate void MarshalToForm(String action, String textToAdd);
/// <summary>
/// Called when a WM_DEVICECHANGE message has arrived,
/// indicating that a device has been attached or removed.
/// </summary>
///
/// <param name="m"> a message with information about the device </param>
public void OnDeviceChange(Message m)
{
Tracer.Trace("ProximityModule (HID) USB OnDeviceChange() - m.WParam=" + m.WParam);
try
{
switch (m.WParam.ToInt32())
{
case DeviceManagement.DBT_DEVNODES_CHANGED:
// this one comes independent of the registration.
Tracer.Trace("DBT_DEVNODES_CHANGED");
if (!myDeviceDetected)
{
myDeviceDetected = FindTheHid(vendorId, productId);
if (myDeviceDetected)
{
OnDeviceAttached(new ProximityModuleEventArgs() { description = m.ToString() });
}
}
break;
case DeviceManagement.DBT_DEVICEARRIVAL:
// you have to issue MyDeviceManagement.RegisterForDeviceNotifications() first to receive this notification.
// If WParam contains DBT_DEVICEARRIVAL, a device has been attached.
Tracer.Trace("A USB device has been attached.");
// Find out if it's the device we're communicating with.
if (MyDeviceManagement.DeviceNameMatch(m, myDevicePathName))
{
Tracer.Trace("OK: My USB device (Proximity Module) attached.");
OnDeviceAttached(new ProximityModuleEventArgs() { description = m.ToString() });
}
break;
case DeviceManagement.DBT_DEVICEREMOVECOMPLETE:
// you have to issue MyDeviceManagement.RegisterForDeviceNotifications() first to receive this notification.
// If WParam contains DBT_DEVICEREMOVAL, a device has been removed.
Tracer.Trace("Warning: A USB device has been removed.");
// Find out if it's the device we're communicating with.
if (MyDeviceManagement.DeviceNameMatch(m, myDevicePathName))
{
Tracer.Trace("Warning: My device (Proximity Module) removed.");
// Set MyDeviceDetected False so on the next data-transfer attempt,
// FindTheHid() will be called to look for the device
// and get a new handle.
myDeviceDetected = false;
OnDeviceDetached(new ProximityModuleEventArgs() { description = m.ToString() });
}
break;
}
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
private void GetInputReportBufferSize()
{
Int32 numberOfInputBuffers = 0;
Boolean success;
try
{
// Get the number of input buffers.
success = MyHid.GetNumberOfInputBuffers(hidHandle, ref numberOfInputBuffers);
Tracer.Trace("Number of Input Buffers = " + numberOfInputBuffers);
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
/// <summary>
/// Uses a series of API calls to locate a HID-class device
/// by its Vendor ID and Product ID.
/// Fills myDevicePathName with a path to device found, readHandle and writeHandle. Registers for Device Notifications (attached / detached type of events).
/// </summary>
///
/// <returns>
/// True if the device is detected, False if not detected.
/// </returns>
private Boolean FindTheHid(Int32 myVendorID, Int32 myProductID)
{
Boolean someHidDevicesFound = false;
String[] devicePathName = new String[128];
String functionName = "";
Guid hidGuid = Guid.Empty;
Int32 memberIndex = 0;
Boolean success = false;
try
{
myDeviceDetected = false;
Tracer.Trace(string.Format("FindTheHid(0x{0:X04}, 0x{1:X04})", myVendorID, myProductID));
// ***
// API function: 'HidD_GetHidGuid
// Purpose: Retrieves the interface class GUID for the HID class.
// Accepts: 'A System.Guid object for storing the GUID.
// ***
Hid.HidD_GetHidGuid(ref hidGuid);
functionName = "GetHidGuid";
Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
Tracer.Trace(" GUID for system HIDs: " + hidGuid.ToString());
// Fill an array with the device path names of all attached HIDs.
someHidDevicesFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName);
// If there is at least one HID, attempt to read the Vendor ID and Product ID
// of each device until there is a match or all devices have been examined.
//
// Fill myDevicePathName with a path to device found.
if (someHidDevicesFound)
{
memberIndex = 0;
// Tracer.Trace(" total number of HID devices: " + devicePathName.Length); // will be something like 128, a lot of empty paths there.
do
{
// ***
// API function:
// CreateFile
// Purpose:
// Retrieves a handle to a device.
// Accepts:
// A device path name returned by SetupDiGetDeviceInterfaceDetail
// The type of access requested (read/write).
// FILE_SHARE attributes to allow other processes to access the device while this handle is open.
// A Security structure or IntPtr.Zero.
// A creation disposition value. Use OPEN_EXISTING for devices.
// Flags and attributes for files. Not used for devices.
// Handle to a template file. Not used.
// Returns: a handle without read or write access.
// This enables obtaining information about all HIDs, even system
// keyboards and mice.
// Separate handles are used for reading and writing.
// ***
if (!string.IsNullOrEmpty(devicePathName[memberIndex]))
{
Tracer.Trace(" trying HID device path '" + devicePathName[memberIndex] + "'");
hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);
functionName = "CreateFile";
Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
Tracer.Trace(" FindTheHid(): some HID device found, returned handle: " + hidHandle.ToString());
if (!hidHandle.IsInvalid)
{
// The returned handle is valid,
// so find out if this is the device we're looking for.
// Set the Size property of DeviceAttributes to the number of bytes in the structure.
MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes);
// ***
// API function:
// HidD_GetAttributes
// Purpose:
// Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID,
// Product ID, and Product Version Number for a device.
// Accepts:
// A handle returned by CreateFile.
// A pointer to receive a HIDD_ATTRIBUTES structure.
// Returns:
// True on success, False on failure.
// ***
success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes);
if (success)
{
Tracer.Trace(" HIDD_ATTRIBUTES structure filled without error.");
Tracer.Trace(" Structure size: " + MyHid.DeviceAttributes.Size);
Tracer.Trace(string.Format(" Vendor ID: 0x{0:X04}", MyHid.DeviceAttributes.VendorID));
Tracer.Trace(string.Format(" Product ID: 0x{0:X04}", MyHid.DeviceAttributes.ProductID));
Tracer.Trace(string.Format(" Version Number: 0x{0:X04}", MyHid.DeviceAttributes.VersionNumber));
// Find out if the device matches the one we're looking for.
if ((MyHid.DeviceAttributes.VendorID == myVendorID) && (MyHid.DeviceAttributes.ProductID == myProductID))
{
Tracer.Trace(" My device detected");
myDeviceDetected = true;
// Save the DevicePathName for OnDeviceChange().
myDevicePathName = devicePathName[memberIndex];
}
else
{
// It's not a match, so close the handle.
Tracer.Trace(" (This is not My Device)");
myDeviceDetected = false;
hidHandle.Close();
}
}
else
{
// There was a problem in retrieving the information.
Tracer.Trace(" Error in filling HIDD_ATTRIBUTES structure.");
myDeviceDetected = false;
hidHandle.Close();
}
}
}
// Keep looking until we find the device or there are no devices left to examine.
memberIndex = memberIndex + 1;
}
while (!((myDeviceDetected || (memberIndex == devicePathName.Length))));
}
if (myDeviceDetected)
{
// The device was detected.
// Register to receive notifications if the device is removed or attached.
success = MyDeviceManagement.RegisterForDeviceNotifications(myDevicePathName, WindowHandle, hidGuid, ref deviceNotificationHandle);
Tracer.Trace("RegisterForDeviceNotifications = " + success);
// Learn the capabilities of the device.
MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle);
if (success)
{
// Find out if the device is a system mouse or keyboard.
hidUsage = MyHid.GetHidUsage(MyHid.Capabilities);
// Get the Input report buffer size.
GetInputReportBufferSize();
// Get handles to use in requesting Input and Output reports.
readHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, FileIO.FILE_FLAG_OVERLAPPED, 0);
functionName = "CreateFile, ReadHandle";
Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
Tracer.Trace(" FindTheHid(): success, returned handle: " + readHandle.ToString());
if (readHandle.IsInvalid)
{
exclusiveAccess = true;
Tracer.Error("The device is a system " + hidUsage + ". Applications can access Feature reports only.");
}
else
{
writeHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);
functionName = "CreateFile, WriteHandle";
Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
Tracer.Trace(" FindTheHid(): handle valid, returned handle: " + writeHandle.ToString());
// Flush any waiting reports in the input buffer. (optional)
MyHid.FlushQueue(readHandle);
}
}
}
else
{
// The device wasn't detected.
Tracer.Error(string.Format("My Device not found - need a HID with vendorId={0}, productId={1}.", vendorId, productId));
}
return myDeviceDetected;
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
/// <summary>
/// Sends an Output report, then may retrieve an Input report.
/// </summary>
private byte[] ExchangeInputAndOutputReports(byte[] outputReportBuffer, bool doOutputReport, bool doInputReport, int expectedInputReportID, EventHandler<AsyncInputReportArgs> readCompleteHandler)
{
StringBuilder byteValue = null;
int count = 0;
byte[] inputReportBuffer = null;
bool success = false;
try
{
success = false;
// Don't attempt to exchange reports if valid handles aren't available
// (as for a mouse or keyboard under Windows 2000/XP.)
if (!readHandle.IsInvalid && !writeHandle.IsInvalid)
{
// Don't attempt to send an Output report if the HID has no Output report.
if (doOutputReport && MyHid.Capabilities.OutputReportByteLength > 0)
{
// Write a report.
if ((UseControlTransfersOnly) == true)
{
// Use a control transfer to send the report,
// even if the HID has an interrupt OUT endpoint.
Hid.OutputReportViaControlTransfer myOutputReport = new Hid.OutputReportViaControlTransfer();
success = myOutputReport.Write(outputReportBuffer, writeHandle);
}
else
{
// Use WriteFile to send the report.
// If the HID has an interrupt OUT endpoint, WriteFile uses an
// interrupt transfer to send the report.
// If not, WriteFile uses a control transfer.
Hid.OutputReportViaInterruptTransfer myOutputReport = new Hid.OutputReportViaInterruptTransfer();
success = myOutputReport.Write(outputReportBuffer, writeHandle);
}
if (success)
{
;
/*
byteValue = new StringBuilder();
byteValue.AppendFormat("An Output report has been written. Output Report ID: {0:X02}\r\n Output Report Data: ", outputReportBuffer[0]);
for (count = 0; count <= outputReportBuffer.Length - 1; count++)
{
// Display bytes as 2-character hex strings.
byteValue.AppendFormat("{0:X02} ", outputReportBuffer[count]);
}
Tracer.Trace(byteValue.ToString());
*/
}
else
{
Tracer.Error("The attempt to write an Output report has failed.");
}
}
else
{
//Tracer.Trace("No attempt to send an Output report was made.");
if (doOutputReport)
{
Tracer.Error("The HID doesn't have an Output report, but it was requested.");
}
}
// Read an Input report.
// Don't attempt to send an Input report if the HID has no Input report.
// (The HID spec requires all HIDs to have an interrupt IN endpoint,
// which suggests that all HIDs must support Input reports.)
if (doInputReport && MyHid.Capabilities.InputReportByteLength > 0)
{
success = false;
// Set the size of the Input report buffer.
inputReportBuffer = new byte[MyHid.Capabilities.InputReportByteLength];
if (UseControlTransfersOnly || readCompleteHandler == null)
{
// Read a report using a control transfer.
Hid.InputReportViaControlTransfer myInputReport = new Hid.InputReportViaControlTransfer();
// Read the report via HidD_GetInputReport http://www.osronline.com/DDKx/intinput/hidfunc_3hgy.htm
// - "If the top-level collection includes report IDs, the caller must set the first byte of the buffer to a nonzero report ID; otherwise the caller must set the first byte to zero."
inputReportBuffer[0] = (byte)expectedInputReportID;
myInputReport.Read(hidHandle, readHandle, writeHandle, ref myDeviceDetected, ref inputReportBuffer, ref success);
if (success)
{
;
/*
byteValue = new StringBuilder();
byteValue.AppendFormat("ExchangeInputAndOutputReports(): An Input report has been read via ControlTransfer. Input Report ID: {0:X02}\r\n Input Report Data: ", inputReportBuffer[0]);
for (count = 0; count <= inputReportBuffer.Length - 1; count++)
{
// Display bytes as 2-character Hex strings.
byteValue.AppendFormat("{0:X02} ", inputReportBuffer[count]);
}
Tracer.Trace(byteValue.ToString());
*/
}
else
{
Tracer.Error("ExchangeInputAndOutputReports(): The attempt to read an Input report has failed.");
}
}
else
{
// Read a report using interrupt transfers.
// To enable reading a report without blocking the main thread, this
// application uses an asynchronous delegate.
//Tracer.Trace("IP: Arranging asyncronous read via Interrupt Transfer");
IAsyncResult ar = null;
Hid.InputReportViaInterruptTransfer myInputReport = new Hid.InputReportViaInterruptTransfer();
if (readCompleteHandler != null)
{
myInputReport.HasReadData += readCompleteHandler;
}
// Define a delegate for the Read method of myInputReport.
ReadInputReportDelegate MyReadInputReportDelegate = new ReadInputReportDelegate(myInputReport.Read);
// The BeginInvoke method calls myInputReport.Read to attempt to read a report.
// The method has the same parameters as the Read function,
// plus two additional parameters:
// GetInputReportData is the callback procedure that executes when the Read function returns.
// MyReadInputReportDelegate is the asynchronous delegate object.
// The last parameter can optionally be an object passed to the callback.
ar = MyReadInputReportDelegate.BeginInvoke(hidHandle, readHandle, writeHandle, ref myDeviceDetected, ref inputReportBuffer, ref success, new AsyncCallback(GetInputReportData), MyReadInputReportDelegate);
}
}
else
{
//Tracer.Trace("No attempt to read an Input report was made.");
if (doInputReport)
{
Tracer.Error("The HID doesn't have an Input report, but it was requested.");
}
}
}
else
{
Tracer.Error("Invalid handle. The device is probably a system mouse or keyboard.");
Tracer.Error("No attempt to write an Output report or read an Input report was made.");
}
return inputReportBuffer; // may still be null
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
/// <summary>
/// Retrieves Input report data and status information.
/// This routine is called automatically when myInputReport.Read
/// returns. Calls several marshaling routines to access the main form.
/// </summary>
///
/// <param name="ar"> an object containing status information about the asynchronous operation. </param>
private void GetInputReportData(IAsyncResult ar)
{
StringBuilder byteValue = null;
int count = 0;
byte[] inputReportBuffer = null;
bool success = false;
try
{
// Define a delegate using the IAsyncResult object.
ReadInputReportDelegate deleg = ((ReadInputReportDelegate)(ar.AsyncState));
// Get the IAsyncResult object and the values of other paramaters that the
// BeginInvoke method passed ByRef.
deleg.EndInvoke(ref myDeviceDetected, ref inputReportBuffer, ref success, ar);
// Display the received report data in the form's list box.
if ((ar.IsCompleted && success))
{
;
/*
byteValue = new StringBuilder();
byteValue.AppendFormat("GetInputReportData(): An Input report has been read asyncronously via Interrupt Transfer. Input Report ID: {0:X02}\r\n Input Report Data: ", inputReportBuffer[0]);
for (count = 0; count <= inputReportBuffer.Length - 1; count++)
{
// Display bytes as 2-character Hex strings.
byteValue.AppendFormat("{0:X02} ", inputReportBuffer[count]);
}
Tracer.Trace(byteValue.ToString());
*/
}
else
{
Tracer.Error("GetInputReportData(): The attempt to read an Input report has failed.");
}
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
/// <summary>
/// Initiates exchanging reports.
/// The application sends a report and requests to read a report.
/// </summary>
private void WriteToDevice(byte[] outputReportBuffer)
{
//Tracer.Trace("WriteToDevice() " + DateTime.Now);
try
{
// If the device hasn't been detected, was removed, or timed out on a previous attempt
// to access it, look for the device.
if ((myDeviceDetected == false))
{
myDeviceDetected = FindTheHid(vendorId, productId);
}
if ((myDeviceDetected == true))
{
// Get the bytes to send in a report from the combo boxes.
// An option button selects whether to exchange Input and Output reports
// or Feature reports.
//if ((optInputOutput.Checked == true))
{
ExchangeInputAndOutputReports(outputReportBuffer, true, false, 0, null); // do not expect any response.
}
//else
//{
// ExchangeFeatureReports();
//}
}
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
private byte[] ReadAndWriteToDevice(byte[] outputReportBuffer, int expectedInputReportID)
{
byte[] inputReportBuffer = null;
//Tracer.Trace("ReadAndWriteToDevice() " + DateTime.Now);
try
{
// If the device hasn't been detected, was removed, or timed out on a previous attempt
// to access it, look for the device.
if ((myDeviceDetected == false))
{
myDeviceDetected = FindTheHid(vendorId, productId);
}
if ((myDeviceDetected == true))
{
// An option button selects whether to exchange Input and Output reports
// or Feature reports.
//if ((optInputOutput.Checked == true))
{
inputReportBuffer = ExchangeInputAndOutputReports(outputReportBuffer, true, true, expectedInputReportID, null); // expect, wait for and read a response.
}
//else
//{
// ExchangeFeatureReports();
//}
}
return inputReportBuffer;
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
private byte[] ReadFromDevice(EventHandler<AsyncInputReportArgs> readCompleteHandler, int expectedInputReportID)
{
byte[] inputReportBuffer = null;
//Tracer.Trace("ReadFromDevice() " + DateTime.Now);
try
{
// If the device hasn't been detected, was removed, or timed out on a previous attempt
// to access it, look for the device.
if ((myDeviceDetected == false))
{
myDeviceDetected = FindTheHid(vendorId, productId);
}
if ((myDeviceDetected == true))
{
// An option button selects whether to exchange Input and Output reports
// or Feature reports.
//if ((optInputOutput.Checked == true))
{
inputReportBuffer = ExchangeInputAndOutputReports(null, false, true, expectedInputReportID, readCompleteHandler); // wait for any input from the device, call readCompleteHandler when it comes.
}
//else
//{
// ExchangeFeatureReports();
//}
}
return inputReportBuffer;
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
/// <summary>
/// Perform actions that must execute when the program ends.
/// </summary>
private void ShutdownHid()
{
try
{
// Close open handles to the device.
if (!(hidHandle == null))
{
if (!(hidHandle.IsInvalid))
{
hidHandle.Close();
}
}
if (!(readHandle == null))
{
if (!(readHandle.IsInvalid))
{
readHandle.Close();
}
}
if (!(writeHandle == null))
{
if (!(writeHandle.IsInvalid))
{
writeHandle.Close();
}
}
// Stop receiving notifications.
MyDeviceManagement.StopReceivingDeviceNotifications(deviceNotificationHandle);
myDeviceDetected = false;
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
/// <summary>
/// Perform actions that must execute when the program starts.
/// </summary>
private void Startup()
{
try
{
MyHid = new Hid();
// Default USB Vendor ID and Product ID:
//txtVendorID.Text = "0925";
//txtProductID.Text = "7001";
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
}
}
| |
/* ====================================================================
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 NPOI.XSSF.UserModel;
using System;
using NPOI.OpenXml4Net.OPC;
using System.Text;
using NPOI.SS.UserModel;
using System.Collections;
using System.Globalization;
using System.Collections.Generic;
namespace NPOI.XSSF.Extractor
{
/**
* Helper class to extract text from an OOXML Excel file
*/
public class XSSFExcelExtractor : POIXMLTextExtractor, NPOI.SS.Extractor.IExcelExtractor
{
public static XSSFRelation[] SUPPORTED_TYPES = new XSSFRelation[] {
XSSFRelation.WORKBOOK, XSSFRelation.MACRO_TEMPLATE_WORKBOOK,
XSSFRelation.MACRO_ADDIN_WORKBOOK, XSSFRelation.TEMPLATE_WORKBOOK,
XSSFRelation.MACROS_WORKBOOK
};
private XSSFWorkbook workbook;
private bool includeSheetNames = true;
private bool formulasNotResults = false;
private bool includeCellComments = false;
private bool includeHeadersFooters = true;
private bool includeTextBoxes = true;
public XSSFExcelExtractor(OPCPackage Container)
: this(new XSSFWorkbook(Container))
{
}
public XSSFExcelExtractor(XSSFWorkbook workbook)
: base(workbook)
{
this.workbook = workbook;
}
/// <summary>
/// Should header and footer be included? Default is true
/// </summary>
public bool IncludeHeaderFooter
{
get
{
return this.includeHeadersFooters;
}
set
{
this.includeHeadersFooters = value;
}
}
/// <summary>
/// Should sheet names be included? Default is true
/// </summary>
/// <value>if set to <c>true</c> [include sheet names].</value>
public bool IncludeSheetNames
{
get
{
return this.includeSheetNames;
}
set
{
this.includeSheetNames = value;
}
}
/// <summary>
/// Should we return the formula itself, and not
/// the result it produces? Default is false
/// </summary>
/// <value>if set to <c>true</c> [formulas not results].</value>
public bool FormulasNotResults
{
get
{
return this.formulasNotResults;
}
set
{
this.formulasNotResults = value;
}
}
/// <summary>
/// Should cell comments be included? Default is false
/// </summary>
/// <value>if set to <c>true</c> [include cell comments].</value>
public bool IncludeCellComments
{
get
{
return this.includeCellComments;
}
set
{
this.includeCellComments = value;
}
}
public bool IncludeTextBoxes
{
get
{
return includeTextBoxes;
}
set
{
includeTextBoxes = value;
}
}
/**
* Should sheet names be included? Default is true
*/
public void SetIncludeSheetNames(bool includeSheetNames)
{
this.includeSheetNames = includeSheetNames;
}
/**
* Should we return the formula itself, and not
* the result it produces? Default is false
*/
public void SetFormulasNotResults(bool formulasNotResults)
{
this.formulasNotResults = formulasNotResults;
}
/**
* Should cell comments be included? Default is false
*/
public void SetIncludeCellComments(bool includeCellComments)
{
this.includeCellComments = includeCellComments;
}
/**
* Should headers and footers be included? Default is true
*/
public void SetIncludeHeadersFooters(bool includeHeadersFooters)
{
this.includeHeadersFooters = includeHeadersFooters;
}
/**
* Should text within textboxes be included? Default is true
* @param includeTextBoxes
*/
public void SetIncludeTextBoxes(bool includeTextBoxes)
{
this.includeTextBoxes = includeTextBoxes;
}
public void SetLocale(CultureInfo locale)
{
this.locale = locale;
}
private CultureInfo locale = null;
/**
* Retreives the text contents of the file
*/
public override String Text
{
get
{
DataFormatter formatter;
if (locale == null)
{
formatter = new DataFormatter();
}
else
{
formatter = new DataFormatter(locale);
}
StringBuilder text = new StringBuilder();
foreach (ISheet sh in workbook)
{
XSSFSheet sheet = (XSSFSheet)sh;
if (includeSheetNames)
{
text.Append(sheet.SheetName + "\n");
}
// Header(s), if present
if (includeHeadersFooters)
{
text.Append(
ExtractHeaderFooter(sheet.FirstHeader)
);
text.Append(
ExtractHeaderFooter(sheet.OddHeader)
);
text.Append(
ExtractHeaderFooter(sheet.EvenHeader)
);
}
// Rows and cells
foreach (Object rawR in sheet)
{
IRow row = (IRow)rawR;
IEnumerator<ICell> ri = row.GetEnumerator();
bool firsttime = true;
for (int j = 0; j < row.LastCellNum; j++)
{
// Add a tab delimiter for each empty cell.
if (!firsttime)
{
text.Append("\t");
}
else
{
firsttime = false;
}
ICell cell = row.GetCell(j);
if (cell == null)
continue;
// Is it a formula one?
if (cell.CellType == CellType.Formula)
{
if (formulasNotResults)
{
text.Append(cell.CellFormula);
}
else
{
if (cell.CachedFormulaResultType == CellType.String)
{
HandleStringCell(text, cell);
}
else
{
HandleNonStringCell(text, cell, formatter);
}
}
}
else if (cell.CellType == CellType.String)
{
HandleStringCell(text, cell);
}
else
{
HandleNonStringCell(text, cell, formatter);
}
// Output the comment, if requested and exists
IComment comment = cell.CellComment;
if (includeCellComments && comment != null)
{
// Replace any newlines with spaces, otherwise it
// breaks the output
String commentText = comment.String.String.Replace('\n', ' ');
text.Append(" Comment by ").Append(comment.Author).Append(": ").Append(commentText);
}
}
text.Append("\n");
}
// add textboxes
if (includeTextBoxes)
{
XSSFDrawing drawing = sheet.GetDrawingPatriarch();
if (drawing != null)
{
foreach (XSSFShape shape in drawing.GetShapes())
{
if (shape is XSSFSimpleShape)
{
String boxText = ((XSSFSimpleShape)shape).Text;
if (boxText.Length > 0)
{
text.Append(boxText);
text.Append('\n');
}
}
}
}
}
// Finally footer(s), if present
if (includeHeadersFooters)
{
text.Append(
ExtractHeaderFooter(sheet.FirstFooter)
);
text.Append(
ExtractHeaderFooter(sheet.OddFooter)
);
text.Append(
ExtractHeaderFooter(sheet.EvenFooter)
);
}
}
return text.ToString();
}
}
private void HandleStringCell(StringBuilder text, ICell cell)
{
text.Append(cell.RichStringCellValue.String);
}
private void HandleNonStringCell(StringBuilder text, ICell cell, DataFormatter formatter)
{
CellType type = cell.CellType;
if (type == CellType.Formula)
{
type = cell.CachedFormulaResultType;
}
if (type == CellType.Numeric)
{
ICellStyle cs = cell.CellStyle;
if (cs.GetDataFormatString() != null)
{
text.Append(formatter.FormatRawCellContents(
cell.NumericCellValue, cs.DataFormat, cs.GetDataFormatString()
));
return;
}
}
// No supported styling applies to this cell
XSSFCell xcell = (XSSFCell)cell;
text.Append(xcell.GetRawValue());
}
private String ExtractHeaderFooter(IHeaderFooter hf)
{
return NPOI.HSSF.Extractor.ExcelExtractor.ExtractHeaderFooter(hf);
}
}
}
| |
/*
Copyright (c) 2008, Rune Skovbo Johansen & Unity Technologies ApS
See the document "TERMS OF USE" included in the project folder for licencing details.
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class LegInfo {
public Transform hip;
public Transform ankle;
public Transform toe;
public float footWidth;
public float footLength;
public Vector2 footOffset;
[HideInInspector] public Transform[] legChain;
[HideInInspector] public Transform[] footChain;
[HideInInspector] public float legLength;
[HideInInspector] public Vector3 ankleHeelVector;
[HideInInspector] public Vector3 toeToetipVector;
[HideInInspector] public Color debugColor;
}
[System.Serializable]
public class MotionGroupInfo {
public string name;
public IMotionAnalyzer[] motions;
public Interpolator interpolator;
public float[] GetMotionWeights(Vector3 velocity) {
return interpolator.Interpolate(new float[] {velocity.x, velocity.y, velocity.z});
}
}
[System.Serializable]
public class LegController : MonoBehaviour {
public float groundPlaneHeight;
public AnimationClip groundedPose;
/*[HideInInspector]*/ public Transform rootBone;
public Transform root { get { return rootBone; } }
public LegInfo[] legs;
public MotionAnalyzer[] sourceAnimations;
[HideInInspector] public bool initialized = false;
[HideInInspector] public MotionAnalyzerBackwards[] sourceAnimationsBackwards;
[HideInInspector] public Vector3 m_HipAverage;
public Vector3 hipAverage { get { return m_HipAverage; } }
[HideInInspector] public Vector3 m_HipAverageGround;
public Vector3 hipAverageGround { get { return m_HipAverageGround; } }
[HideInInspector] public IMotionAnalyzer[] m_Motions;
public IMotionAnalyzer[] motions { get { return m_Motions; } }
[HideInInspector] public IMotionAnalyzer[] m_CycleMotions;
public IMotionAnalyzer[] cycleMotions { get { return m_CycleMotions; } }
[HideInInspector] public MotionGroupInfo[] m_MotionGroups;
public MotionGroupInfo[] motionGroups { get { return m_MotionGroups; } }
[HideInInspector] public IMotionAnalyzer[] m_NonGroupMotions;
public IMotionAnalyzer[] nonGroupMotions { get { return m_NonGroupMotions; }}
public void InitFootData(int leg) {
// Make sure character is in grounded pose before analyzing
gameObject.SampleAnimation(groundedPose,0);
// Give each leg a color
Vector3 colorVect = Quaternion.AngleAxis(leg*360.0f/legs.Length, Vector3.one) * Vector3.right;
legs[leg].debugColor = new Color(colorVect.x, colorVect.y, colorVect.z);
// Calculate heel and toetip positions and alignments
// (The vector from the ankle to the ankle projected onto the ground at the stance pose
// in local coordinates relative to the ankle transform.
// This essentially is the ankle moved to the bottom of the foot, approximating the heel.)
// Get ankle position projected down onto the ground
Matrix4x4 ankleMatrix = Util.RelativeMatrix(legs[leg].ankle,gameObject.transform);
Vector3 anklePosition = ankleMatrix.MultiplyPoint(Vector3.zero);
Vector3 heelPosition = anklePosition;
heelPosition.y = groundPlaneHeight;
// Get toe position projected down onto the ground
Matrix4x4 toeMatrix = Util.RelativeMatrix(legs[leg].toe,gameObject.transform);
Vector3 toePosition = toeMatrix.MultiplyPoint(Vector3.zero);
Vector3 toetipPosition = toePosition;
toetipPosition.y = groundPlaneHeight;
// Calculate foot middle and vector
Vector3 footMiddle = (heelPosition + toetipPosition)/2;
Vector3 footVector;
if (toePosition==anklePosition) {
footVector = ankleMatrix.MultiplyVector(legs[leg].ankle.localPosition);
footVector.y = 0;
footVector = footVector.normalized;
}
else {
footVector = (toetipPosition - heelPosition).normalized;
}
Vector3 footSideVector = Vector3.Cross(Vector3.up, footVector);
legs[leg].ankleHeelVector = (
footMiddle
+ (-legs[leg].footLength/2 + legs[leg].footOffset.y) * footVector
+ legs[leg].footOffset.x * footSideVector
);
legs[leg].ankleHeelVector = ankleMatrix.inverse.MultiplyVector(legs[leg].ankleHeelVector - anklePosition);
legs[leg].toeToetipVector = (
footMiddle
+ (legs[leg].footLength/2 + legs[leg].footOffset.y) * footVector
+ legs[leg].footOffset.x * footSideVector
);
legs[leg].toeToetipVector = toeMatrix.inverse.MultiplyVector(legs[leg].toeToetipVector - toePosition);
}
public void Init() {
// Only set initialized to true in the end, when we know that no errors have occurred.
initialized = false;
Debug.Log("Initializing "+name+" Locomotion System...");
// Find the skeleton root (child of the GameObject) if none has been set already
if (rootBone==null) {
if (legs[0].hip==null) { Debug.LogError(name+": Leg Transforms are null.",this); return; }
rootBone = legs[0].hip;
while (root.parent != transform) rootBone = root.parent;
}
// Calculate data for LegInfo objects
m_HipAverage = Vector3.zero;
for (int leg=0; leg<legs.Length; leg++) {
// Calculate leg bone chains
if (legs[leg].toe==null) legs[leg].toe = legs[leg].ankle;
legs[leg].legChain = GetTransformChain(legs[leg].hip, legs[leg].ankle);
legs[leg].footChain = GetTransformChain(legs[leg].ankle, legs[leg].toe);
// Calculate length of leg
legs[leg].legLength = 0;
for (int i=0; i<legs[leg].legChain.Length-1; i++) {
legs[leg].legLength += (
transform.InverseTransformPoint(legs[leg].legChain[i+1].position)
-transform.InverseTransformPoint(legs[leg].legChain[i].position)
).magnitude;
}
m_HipAverage += transform.InverseTransformPoint(legs[leg].legChain[0].position);
InitFootData(leg);
}
m_HipAverage /= legs.Length;
m_HipAverageGround = m_HipAverage;
m_HipAverageGround.y = groundPlaneHeight;
}
public void Init2() {
// Analyze motions
List<MotionAnalyzerBackwards> sourceAnimationBackwardsList = new List<MotionAnalyzerBackwards>();
for (int i=0; i<sourceAnimations.Length; i++) {
// Initialize motion objects
Debug.Log("Analysing sourceAnimations["+i+"]: "+sourceAnimations[i].name);
sourceAnimations[i].Analyze(gameObject);
// Also initialize backwards motion, if specified
if (sourceAnimations[i].alsoUseBackwards) {
MotionAnalyzerBackwards backwards = new MotionAnalyzerBackwards();
backwards.orig = sourceAnimations[i];
backwards.Analyze(gameObject);
sourceAnimationBackwardsList.Add(backwards);
}
}
sourceAnimationsBackwards = sourceAnimationBackwardsList.ToArray();
// Motion sampling have put bones in random pose...
// Reset to grounded pose, time 0
gameObject.SampleAnimation(groundedPose,0);
initialized = true;
Debug.Log("Initializing "+name+" Locomotion System... Done!");
}
void Awake() {
if (!initialized) { Debug.LogError(name+": Locomotion System has not been initialized.",this); return; }
// Put regular and backwards motions into one array
m_Motions = new IMotionAnalyzer[sourceAnimations.Length + sourceAnimationsBackwards.Length];
for (int i=0; i<sourceAnimations.Length; i++) {
motions[i] = sourceAnimations[i];
}
for (int i=0; i<sourceAnimationsBackwards.Length; i++) {
motions[sourceAnimations.Length+i] = sourceAnimationsBackwards[i];
}
// Get number of walk cycle motions and put them in an array
int cycleMotionAmount = 0;
for (int i=0; i<motions.Length; i++) {
if (motions[i].motionType == MotionType.WalkCycle) cycleMotionAmount++;
}
m_CycleMotions = new IMotionAnalyzer[cycleMotionAmount];
int index = 0;
for (int i=0; i<motions.Length; i++) {
if (motions[i].motionType == MotionType.WalkCycle) {
cycleMotions[index] = motions[i];
index++;
}
}
// Setup motion groups
List<string> motionGroupNameList = new List<string>();
List<MotionGroupInfo> motionGroupList = new List<MotionGroupInfo>();
List<List<IMotionAnalyzer>> motionGroupMotionLists = new List<List<IMotionAnalyzer>>();
List<IMotionAnalyzer> nonGroupMotionList = new List<IMotionAnalyzer>();
for (int i=0; i<motions.Length; i++) {
if (motions[i].motionGroup == "") {
nonGroupMotionList.Add(motions[i]);
}
else {
string groupName = motions[i].motionGroup;
if ( !motionGroupNameList.Contains(groupName) ) {
// Name is new so create a new motion group
MotionGroupInfo m = new MotionGroupInfo();
// Use it as controller for our new motion group
m.name = groupName;
motionGroupList.Add(m);
motionGroupNameList.Add(groupName);
motionGroupMotionLists.Add(new List<IMotionAnalyzer>());
}
motionGroupMotionLists[motionGroupNameList.IndexOf(groupName)].Add(motions[i]);
}
}
m_NonGroupMotions = nonGroupMotionList.ToArray();
m_MotionGroups = motionGroupList.ToArray();
for (int g=0; g<motionGroups.Length; g++) {
motionGroups[g].motions = motionGroupMotionLists[g].ToArray();
}
// Set up parameter space (for each motion group) used for automatic blending
for (int g=0; g<motionGroups.Length; g++) {
MotionGroupInfo group = motionGroups[g];
Vector3[] motionVelocities = new Vector3[group.motions.Length];
float[][] motionParameters = new float[group.motions.Length][];
for (int i=0; i<group.motions.Length; i++) {
motionVelocities[i] = group.motions[i].cycleVelocity;
motionParameters[i] = new float[] {motionVelocities[i].x, motionVelocities[i].y, motionVelocities[i].z};
}
group.interpolator = new PolarGradientBandInterpolator(motionParameters);
}
// Calculate offset time values for each walk cycle motion
CalculateTimeOffsets();
}
// Get the chain of transforms from one transform to a descendent one
public Transform[] GetTransformChain(Transform upper, Transform lower) {
Transform t = lower;
int chainLength = 1;
while (t != upper) {
t = t.parent;
chainLength++;
}
Transform[] chain = new Transform[chainLength];
t = lower;
for (int j=0; j<chainLength; j++) {
chain[chainLength-1-j] = t;
t = t.parent;
}
return chain;
}
public void CalculateTimeOffsets() {
float[] offsets = new float[cycleMotions.Length];
float[] offsetChanges = new float[cycleMotions.Length];
for (int i=0; i<cycleMotions.Length; i++) offsets[i] = 0;
int springs = (cycleMotions.Length*cycleMotions.Length-cycleMotions.Length)/2;
int iteration = 0;
bool finished = false;
while (iteration<100 && finished==false) {
for (int i=0; i<cycleMotions.Length; i++) offsetChanges[i] = 0;
// Calculate offset changes
for (int i=1; i<cycleMotions.Length; i++) {
for (int j=0; j<i; j++) {
for (int leg=0; leg<legs.Length; leg++) {
float ta = cycleMotions[i].cycles[leg].stanceTime + offsets[i];
float tb = cycleMotions[j].cycles[leg].stanceTime + offsets[j];
Vector2 va = new Vector2( Mathf.Cos(ta*2*Mathf.PI), Mathf.Sin(ta*2*Mathf.PI) );
Vector2 vb = new Vector2( Mathf.Cos(tb*2*Mathf.PI), Mathf.Sin(tb*2*Mathf.PI) );
Vector2 abVector = vb-va;
Vector2 va2 = va + abVector*0.1f;
Vector2 vb2 = vb - abVector*0.1f;
float ta2 = Util.Mod(Mathf.Atan2(va2.y,va2.x)/2/Mathf.PI);
float tb2 = Util.Mod(Mathf.Atan2(vb2.y,vb2.x)/2/Mathf.PI);
float aChange = Util.Mod(ta2-ta);
float bChange = Util.Mod(tb2-tb);
if (aChange>0.5f) aChange = aChange-1;
if (bChange>0.5f) bChange = bChange-1;
offsetChanges[i] += aChange * 5.0f / springs;
offsetChanges[j] += bChange * 5.0f / springs;
}
}
}
// Apply new offset changes
float maxChange = 0;
for (int i=0; i<cycleMotions.Length; i++) {
offsets[i] += offsetChanges[i];
maxChange = Mathf.Max(maxChange,Mathf.Abs(offsetChanges[i]));
}
iteration++;
if (maxChange<0.0001) finished = true;
}
// Apply the offsets to the motions
for (int m=0; m<cycleMotions.Length; m++) {
cycleMotions[m].cycleOffset = offsets[m];
for (int leg=0; leg<legs.Length; leg++) {
cycleMotions[m].cycles[leg].stanceTime =
Util.Mod(cycleMotions[m].cycles[leg].stanceTime + offsets[m]);
}
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections;
using System.Diagnostics;
using Axiom.Core;
using Axiom.MathLib;
namespace Axiom.Graphics {
/// <summary>
/// This class defines the interface that must be implemented by shadow casters.
/// </summary>
public abstract class ShadowCaster {
#region Properties
/// <summary>
/// Gets/Sets whether or not this object currently casts a shadow.
/// </summary>
public abstract bool CastShadows { get; set; }
#endregion Properties
#region Methods
/// <summary>
/// Gets the world space bounding box of the dark cap, as extruded using the light provided.
/// </summary>
/// <param name="light"></param>
/// <param name="dirLightExtrusionDist"></param>
/// <returns></returns>
public abstract AxisAlignedBox GetDarkCapBounds(Light light, float dirLightExtrusionDist);
/// <summary>
/// Gets details of the edges which might be used to determine a silhouette.
/// </summary>
/// <remarks>Defaults to LOD index 0.</remarks>
public EdgeData GetEdgeList() {
return GetEdgeList(0);
}
/// <summary>
/// Gets details of the edges which might be used to determine a silhouette.
/// </summary>
public abstract EdgeData GetEdgeList(int lodIndex);
/// <summary>
/// Gets the world space bounding box of the light cap.
/// </summary>
/// <returns></returns>
public abstract AxisAlignedBox GetLightCapBounds();
/// <summary>
/// Get the world bounding box of the caster.
/// </summary>
/// <param name="derive"></param>
/// <returns></returns>
public abstract AxisAlignedBox GetWorldBoundingBox(bool derive);
public AxisAlignedBox GetWorldBoundingBox() {
return GetWorldBoundingBox(false);
}
/// <summary>
/// Gets an iterator over the renderables required to render the shadow volume.
/// </summary>
/// <remarks>
/// Shadowable geometry should ideally be designed such that there is only one
/// ShadowRenderable required to render the the shadow; however this is not a necessary
/// limitation and it can be exceeded if required.
/// </remarks>
/// <param name="technique">The technique being used to generate the shadow.</param>
/// <param name="light">The light to generate the shadow from.</param>
/// <param name="indexBuffer">The index buffer to build the renderables into,
/// the current contents are assumed to be disposable.</param>
/// <param name="extrudeVertices">If true, this means this class should extrude
/// the vertices of the back of the volume in software. If false, it
/// will not be done (a vertex program is assumed).</param>
/// <param name="flags">Technique-specific flags, see <see cref="ShadowRenderableFlags"/></param>
/// <returns>An iterator that will allow iteration over all renderables for the full shadow volume.</returns>
public abstract IEnumerator GetShadowVolumeRenderableEnumerator(ShadowTechnique technique, Light light,
HardwareIndexBuffer indexBuffer, bool extrudeVertices, float extrusionDistance, int flags);
public IEnumerator GetShadowVolumeRenderableEnumerator(ShadowTechnique technique, Light light,
HardwareIndexBuffer indexBuffer, float extrusionDistance, bool extrudeVertices) {
return GetShadowVolumeRenderableEnumerator(technique, light, indexBuffer, extrudeVertices, extrusionDistance, 0);
}
/// <summary>
/// Return the last calculated shadow renderables.
/// </summary>
/// <returns></returns>
public abstract IEnumerator GetLastShadowVolumeRenderableEnumerator();
/// <summary>
/// Utility method for extruding vertices based on a light.
/// </summary>
/// <remarks>
/// Unfortunately, because D3D cannot handle homogenous (4D) position
/// coordinates in the fixed-function pipeline (GL can, but we have to
/// be cross-API), when we extrude in software we cannot extrude to
/// infinity the way we do in the vertex program (by setting w to
/// 0.0f). Therefore we extrude by a fixed distance, which may cause
/// some problems with larger scenes. Luckily better hardware (ie
/// vertex programs) can fix this.
/// </remarks>
/// <param name="vertexBuffer">The vertex buffer containing ONLY xyz position
/// values, which must be originalVertexCount * 2 * 3 floats long.</param>
/// <param name="originalVertexCount">The count of the original number of
/// vertices, ie the number in the mesh, not counting the doubling
/// which has already been done (by <see cref="VertexData.PrepareForShadowVolume"/>)
/// to provide the extruded area of the buffer.</param>
/// <param name="lightPosition"> 4D light position in object space, when w=0.0f this
/// represents a directional light</param>
/// <param name="extrudeDistance">The distance to extrude.</param>
public static void ExtrudeVertices(HardwareVertexBuffer vertexBuffer, int originalVertexCount, Vector4 lightPosition, float extrudeDistance) {
unsafe {
Debug.Assert(vertexBuffer.VertexSize == sizeof(float) * 3, "Position buffer should contain only positions!");
// Extrude the first area of the buffer into the second area
// Lock the entire buffer for writing, even though we'll only be
// updating the latter because you can't have 2 locks on the same
// buffer
IntPtr srcPtr = vertexBuffer.Lock(BufferLocking.Normal);
IntPtr destPtr = new IntPtr(srcPtr.ToInt32() + (originalVertexCount * 3 * 4));
float* pSrc = (float*)srcPtr.ToPointer();
float* pDest = (float*)destPtr.ToPointer();
int destCount = 0, srcCount = 0;
// Assume directional light, extrusion is along light direction
Vector3 extrusionDir = new Vector3(-lightPosition.x, -lightPosition.y, -lightPosition.z);
extrusionDir.Normalize();
extrusionDir *= extrudeDistance;
for (int vert = 0; vert < originalVertexCount; vert++) {
if (lightPosition.w != 0.0f) {
// Point light, adjust extrusionDir
extrusionDir.x = pSrc[srcCount + 0] - lightPosition.x;
extrusionDir.y = pSrc[srcCount + 1] - lightPosition.y;
extrusionDir.z = pSrc[srcCount + 2] - lightPosition.z;
extrusionDir.Normalize();
extrusionDir *= extrudeDistance;
}
pDest[destCount++] = pSrc[srcCount++] + extrusionDir.x;
pDest[destCount++] = pSrc[srcCount++] + extrusionDir.y;
pDest[destCount++] = pSrc[srcCount++] + extrusionDir.z;
}
}
vertexBuffer.Unlock();
}
/// <summary>
/// Tells the caster to perform the tasks necessary to update the
/// edge data's light listing. Can be overridden if the subclass needs
/// to do additional things.
/// </summary>
/// <param name="edgeData">The edge information to update.</param>
/// <param name="lightPosition">4D vector representing the light, a directional light has w=0.0.</param>
protected virtual void UpdateEdgeListLightFacing(EdgeData edgeData, Vector4 lightPosition) {
edgeData.UpdateTriangleLightFacing(lightPosition);
}
/// <summary>
/// Generates the indexes required to render a shadow volume into the
/// index buffer which is passed in, and updates shadow renderables to use it.
/// </summary>
/// <param name="edgeData">The edge information to use.</param>
/// <param name="indexBuffer">The buffer into which to write data into; current
/// contents are assumed to be discardable.</param>
/// <param name="light">The light, mainly for type info as silhouette calculations
/// should already have been done in <see cref="UpdateEdgeListLightFacing"/></param>
/// <param name="shadowRenderables">A list of shadow renderables which has
/// already been constructed but will need populating with details of
/// the index ranges to be used.</param>
/// <param name="flags">Additional controller flags, see <see cref="ShadowRenderableFlags"/>.</param>
protected virtual void GenerateShadowVolume(EdgeData edgeData, HardwareIndexBuffer indexBuffer, Light light,
ShadowRenderableList shadowRenderables, int flags) {
// Edge groups should be 1:1 with shadow renderables
Debug.Assert(edgeData.edgeGroups.Count == shadowRenderables.Count);
LightType lightType = light.Type;
bool extrudeToInfinity = (flags & (int)ShadowRenderableFlags.ExtrudeToInfinity) > 0;
// Lock index buffer for writing
IntPtr idxPtr = indexBuffer.Lock(BufferLocking.Discard);
int indexStart = 0;
unsafe {
// TODO: Will currently cause an overflow for 32 bit indices, revisit
short* pIdx = (short*)idxPtr.ToPointer();
int count = 0;
// Iterate over the groups and form renderables for each based on their
// lightFacing
for(int groupCount = 0; groupCount < edgeData.edgeGroups.Count; groupCount++) {
EdgeData.EdgeGroup eg = (EdgeData.EdgeGroup)edgeData.edgeGroups[groupCount];
ShadowRenderable si = (ShadowRenderable)shadowRenderables[groupCount];
RenderOperation lightShadOp = null;
// Initialise the index bounds for this shadow renderable
RenderOperation shadOp = si.GetRenderOperationForUpdate();
shadOp.indexData.indexCount = 0;
shadOp.indexData.indexStart = indexStart;
// original number of verts (without extruded copy)
int originalVertexCount = eg.vertexData.vertexCount;
bool firstDarkCapTri = true;
int darkCapStart = 0;
for (int edgeCount = 0; edgeCount < eg.edges.Count; edgeCount++) {
EdgeData.Edge edge = (EdgeData.Edge)eg.edges[edgeCount];
EdgeData.Triangle t1 = (EdgeData.Triangle)edgeData.triangles[edge.triIndex[0]];
EdgeData.Triangle t2 =
edge.isDegenerate ? (EdgeData.Triangle)edgeData.triangles[edge.triIndex[0]] : (EdgeData.Triangle)edgeData.triangles[edge.triIndex[1]];
if (t1.lightFacing && (edge.isDegenerate || !t2.lightFacing)) {
/* Silhouette edge, first tri facing the light
Also covers degenerate tris where only tri 1 is valid
Remember verts run anticlockwise along the edge from
tri 0 so to point shadow volume tris outward, light cap
indexes have to be backwards
We emit 2 tris if light is a point light, 1 if light
is directional, because directional lights cause all
points to converge to a single point at infinity.
First side tri = near1, near0, far0
Second tri = far0, far1, near1
'far' indexes are 'near' index + originalVertexCount
because 'far' verts are in the second half of the
buffer
*/
pIdx[count++] = (short)edge.vertIndex[1];
pIdx[count++] = (short)edge.vertIndex[0];
pIdx[count++] = (short)(edge.vertIndex[0] + originalVertexCount);
shadOp.indexData.indexCount += 3;
if (!(lightType == LightType.Directional && extrudeToInfinity)) {
// additional tri to make quad
pIdx[count++] = (short)(edge.vertIndex[0] + originalVertexCount);
pIdx[count++] = (short)(edge.vertIndex[1] + originalVertexCount);
pIdx[count++] = (short)edge.vertIndex[1];
shadOp.indexData.indexCount += 3;
}
// Do dark cap tri
// Use McGuire et al method, a triangle fan covering all silhouette
// edges and one point (taken from the initial tri)
if ((flags & (int)ShadowRenderableFlags.IncludeDarkCap) > 0) {
if (firstDarkCapTri) {
darkCapStart = edge.vertIndex[0] + originalVertexCount;
firstDarkCapTri = false;
}
else {
pIdx[count++] = (short)darkCapStart;
pIdx[count++] = (short)(edge.vertIndex[1] + originalVertexCount);
pIdx[count++] = (short)(edge.vertIndex[0] + originalVertexCount);
shadOp.indexData.indexCount += 3;
}
}
}
else if (!t1.lightFacing && (edge.isDegenerate || t2.lightFacing)) {
// Silhouette edge, second tri facing the light
// Note edge indexes inverse of when t1 is light facing
pIdx[count++] = (short)edge.vertIndex[0];
pIdx[count++] = (short)edge.vertIndex[1];
pIdx[count++] = (short)(edge.vertIndex[1] + originalVertexCount);
shadOp.indexData.indexCount += 3;
if (!(lightType == LightType.Directional && extrudeToInfinity)) {
// additional tri to make quad
pIdx[count++] = (short)(edge.vertIndex[1] + originalVertexCount);
pIdx[count++] = (short)(edge.vertIndex[0] + originalVertexCount);
pIdx[count++] = (short)edge.vertIndex[0];
shadOp.indexData.indexCount += 3;
}
// Do dark cap tri
// Use McGuire et al method, a triangle fan covering all silhouette
// edges and one point (taken from the initial tri)
if ((flags & (int)ShadowRenderableFlags.IncludeDarkCap) > 0) {
if (firstDarkCapTri) {
darkCapStart = edge.vertIndex[1] + originalVertexCount;
firstDarkCapTri = false;
}
else {
pIdx[count++] = (short)darkCapStart;
pIdx[count++] = (short)(edge.vertIndex[0] + originalVertexCount);
pIdx[count++] = (short)(edge.vertIndex[1] + originalVertexCount);
shadOp.indexData.indexCount += 3;
}
}
}
}
// Do light cap
if ((flags & (int)ShadowRenderableFlags.IncludeLightCap) > 0) {
ShadowRenderable lightCapRend = null;
if(si.IsLightCapSeperate) {
// separate light cap
lightCapRend = si.LightCapRenderable;
lightShadOp = lightCapRend.GetRenderOperationForUpdate();
lightShadOp.indexData.indexCount = 0;
// start indexes after the current total
// NB we don't update the total here since that's done below
lightShadOp.indexData.indexStart =
indexStart + shadOp.indexData.indexCount;
}
for(int triCount = 0; triCount < edgeData.triangles.Count; triCount++) {
EdgeData.Triangle t = (EdgeData.Triangle)edgeData.triangles[triCount];
// Light facing, and vertex set matches
if (t.lightFacing && t.vertexSet == eg.vertexSet) {
pIdx[count++] = (short)t.vertIndex[0];
pIdx[count++] = (short)t.vertIndex[1];
pIdx[count++] = (short)t.vertIndex[2];
if(lightShadOp != null) {
lightShadOp.indexData.indexCount += 3;
}
else {
shadOp.indexData.indexCount += 3;
}
}
}
}
// update next indexStart (all renderables sharing the buffer)
indexStart += shadOp.indexData.indexCount;
// add on the light cap too
if (lightShadOp != null) {
indexStart += lightShadOp.indexData.indexCount;
}
}
}
// Unlock index buffer
indexBuffer.Unlock();
Debug.Assert(indexStart <= indexBuffer.IndexCount, "Index buffer overrun while generating shadow volume!");
}
/// <summary>
/// Utility method for extruding a bounding box.
/// </summary>
/// <param name="box">Original bounding box, will be updated in-place.</param>
/// <param name="lightPosition">4D light position in object space, when w=0.0f this
/// represents a directional light</param>
/// <param name="extrudeDistance">The distance to extrude.</param>
protected virtual void ExtrudeBounds(AxisAlignedBox box, Vector4 lightPosition, float extrudeDistance) {
Vector3 extrusionDir = Vector3.Zero;
if (lightPosition.w == 0) {
extrusionDir.x = -lightPosition.x;
extrusionDir.y = -lightPosition.y;
extrusionDir.z = -lightPosition.z;
extrusionDir.Normalize();
extrusionDir *= extrudeDistance;
box.SetExtents(box.Minimum + extrusionDir, box.Maximum + extrusionDir);
}
else {
Vector3[] corners = box.Corners;
Vector3 vmin = new Vector3();
Vector3 vmax = new Vector3();
for(int i = 0; i < 8; i++) {
extrusionDir.x = corners[i].x - lightPosition.x;
extrusionDir.y = corners[i].y - lightPosition.y;
extrusionDir.z = corners[i].z - lightPosition.z;
extrusionDir.Normalize();
extrusionDir *= extrudeDistance;
Vector3 res = corners[i] + extrusionDir;
if(i == 0) {
vmin = res;
vmax = res;
}
else {
vmin.Floor(res);
vmax.Ceil(res);
}
}
box.SetExtents(vmin, vmax);
}
}
/// <summary>
/// Helper method for calculating extrusion distance.
/// </summary>
/// <param name="objectPos"></param>
/// <param name="light"></param>
/// <returns></returns>
protected float GetExtrusionDistance(Vector3 objectPos, Light light) {
Vector3 diff = objectPos - light.DerivedPosition;
return light.AttenuationRange - diff.Length;
}
/// <summary>
/// Get the distance to extrude for a point/spot light.
/// </summary>
/// <param name="light"></param>
/// <returns></returns>
public abstract float GetPointExtrusionDistance(Light light);
#endregion Methods
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace BuildIt.CognitiveServices
{
/// <summary>
/// The Image Search API lets partners send a search query to Bing and get
/// back a list of relevant images. Note you should call the Image API if
/// you need image content only. If you need other content such as news
/// and webpages in addition to images, you must call the Search API
/// which includes images in the response. You must display the images in
/// the order provided in the response.
/// </summary>
public partial class ImageSearchAPIV5 : Microsoft.Rest.ServiceClient<ImageSearchAPIV5>, IImageSearchAPIV5
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the ImageSearchAPIV5 class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public ImageSearchAPIV5(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the ImageSearchAPIV5 class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public ImageSearchAPIV5(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the ImageSearchAPIV5 class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ImageSearchAPIV5(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ImageSearchAPIV5 class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ImageSearchAPIV5(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new System.Uri("https://api.cognitive.microsoft.com/bing/v5.0/images");
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <summary>
/// Get relevant images for a given query.
/// </summary>
/// <param name='count'>
/// The number of image results to return in the response. The actual number
/// delivered may be less than requested.
/// </param>
/// <param name='offset'>
/// The zero-based offset that indicates the number of image results to skip
/// before returning results.
/// </param>
/// <param name='mkt'>
/// The market where the results come from. Typically, this is the country
/// where the user is making the request from; however, it could be a
/// different country if the user is not located in a country where Bing
/// delivers results. The market must be in the form {language code}-{country
/// code}. For example, en-US.
///
/// <br>
/// <br>
/// Full list of supported markets:
/// <br>
/// es-AR,en-AU,de-AT,nl-BE,fr-BE,pt-BR,en-CA,fr-CA,es-CL,da-DK,fi-FI,fr-FR,de-DE,zh-HK,en-IN,en-ID,en-IE,it-IT,ja-JP,ko-KR,en-MY,es-MX,nl-NL,en-NZ,no-NO,zh-CN,pl-PL,pt-PT,en-PH,ru-RU,ar-SA,en-ZA,es-ES,sv-SE,fr-CH,de-CH,zh-TW,tr-TR,en-GB,en-US,es-US.
/// Possible values include: 'en-us'
/// </param>
/// <param name='safeSearch'>
/// A filter used to filter results for adult content. Possible values
/// include: 'Off', 'Moderate', 'Strict'
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> SearchWithHttpMessagesAsync(string query, double? count = 10, double? offset = 0, string mkt = "en-us", string safeSearch = "Moderate", string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
string q = query;
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("q", q);
tracingParameters.Add("count", count);
tracingParameters.Add("offset", offset);
tracingParameters.Add("mkt", mkt);
tracingParameters.Add("safeSearch", safeSearch);
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Search", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "search").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (q != null)
{
_queryParameters.Add(string.Format("q={0}", System.Uri.EscapeDataString(q)));
}
if (count != null)
{
_queryParameters.Add(string.Format("count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, this.SerializationSettings).Trim('"'))));
}
if (offset != null)
{
_queryParameters.Add(string.Format("offset={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(offset, this.SerializationSettings).Trim('"'))));
}
if (mkt != null)
{
_queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(mkt)));
}
if (safeSearch != null)
{
_queryParameters.Add(string.Format("safeSearch={0}", System.Uri.EscapeDataString(safeSearch)));
}
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
if (customHeaders != null)
{
foreach (var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get insights for an image sent in the POST body.
/// <br/>
/// <br/>
/// See full documentation for this API <a target="_blank"
/// href="https://msdn.microsoft.com/en-us/library/dn760791.aspx">here<a>
/// </summary>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageInsightsWithHttpMessagesAsync(string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ImageInsights", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "search").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
if (customHeaders != null)
{
foreach (var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get currently trending images.
/// </summary>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TrendingWithHttpMessagesAsync(string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Trending", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "trending").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
if (customHeaders != null)
{
foreach (var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Xunit;
namespace System.IO.Tests
{
public class Directory_GetFileSystemEntries_str : FileSystemTest
{
#region Utilities
public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" };
protected virtual bool TestFiles { get { return true; } } // True if the virtual GetEntries mmethod returns files
protected virtual bool TestDirectories { get { return true; } } // True if the virtual GetEntries mmethod returns Directories
public virtual string[] GetEntries(string dirName)
{
return Directory.GetFileSystemEntries(dirName);
}
#endregion
#region UniversalTests
[Fact]
public void NullFileName()
{
Assert.Throws<ArgumentNullException>(() => GetEntries(null));
}
[Fact]
public void EmptyFileName()
{
Assert.Throws<ArgumentException>(() => GetEntries(string.Empty));
}
[Fact]
public void InvalidFileNames()
{
Assert.Throws<DirectoryNotFoundException>(() => GetEntries("DoesNotExist"));
Assert.Throws<ArgumentException>(() => GetEntries("\0"));
}
[Fact]
public void EmptyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Empty(GetEntries(testDir.FullName));
}
[Fact]
public void GetEntriesThenDelete()
{
string testDirPath = GetTestFilePath();
DirectoryInfo testDirInfo = new DirectoryInfo(testDirPath);
testDirInfo.Create();
string testDir1 = GetTestFileName();
string testDir2 = GetTestFileName();
string testFile1 = GetTestFileName();
string testFile2 = GetTestFileName();
string testFile3 = GetTestFileName();
string testFile4 = GetTestFileName();
string testFile5 = GetTestFileName();
testDirInfo.CreateSubdirectory(testDir1);
testDirInfo.CreateSubdirectory(testDir2);
using (File.Create(Path.Combine(testDirPath, testFile1)))
using (File.Create(Path.Combine(testDirPath, testFile2)))
using (File.Create(Path.Combine(testDirPath, testFile3)))
{
string[] results;
using (File.Create(Path.Combine(testDirPath, testFile4)))
using (File.Create(Path.Combine(testDirPath, testFile5)))
{
results = GetEntries(testDirPath);
Assert.NotNull(results);
Assert.NotEmpty(results);
if (TestFiles)
{
Assert.Contains(Path.Combine(testDirPath, testFile1), results);
Assert.Contains(Path.Combine(testDirPath, testFile2), results);
Assert.Contains(Path.Combine(testDirPath, testFile3), results);
Assert.Contains(Path.Combine(testDirPath, testFile4), results);
Assert.Contains(Path.Combine(testDirPath, testFile5), results);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDirPath, testDir1), results);
Assert.Contains(Path.Combine(testDirPath, testDir2), results);
}
}
File.Delete(Path.Combine(testDirPath, testFile4));
File.Delete(Path.Combine(testDirPath, testFile5));
FailSafeDirectoryOperations.DeleteDirectory(testDir1, true);
results = GetEntries(testDirPath);
Assert.NotNull(results);
Assert.NotEmpty(results);
if (TestFiles)
{
Assert.Contains(Path.Combine(testDirPath, testFile1), results);
Assert.Contains(Path.Combine(testDirPath, testFile2), results);
Assert.Contains(Path.Combine(testDirPath, testFile3), results);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDirPath, testDir2), results);
}
}
}
[Fact]
public virtual void IgnoreSubDirectoryFiles()
{
string subDir = GetTestFileName();
Directory.CreateDirectory(Path.Combine(TestDirectory, subDir));
string testFile = Path.Combine(TestDirectory, GetTestFileName());
string testFileInSub = Path.Combine(TestDirectory, subDir, GetTestFileName());
string testDir = Path.Combine(TestDirectory, GetTestFileName());
string testDirInSub = Path.Combine(TestDirectory, subDir, GetTestFileName());
Directory.CreateDirectory(testDir);
Directory.CreateDirectory(testDirInSub);
using (File.Create(testFile))
using (File.Create(testFileInSub))
{
string[] results = GetEntries(TestDirectory);
if (TestFiles)
Assert.Contains(testFile, results);
if (TestDirectories)
Assert.Contains(testDir, results);
Assert.DoesNotContain(testFileInSub, results);
Assert.DoesNotContain(testDirInSub, results);
}
}
[Fact]
public void NonexistentPath()
{
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(GetTestFilePath()));
}
[Fact]
public void TrailingSlashes()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName()));
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
string[] strArr = GetEntries(testDir.FullName + new string(Path.DirectorySeparatorChar, 5));
Assert.NotNull(strArr);
Assert.NotEmpty(strArr);
}
}
#endregion
#region PlatformSpecific
[Fact]
public void InvalidPath()
{
foreach (char invalid in Path.GetInvalidFileNameChars())
{
if (invalid == '/' || invalid == '\\')
{
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString()))));
}
else if (invalid == ':')
{
if (FileSystemDebugInfo.IsCurrentDriveNTFS())
Assert.Throws<NotSupportedException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString()))));
}
else
{
Assert.Throws<ArgumentException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString()))));
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-only Invalid chars in path
public void WindowsInvalidCharsPath()
{
Assert.All(WindowsInvalidUnixValid, invalid =>
Assert.Throws<ArgumentException>(() => GetEntries(invalid)));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-only valid chars in file path
public void UnixValidCharsFilePath()
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
string[] results = GetEntries(testDir.FullName);
Assert.All(WindowsInvalidUnixValid, valid =>
Assert.Contains(Path.Combine(testDir.FullName, valid), results));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Windows-only invalid chars in directory path
public void UnixValidCharsDirectoryPath()
{
if (TestDirectories)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
testDir.CreateSubdirectory(valid);
string[] results = GetEntries(testDir.FullName);
Assert.All(WindowsInvalidUnixValid, valid =>
Assert.Contains(Path.Combine(testDir.FullName, valid), results));
}
}
#endregion
}
public sealed class Directory_GetEntries_CurrentDirectory : RemoteExecutorTestBase
{
[Fact]
public void CurrentDirectory()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
File.WriteAllText(Path.Combine(testDir, GetTestFileName()), "cat");
Directory.CreateDirectory(Path.Combine(testDir, GetTestFileName()));
RemoteInvoke((testDirectory) =>
{
Directory.SetCurrentDirectory(testDirectory);
Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory()));
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
return SuccessExitCode;
}, $"\"{testDir}\"").Dispose();
}
}
}
| |
//
// Bugzz - Multi GUI Desktop Bugzilla Client
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc.
//
// Authors:
// Andreia Gaita ([email protected])
// Marek Habersack ([email protected])
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Bugzz;
using Bugzz.Bugzilla;
using HtmlAgilityPack;
namespace Bugzz.Network
{
internal class WebIO
{
readonly static string userAgent;
CookieManager cookieJar;
DataManager dataManager;
LoginData loginData;
public event Bugzz.DocumentRetrieveFailureEventHandler DocumentRetrieveFailure;
public event Bugzz.DownloadStartedEventHandler DownloadStarted;
public event Bugzz.DownloadEndedEventHandler DownloadEnded;
public event Bugzz.DownloadProgressEventHandler DownloadProgress;
private Uri baseUrl;
public Uri BaseUrl {
get { return baseUrl; }
set { baseUrl = value; }
}
public long MaxRequestAttempts;// { get; set; }
public long MaxLoginAttempts;// { get; set; }
static WebIO ()
{
// TODO: construct something funnier later on
userAgent = global::Bugzz.Constants.Package + "/" + global::Bugzz.Constants.Version;
}
public WebIO (string baseUrl, LoginData loginData, DataManager dataManager)
{
MaxRequestAttempts = 3;
MaxLoginAttempts = 3;
this.loginData = loginData;
this.dataManager = dataManager;
if (!String.IsNullOrEmpty (baseUrl)) {
try {
this.baseUrl = new Uri (baseUrl);
} catch (Exception ex) {
throw new ArgumentException ("Invalid base URL.", "baseUrl", ex);
}
}
cookieJar = new CookieManager ();
}
void OnDocumentRetrieveFailure (Uri uri, HttpStatusCode status)
{
if (DocumentRetrieveFailure == null)
return;
DocumentRetrieveFailure (new DocumentRetrieveFailureEventArgs (uri, status));
}
void OnDownloadStarted (Uri uri, long contentLength)
{
if (DownloadStarted == null)
return;
DownloadStarted (new DownloadStartedEventArgs (uri, contentLength));
}
void OnDownloadEnded (Uri uri, long contentLength, HttpStatusCode status)
{
if (DownloadEnded == null)
return;
DownloadEnded (new DownloadEndedEventArgs (uri, contentLength, status));
}
void OnDownloadProgress (long maxCount, long curCount)
{
if (DownloadProgress == null)
return;
DownloadProgress (new DownloadProgressEventArgs (maxCount, curCount));
}
public string PostDocument (string relativeUrl, string expectedResponseType, Regex fallbackTypeRegex)
{
return null;
}
public string GetDocument (string relativeUrl, string expectedContentType, Regex fallbackTypeRegex)
{
Uri baseUrl = BaseUrl;
if (baseUrl == null)
return null;
Uri fullUrl;
UriBuilder ub = new UriBuilder (baseUrl);
try {
ub.Path = relativeUrl;
fullUrl = new Uri (ub.ToString ());
} catch (Exception ex) {
throw new WebIOException ("Malformed relative URL.", relativeUrl, ex);
}
string response;
Uri redirect;
bool addressesMatch, standardLogin;
long attempts = MaxRequestAttempts;
long loginAttempts = MaxLoginAttempts;
HttpStatusCode status = HttpStatusCode.BadRequest;
bool loggedIn = false;
Console.WriteLine ("Requesting URL: {0}", fullUrl);
while (attempts > 0) {
try {
status = Get (fullUrl, expectedContentType, fallbackTypeRegex, out response, out addressesMatch,
out standardLogin, out redirect, false);
if (status != HttpStatusCode.OK) {
attempts--;
continue;
}
if (!addressesMatch) {
if (loginAttempts <= 0)
throw new WebIOException ("Login failure.", redirect.ToString ());
loggedIn = false;
Uri loginAddress = loginData.Url;
Console.WriteLine ("loginAddress == {0}", loginAddress);
loginAttempts--;
if (redirect != null && loginAddress.Scheme == redirect.Scheme &&
loginAddress.Host == redirect.Host &&
loginAddress.AbsolutePath == redirect.AbsolutePath) {
UriBuilder uri = new UriBuilder ();
uri.Scheme = redirect.Scheme;
uri.Host = redirect.Host;
uri.Path = redirect.AbsolutePath + loginData.FormActionUrl;
Console.WriteLine ("Login attempts left: {0}", loginAttempts);
LogIn (uri);
continue;
}
} else if (standardLogin) {
Console.WriteLine ("Standard login found. Will POST to '{0}'", redirect.ToString ());
LogIn (new UriBuilder (redirect));
} else
loggedIn = true;
if (!loggedIn)
if (loginAttempts <= 0)
throw new WebIOException ("Login failure.", redirect != null ? redirect.ToString () : String.Empty);
else {
loginAttempts--;
continue;
}
return response;
} catch (BugzzException) {
throw;
} catch (Exception ex) {
throw new WebIOException ("Error downloading document.", fullUrl.ToString (), ex);
} finally {
if (status != HttpStatusCode.OK)
OnDocumentRetrieveFailure (fullUrl, status);
}
};
return null;
}
bool LogIn (UriBuilder formPostUri)
{
if (String.IsNullOrEmpty (loginData.Username) || String.IsNullOrEmpty (loginData.Password))
return false;
string usernameField = loginData.UsernameField, passwordField = loginData.PasswordField;
VersionData bvd = null;
if (String.IsNullOrEmpty (usernameField)) {
bvd = dataManager.VersionData;
usernameField = bvd.GetLoginVariable ("bugzilla_login");
if (String.IsNullOrEmpty (usernameField))
throw new BugzillaException ("Missing bugzilla login form field name 'bugzilla_login'");
}
if (String.IsNullOrEmpty (passwordField)) {
if (bvd == null)
bvd = dataManager.VersionData;
passwordField = bvd.GetLoginVariable ("bugzilla_password");
if (String.IsNullOrEmpty (passwordField))
throw new BugzillaException ("Missing bugzilla login form field name 'bugzilla_password'.");
}
Console.WriteLine ("Attempting to log in ");//at '" + req.Address.ToString () + "'.");
string postData = usernameField + "=" + loginData.Username + "&" + passwordField + "=" + loginData.Password;
foreach (KeyValuePair <string, string> kvp in loginData.ExtraData)
postData += ("&" + kvp.Key + "=" + kvp.Value);
Console.WriteLine ("Login POST url: {0}", formPostUri.ToString ());
Console.WriteLine ("Post data: {0}", postData);
string response;
HttpStatusCode status = Post (new Uri (formPostUri.ToString ()), postData, out response, true);
if (status == HttpStatusCode.OK)
return true;
return false;
}
bool MatchingContentType (string contentType, string response, string expectedContentType, Regex fallbackTypeRegex)
{
Console.WriteLine ("{0}.MatchingContentType ()", this);
Console.WriteLine ("\tcontent type: {0}", contentType);
Console.WriteLine ("\texpected: {0}", expectedContentType);
List <string> typeStrings = dataManager.GetMimeType (expectedContentType);
Console.WriteLine ("typeStrings == {0}", typeStrings);
if (String.IsNullOrEmpty (contentType) || typeStrings == null) {
if (fallbackTypeRegex == null || response == null)
return false;
return fallbackTypeRegex.IsMatch (response);
}
foreach (string type in typeStrings) {
Console.WriteLine ("Type: {0}", type);
if (contentType.StartsWith (type))
return true;
}
return false;
}
bool HasLoginForm (HttpWebRequest request, string response, out Uri action)
{
if (String.IsNullOrEmpty (response)) {
action = null;
return false;
}
HtmlDocument doc = new HtmlDocument ();
try {
doc.LoadHtml (response);
} catch {
// failed, not html - no form
action = null;
return false;
}
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes ("//form[string-length (@name) > 0 and string-length (@action) > 0]");
if (nodes == null || nodes.Count == 0) {
action = null;
return false;
}
VersionData bvd = dataManager.VersionData;
string usernameField = bvd.GetLoginVariable ("bugzilla_login");
if (String.IsNullOrEmpty (usernameField))
throw new BugzillaException ("Missing bugzilla login form field name 'bugzilla_login'");
string passwordField = bvd.GetLoginVariable ("bugzilla_password");
if (String.IsNullOrEmpty (passwordField))
throw new BugzillaException ("Missing bugzilla login form field name 'bugzilla_password'.");
HtmlAttributeCollection attributes;
foreach (HtmlNode node in nodes) {
attributes = node.Attributes;
if (attributes ["name"].Value != "login")
continue;
string actionValue = attributes ["action"].Value;
Uri actionUri = new Uri (actionValue, UriKind.RelativeOrAbsolute);
if (actionUri.IsAbsoluteUri) {
action = actionUri;
return true;
}
UriBuilder ub = new UriBuilder (request.Address);
ub.Query = null;
ub.Fragment = null;
string path = ub.Path;
int idx;
if (!path.EndsWith ("/")) {
idx = path.LastIndexOf ("/");
if (idx > -1)
path = path.Substring (0, idx + 1);
else
path += "/";
}
idx = actionValue.IndexOf ("?");
if (idx > -1)
path += actionValue.Substring (0, idx + 1);
else
path += actionValue;
ub.Path = path;
action = ub.Uri;
return true;
}
action = null;
return false;
}
private HttpStatusCode Get (Uri uri, string expectedContentType, Regex fallbackTypeRegex,
out string response, out bool addressesMatch, out bool standardLogin, out Uri redirectAddress, bool ignoreResponse)
{
long contentLength = -1;
HttpStatusCode statusCode = HttpStatusCode.NotFound;
cookieJar.AddUri (uri);
HttpWebRequest request = WebRequest.Create (uri) as HttpWebRequest;
HttpWebResponse resp = null;
request.Method = "GET";
request.UserAgent = userAgent;
request.CookieContainer = cookieJar;
response = null;
standardLogin = false;
try {
resp = request.GetResponse () as HttpWebResponse;
statusCode = resp.StatusCode;
Console.WriteLine ("GET: content type == '" + resp.ContentType + "'");
addressesMatch = (request.Address == uri);
Console.WriteLine ("GET:addressesMatch = " + addressesMatch);
redirectAddress = request.Address;
StringBuilder sb = new StringBuilder ();
if (!ignoreResponse) {
Stream d = resp.GetResponseStream ();
char[] buffer = new char[4096];
int bufferLen = buffer.Length;
int charsRead = -1;
long count;
using (StreamReader reader = new StreamReader (d)) {
count = 0;
contentLength = resp.ContentLength;
OnDownloadStarted (uri, contentLength);
if (contentLength == -1)
contentLength = Int64.MaxValue; // potentially
// dangerous
while (count < contentLength) {
charsRead = reader.Read (buffer, 0, bufferLen);
if (charsRead == 0)
break;
count += charsRead;
OnDownloadProgress (contentLength, count);
sb.Append (buffer, 0, charsRead);
}
OnDownloadEnded (uri, contentLength, statusCode);
}
}
//Console.WriteLine ("----GET----");
//Console.WriteLine (sb.ToString ());
//Console.WriteLine ("----END OF GET----");
response = sb.ToString ();
} catch (WebException ex) {
Console.WriteLine ("GET WebException");
Exception e = ex;
while (e != null) {
Console.WriteLine (e.Message);
Console.WriteLine (e.StackTrace);
e = e.InnerException;
}
response = null;
redirectAddress = null;
addressesMatch = true;
if (ex.Response != null) {
try {
HttpWebResponse exResponse = ex.Response as HttpWebResponse;
statusCode = exResponse.StatusCode;
} catch {
statusCode = HttpStatusCode.BadRequest;
}
}
if (statusCode == HttpStatusCode.NotModified) {
statusCode = HttpStatusCode.OK;
OnDownloadEnded (uri, contentLength, statusCode);
} else {
OnDocumentRetrieveFailure (uri, statusCode);
throw new WebIOException ("Request failed.", uri.ToString (), ex);
}
} catch (Exception ex) {
Console.WriteLine ("GET Exception");
Exception e = ex;
while (e != null) {
Console.WriteLine (e.Message);
Console.WriteLine (e.StackTrace);
e = e.InnerException;
}
response = null;
redirectAddress = null;
addressesMatch = false;
throw new WebIOException ("Request failed.", uri.ToString (), ex);
} finally {
cookieJar.Save ();
if (resp != null) {
Uri loginFormRedirect;
if (HasLoginForm (request, response, out loginFormRedirect)) {
standardLogin = true;
response = null;
redirectAddress = loginFormRedirect;
} else if (!MatchingContentType (resp.ContentType, response, expectedContentType, fallbackTypeRegex))
response = null;
resp.Close ();
}
}
return statusCode;
}
private HttpStatusCode Post (Uri uri, string postData, out string response, bool ignoreResponse)
{
HttpStatusCode statusCode = HttpStatusCode.NotFound;
ASCIIEncoding ascii = new ASCIIEncoding ();
byte[] data = ascii.GetBytes (postData);
cookieJar.AddUri (uri);
HttpWebRequest request = WebRequest.Create (uri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.UserAgent = userAgent;
request.CookieContainer = cookieJar;
HttpWebResponse resp = null;
try {
using (Stream s = request.GetRequestStream ()) {
s.Write (data, 0, data.Length);
}
resp = request.GetResponse () as HttpWebResponse;
statusCode = resp.StatusCode;
StringBuilder sb = new StringBuilder ();
if (!ignoreResponse) {
Stream d = resp.GetResponseStream ();
char[] buffer = new char[4096];
int bufferLen = buffer.Length;
int charsRead = -1;
long count;
using (StreamReader reader = new StreamReader (d)) {
count = 0;
long contentLength = resp.ContentLength;
if (contentLength == -1)
contentLength = Int64.MaxValue; // potentially
// dangerous
while (count < contentLength) {
charsRead = reader.Read (buffer, 0, bufferLen);
if (charsRead == 0)
break;
count += charsRead;
sb.Append (buffer, 0, charsRead);
}
}
}
response = sb.ToString ();
} catch (Exception ex) {
Console.WriteLine ("POST Exception");
Exception e = ex;
while (e != null) {
Console.WriteLine (e.Message);
Console.WriteLine (e.StackTrace);
e = e.InnerException;
}
response = String.Empty;
throw new WebIOException ("Request failed.", uri.ToString (), ex);
} finally {
cookieJar.Save ();
if (resp != null)
resp.Close ();
}
return statusCode;
}
}
}
| |
using Akka.Actor;
using EasyExecute.Common;
using EasyExecuteLib;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Xunit.Sdk;
namespace EasyExecute.Tests
{
public class when_concurrent_service_is_used_where_result_are_cached_by_id
{
[Fact]
public void test_reactive()
{
var total = 100;
var counter = 0;
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions()
{
actorSystem = ActorSystem.Create("ConcurrentExecutorServiceActorSystem", "akka { } akka.actor{ } akka.remote { } "),
purgeInterval = TimeSpan.FromSeconds(5)
});
var result = service.ExecuteAsync("1", async () =>
{
await Task.Delay(TimeSpan.FromMilliseconds(10));
counter++;
return new object();
}, (r) => counter < total + 2, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true,
MaxRetryCount = total,
ExecuteReactively = true
}, (r) => r.Result).Result;
Assert.True(result.Succeeded);
bool hasRunAll;
var retryCount = 0;
do
{
hasRunAll = service.GetWorkHistoryAsync("1").Result.Result.WorkHistory.Any(x => x.WorkerStatus.Succeeded);
Task.Delay(TimeSpan.FromMilliseconds(10)).Wait();
retryCount++;
if (retryCount > 1000) break;
} while (!hasRunAll);
Assert.True(total + 1 == counter);
Assert.True(retryCount > 0);
}
[Fact]
public void it_should_be_able_to_retry4()
{
var total = 1000;
var counter = 0;
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions()
{
actorSystem = ActorSystem.Create("ConcurrentExecutorServiceActorSystem", "akka { } akka.actor{ } akka.remote { } "),
purgeInterval = TimeSpan.FromSeconds(5)
});
var result = service.ExecuteAsync("1", async () =>
{
await Task.Delay(TimeSpan.FromMilliseconds(10));
counter++;
return new object();
}, (r) => counter < total + 2, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true,
MaxRetryCount = total
}, (r) => r.Result).Result;
Assert.False(result.Succeeded);
Assert.Equal(total + 1, counter);
}
[Fact]
public void it_should_be_able_to_retry3()
{
var total = 1000;
var counter = 0;
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions()
{
actorSystem = ActorSystem.Create("ConcurrentExecutorServiceActorSystem", "akka { } akka.actor{ } akka.remote { } "),
purgeInterval = TimeSpan.FromSeconds(5)
});
foreach (var i in Enumerable.Range(1, total))
{
var result = service.ExecuteAsync("1", async () =>
{
await Task.Delay(TimeSpan.FromMilliseconds(10));
counter++;
return new object();
}, (r) => i < total + 1, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true
}, (r) => r.Result).Result;
Assert.False(result.Succeeded);
Assert.True(counter == i);
}
}
[Fact]
public void it_should_be_able_to_retry2()
{
var counter = 0;
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions()
{
actorSystem = ActorSystem.Create("ConcurrentExecutorServiceActorSystem", "akka { } akka.actor{ } akka.remote { } "),
purgeInterval = TimeSpan.FromSeconds(5)
});
var result = service.ExecuteAsync("1", async () =>
{
counter++;
return await Task.FromResult(new object());
}, (r) => counter < 4, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true
}, (r) => r.Result).Result;
Assert.False(result.Succeeded);
Assert.True(counter == 1);
}
[Fact]
public void it_should_be_able_to_retry()
{
var counter = 0;
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions()
{
actorSystem = ActorSystem.Create("ConcurrentExecutorServiceActorSystem", "akka { } akka.actor{ } akka.remote { } "),
purgeInterval = TimeSpan.FromSeconds(5)
});
var result = service.ExecuteAsync("1", async () =>
{
counter++;
return await Task.FromResult(new object());
}, (r) => counter < 4, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true,
MaxRetryCount = 4
}, (r) => r.Result).Result;
Assert.True(result.Succeeded);
Assert.True(counter == 4);
Task.Delay(TimeSpan.FromSeconds(5)).Wait();
result = service.ExecuteAsync("1", async () =>
{
counter++;
return await Task.FromResult(new object());
}, (r) => counter < 4, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true,
MaxRetryCount = 4
}, (r) => r.Result).Result;
Assert.False(result.Succeeded);
Assert.True(counter == 4);
Task.Delay(TimeSpan.FromSeconds(10)).Wait();
result = service.ExecuteAsync("1", async () =>
{
counter++;
return await Task.FromResult(new object());
}, (r) => counter < 4, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true,
MaxRetryCount = 4
}, (r) => r.Result).Result;
Assert.True(result.Succeeded);
Assert.True(counter == 5);
}
[Fact]
public void invoke_call_back_global_on_cache_expirartion()
{
var peekedWorker = "";
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions()
{
actorSystem = ActorSystem.Create("ConcurrentExecutorServiceActorSystem", "akka { } akka.actor{ } akka.remote { } "),
purgeInterval = TimeSpan.FromSeconds(5),
onWorkerPurged = (w) => { peekedWorker = w.WorkerId; }
});
var result = service.ExecuteAsync("1", async () =>
{
return await Task.FromResult(new object());
}, (r) => false, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true
}, (r) => r.Result).Result;
Assert.False(peekedWorker == "1");
Task.Delay(TimeSpan.FromSeconds(11)).Wait();
result = service.ExecuteAsync("1", async () =>
{
return await Task.FromResult(new object());
}, (r) => false, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true
}, (r) => r.Result).Result;
Assert.True(result.Succeeded);
Assert.True(peekedWorker == "1");
}
[Fact]
public void invoke_call_back_inline_on_cache_expirartion()
{
var peekedWorker = "";
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions()
{
actorSystem = ActorSystem.Create("ConcurrentExecutorServiceActorSystem", "akka { } akka.actor{ } akka.remote { } "),
purgeInterval = TimeSpan.FromSeconds(5)
});
var result = service.ExecuteAsync("1", async () =>
{
return await Task.FromResult(new object());
}, (r) => false, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true,
OnWorkerPurged = (w) => { peekedWorker = w.WorkerId; }
}, (r) => r.Result).Result;
Assert.False(peekedWorker == "1");
Task.Delay(TimeSpan.FromSeconds(11)).Wait();
result = service.ExecuteAsync("1", async () =>
{
return await Task.FromResult(new object());
}, (r) => false, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true
}, (r) => r.Result).Result;
Assert.True(result.Succeeded);
Assert.True(peekedWorker == "1");
}
[Fact]
public void it_should_be_able_to_set_cache_expiration_per_call()
{
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions()
{
actorSystem = ActorSystem.Create("ConcurrentExecutorServiceActorSystem", "akka { } akka.actor{ } akka.remote { } "),
purgeInterval = TimeSpan.FromSeconds(5)
});
var result = service.ExecuteAsync("1", async () =>
{
return await Task.FromResult(new object());
}, (r) => false, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true
}, (r) => r.Result).Result;
Assert.True(result.Succeeded);
Task.Delay(TimeSpan.FromSeconds(5)).Wait();
result = service.ExecuteAsync("1", async () =>
{
return await Task.FromResult(new object());
}, (r) => false, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true
}, (r) => r.Result).Result;
Assert.False(result.Succeeded);
Task.Delay(TimeSpan.FromSeconds(10)).Wait();
result = service.ExecuteAsync("1", async () =>
{
return await Task.FromResult(new object());
}, (r) => false, TimeSpan.FromHours(1), new ExecutionRequestOptions()
{
CacheExpirationPeriod = TimeSpan.FromSeconds(10),
DontCacheResultById = false,
StoreCommands = true
}, (r) => r.Result).Result;
Assert.True(result.Succeeded);
}
[Fact]
public void return_execution_history()
{
var service = new EasyExecuteLib.EasyExecute();
var t = service.ExecuteAsync("1",
() => Task.FromResult(new object()),
(finalResult) => false,
TimeSpan.FromSeconds(5), new ExecutionRequestOptions()
{
DontCacheResultById = false
}, (executionResult) => executionResult.Result).Result.Result;
Assert.NotNull(t);
var history = service.GetWorkHistoryAsync().Result;
Assert.True(history.Result.WorkHistory.First().WorkerStatus.IsCompleted);
var logs = service.GetWorkLogAsync().Result;
Assert.True(logs.Result.WorkLog.Count == 6);
}
[Fact]
public void test3()
{
var service = new EasyExecuteLib.EasyExecute();
var t = (service.ExecuteAsync("1", DateTime.UtcNow,
(d) => Task.FromResult(new { time = d }),
(finalResult) => false,
TimeSpan.FromSeconds(5), new ExecutionRequestOptions()
{
DontCacheResultById = false
}, (executionResult) => executionResult.Result)).Result.Result;
Assert.NotNull(t);
var history = service.GetWorkHistoryAsync().Result;
Assert.True(history.Result.WorkHistory.First().WorkerStatus.IsCompleted);
}
[Fact]
public void test2()
{
var service = new EasyExecuteLib.EasyExecute();
var t = (service.ExecuteAsync("1", () =>
{
return Task.FromResult(new object());
}, (finalResult) =>
{
return false;
}, TimeSpan.FromSeconds(5), new ExecutionRequestOptions()
{
DontCacheResultById = false
})).Result.Result;
Assert.NotNull(t);
}
[Fact]
public void test_max_execution_time_not_exceeded()
{
var service = new EasyExecuteLib.EasyExecute();
var result = service.ExecuteAsync<object>("1", () =>
{
Task.Delay(TimeSpan.FromSeconds(1)).Wait(); return Task.FromResult(new object());
}, (r) => false, TimeSpan.FromSeconds(3), new ExecutionRequestOptions()
{
DontCacheResultById = false
}).Result;
Assert.True(result.Succeeded);
}
[Fact]
public void test_max_execution_time_not_exceeded2()
{
var service = new EasyExecuteLib.EasyExecute();
var result = service.ExecuteAsync<object>("1", async () =>
{
await Task.Delay(TimeSpan.FromSeconds(1)); return new object();
}, (r) => false, TimeSpan.FromSeconds(3), new ExecutionRequestOptions()
{
DontCacheResultById = false
}).Result;
Assert.True(result.Succeeded);
}
[Fact]
public void test_max_execution_time_not_exceeded3()
{
var service = new EasyExecuteLib.EasyExecute();
var result = service.ExecuteAsync<object>("1", async () =>
{
await Task.Delay(TimeSpan.FromSeconds(1)); return Task.FromResult(new object());
}, (r) => false, TimeSpan.FromSeconds(3), new ExecutionRequestOptions()
{
DontCacheResultById = false
}).Result;
Assert.True(result.Succeeded);
}
[Fact]
public void test_max_execution_time_exceeded_should_return_correct_value_when_called_again()
{
var now = DateTime.UtcNow;
var service = new EasyExecuteLib.EasyExecute();
var result = service.ExecuteAsync<object>("1", async () =>
{
await Task.Delay(TimeSpan.FromSeconds(3));
return await Task.FromResult(now);
}, (r) => false, TimeSpan.FromSeconds(1), new ExecutionRequestOptions()
{
DontCacheResultById = false
}).Result;
Assert.False(result.Succeeded);
Assert.NotEqual(now, result.Result);
SimulateNormalClient();
SimulateNormalClient();
result = service.ExecuteAsync<object>("1", async () =>
{
await Task.Delay(TimeSpan.FromSeconds(1)); return await Task.FromResult(DateTime.UtcNow);
}, (r) => false, TimeSpan.FromSeconds(3), new ExecutionRequestOptions()
{
DontCacheResultById = false
}).Result;
Assert.False(result.Succeeded);
Assert.Equal(now, result.Result);
}
[Fact]
public void test_max_execution_time_exceeded()
{
var service = new EasyExecuteLib.EasyExecute();
var result = service.ExecuteAsync<object>("1", () =>
{
Task.Delay(TimeSpan.FromSeconds(6)).Wait(); return Task.FromResult(new object());
}, (r) => false, TimeSpan.FromSeconds(3), new ExecutionRequestOptions()
{
DontCacheResultById = false
}).Result;
Assert.False(result.Succeeded);
}
[Fact]
public void test_max_execution_time_exceeded2()
{
var service = new EasyExecuteLib.EasyExecute();
var result = service.ExecuteAsync<object>("1", async () =>
{
await Task.Delay(TimeSpan.FromSeconds(6)); return new object();
}, (r) => false, TimeSpan.FromSeconds(3), new ExecutionRequestOptions()
{
DontCacheResultById = false
}).Result;
Assert.False(result.Succeeded);
}
[Fact]
public void test_max_execution_time_exceeded3()
{
var service = new EasyExecuteLib.EasyExecute();
var result = service.ExecuteAsync<object>("1", async () =>
{
await Task.Delay(TimeSpan.FromSeconds(6)); return Task.FromResult(new object());
}, (r) => false, TimeSpan.FromSeconds(3), new ExecutionRequestOptions()
{
DontCacheResultById = false
}).Result;
Assert.False(result.Succeeded);
}
[Fact]
public void it_should_block_duplicate_work_id()
{
var service = new EasyExecuteLib.EasyExecute();
var result =
service.ExecuteAsync<object>("1", () => Task.FromResult(new object())).Result;
Assert.True(result.Succeeded);
SimulateNormalClient();
var result2 =
service.ExecuteAsync<object>("1", () => Task.FromResult(new object())).Result;
Assert.False(result2.Succeeded);
}
private static void SimulateNormalClient()
{
//simulating fast client send
System.Threading.Thread.Sleep(1000);
System.Threading.Thread.Sleep(1000);
System.Threading.Thread.Sleep(1000);
}
[Fact]
public void it_should_fail_when_client_markes_result_as_failure()
{
var service = new EasyExecuteLib.EasyExecute();
var result = service.ExecuteAsync<object>("1", () => Task.FromResult(new object()), (r) => true).Result;
Assert.False(result.Succeeded);
SimulateNormalClient();
var result2 = service.ExecuteAsync<object>("1", () => Task.FromResult(new object())).Result;
Assert.True(result2.Succeeded);
}
[Fact]
public void it_should_fail_when_client_markes_result_as_failure2()
{
var service = new EasyExecuteLib.EasyExecute();
var result =
service.ExecuteAsync<object>("1", () => Task.FromResult(new object())).Result;
Assert.True(result.Succeeded);
var result2 =
service.ExecuteAsync<object>("1", () => Task.FromResult(new object()), (r) => true).Result;
Assert.False(result2.Succeeded);
}
[Fact]
public void it_should_fail_when_client_markes_result_as_failure_even_with_different_id()
{
var service = new EasyExecuteLib.EasyExecute();
var result =
service.ExecuteAsync<object>("1", () => Task.FromResult(new object())).Result;
Assert.True(result.Succeeded);
var result2 =
service.ExecuteAsync<object>("2", () => Task.FromResult(new object()), (r) => true).Result;
Assert.False(result2.Succeeded);
}
[Fact]
public void it_should_fail_when_client_markes_result_as_failure3()
{
var service = new EasyExecuteLib.EasyExecute();
var result =
service.ExecuteAsync<object>("1", () => Task.FromResult(new object()), (r) => false).Result;
Assert.True(result.Succeeded);
var result2 =
service.ExecuteAsync<object>("1", () => Task.FromResult(new object()), (r) => true).Result;
Assert.False(result2.Succeeded);
}
[Fact]
public void it_should_fail_when_client_markes_result_as_failure_even_with_different_id2()
{
var service = new EasyExecuteLib.EasyExecute();
var result =
service.ExecuteAsync<object>("1", () => Task.FromResult(new object()), (r) => false).Result;
Assert.True(result.Succeeded);
var result2 =
service.ExecuteAsync<object>("2", () => Task.FromResult(new object()), (r) => true).Result;
Assert.False(result2.Succeeded);
}
[Fact]
public void it_should_pass_when_client_markes_result_as_failure_with_different_id()
{
var service = new EasyExecuteLib.EasyExecute();
var result =
service.ExecuteAsync<object>("1", () => Task.FromResult(new object())).Result;
Assert.True(result.Succeeded);
var result2 =
service.ExecuteAsync<object>("2", () => Task.FromResult(new object()), (r) => false).Result;
Assert.True(result2.Succeeded);
}
[Fact]
public void it_should_pass_when_client_markes_result_as_failure_with_different_id2()
{
var service = new EasyExecuteLib.EasyExecute();
var result =
service.ExecuteAsync<object>("1"
, () => Task.FromResult(new object()), (r) => false).Result;
Assert.True(result.Succeeded);
var result2 =
service.ExecuteAsync<object>("2", () => Task.FromResult(new object())).Result;
Assert.True(result2.Succeeded);
}
[Fact]
public void it_should_run_many_operations_fast()
{
const int numberOfRequests = 2000;
var maxExecutionTimePerAskCall = TimeSpan.FromSeconds(3);
const int maxTotalExecutionTimeMs = 6000;
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions() { maxExecutionTimePerAskCall = maxExecutionTimePerAskCall });
var watch = Stopwatch.StartNew();
Parallel.ForEach(Enumerable.Range(0, numberOfRequests),
basket =>
{
var result =
service.ExecuteAsync<object>(basket.ToString(), () => Task.FromResult(new object())).Result;
});
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Assert.True(elapsedMs < maxTotalExecutionTimeMs,
$"Test took {elapsedMs} ms which is more than {maxTotalExecutionTimeMs}");
}
[Fact]
public void it_should_run_one_operations_sequentially()
{
const int numberOfBaskets = 100;
const int numberOfPurchaseFromOneBasketCount = 1;
var maxExecutionTimePerAskCall = TimeSpan.FromSeconds(5);
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions() { maxExecutionTimePerAskCall = maxExecutionTimePerAskCall });
var durationMs = TestHelper.TestOperationExecution(numberOfBaskets, numberOfPurchaseFromOneBasketCount,
(basketIds, purchaseService) =>
{
Parallel.ForEach(basketIds,
basketId =>
{
var result =
service.ExecuteAsync(basketId, () => purchaseService.RunPurchaseServiceAsync(basketId)).Result;
});
},
maxExecutionTimePerAskCall);
Console.WriteLine($"Test took {durationMs} ms");
}
[Fact]
public void it_should_run_many_operations_sequentially()
{
const int numberOfBaskets = 100;
const int numberOfPurchaseFromOneBasketCount = 10;
var maxExecutionTimePerAskCall = TimeSpan.FromSeconds(6);
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions() { maxExecutionTimePerAskCall = maxExecutionTimePerAskCall });
TestHelper.TestOperationExecution(numberOfBaskets, numberOfPurchaseFromOneBasketCount,
(basketIds, purchaseService) =>
{
Parallel.ForEach(basketIds,
basketId =>
{
var result =
service.ExecuteAsync(basketId, () => purchaseService.RunPurchaseServiceAsync(basketId)).Result;
});
},
maxExecutionTimePerAskCall);
}
[Fact]
public void it_should_fail_torun_many_operations_sequentially_without_helper()
{
const int numberOfBaskets = 100;
const int numberOfPurchaseFromOneBasketCount = 10;
var maxExecutionTimePerAskCall = TimeSpan.FromSeconds(5);
var service = new EasyExecuteLib.EasyExecute(new EasyExecuteOptions() { maxExecutionTimePerAskCall = maxExecutionTimePerAskCall });
Assert.Throws<AllException>(() =>
{
TestHelper.TestOperationExecution(numberOfBaskets, numberOfPurchaseFromOneBasketCount,
(basketIds, purchaseService) =>
{
Parallel.ForEach(basketIds, basketId => { purchaseService.RunPurchaseServiceAsync(basketId); });
},
maxExecutionTimePerAskCall);
});
}
}
}
| |
#region Header
//
// CmdWallTopFaces.cs - retrieve top faces of selected or all wall
//
// Copyright (C) 2011-2021 by Jeremy Tammik, Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#define CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
#endregion // Namespaces
namespace BuildingCoder
{
#if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
[Transaction(TransactionMode.Manual)]
#else
[Transaction( TransactionMode.ReadOnly )]
#endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
internal class CmdWallTopFaces : IExternalCommand
{
/// <summary>
/// Super-simple test whether a face is planar
/// and its normal vector points upwards.
/// </summary>
private static bool IsTopPlanarFace(Face f)
{
return f is PlanarFace face
&& Util.PointsUpwards(face.FaceNormal);
}
/// <summary>
/// Simple test whether a given face normal vector
/// points upwards in the middle of the face.
/// </summary>
private static bool IsTopFace(Face f)
{
var b = f.GetBoundingBox();
var p = b.Min;
var q = b.Max;
var midpoint = p + 0.5 * (q - p);
var normal = f.ComputeNormal(midpoint);
return Util.PointsUpwards(normal);
}
/// <summary>
/// Define equality between XYZ objects, ensuring
/// that almost equal points compare equal. Cf.
/// CmdNestedInstanceGeo.XyzEqualityComparer,
/// which uses the native Revit API XYZ comparison
/// member method IsAlmostEqualTo. We cannot use
/// it here, because the tolerance built into that
/// method is too fine and does not recognise
/// points that we need to identify as equal.
/// </summary>
public class XyzEqualityComparer : IEqualityComparer<XYZ>
{
private readonly double _eps;
public XyzEqualityComparer(double eps)
{
Debug.Assert(0 < eps,
"expected a positive tolerance");
_eps = eps;
}
public bool Equals(XYZ p, XYZ q)
{
return _eps > p.DistanceTo(q);
}
public int GetHashCode(XYZ p)
{
return Util.PointString(p).GetHashCode();
}
}
#if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
/// <summary>
/// Offset at which to create a model curve copy
/// of all top face edges for debugging purposes.
/// </summary>
private static readonly XYZ _offset = XYZ.BasisZ / 12;
/// <summary>
/// Translation transformation to apply to create
/// model curve copies of top face edges.
/// </summary>
private static readonly Transform _t =
// Transform.get_Translation( _offset ); // 2013
Transform.CreateTranslation(_offset); // 2014
#endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
var uiapp = commandData.Application;
var uidoc = uiapp.ActiveUIDocument;
var app = uiapp.Application;
var doc = uidoc.Document;
var opt = app.Create.NewGeometryOptions();
var comparer
= new XyzEqualityComparer(1e-6);
#if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
var creator = new Creator(doc);
var t = new Transaction(doc);
t.Start("Create model curve copies of top face edges");
#endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
IList<Face> topFaces = new List<Face>();
int n;
var nWalls = 0;
//foreach( Element e in uidoc.Selection.Elements ) // 2014
foreach (var id in uidoc.Selection.GetElementIds()) // 2015
{
var e = doc.GetElement(id);
var wall = e as Wall;
if (null == wall)
{
Debug.Print($"Skipped {Util.ElementDescription(e)}");
continue;
}
// Get the side faces
var sideFaces
= HostObjectUtils.GetSideFaces(wall,
ShellLayerType.Exterior);
// Access the first side face
var e2 = doc.GetElement(sideFaces[0]);
Debug.Assert(e2.Id.Equals(e.Id),
"expected side face element to be the wall itself");
var face = e2.GetGeometryObjectFromReference(
sideFaces[0]) as Face;
if (null == face)
{
Debug.Print($"No side face found for {Util.ElementDescription(e)}");
continue;
}
// When there are opening such as doors or
// windows in the wall, we need to find the
// outer loop.
// For one possible approach to extract the
// outermost loop, please refer to
// http://thebuildingcoder.typepad.com/blog/2008/12/2d-polygon-areas-and-outer-loop.html
// Determine the outer loop of the side face
// by finding the polygon with the largest area
XYZ normal;
double area, dist, maxArea = 0;
EdgeArray outerLoop = null;
foreach (EdgeArray ea in face.EdgeLoops)
if (CmdWallProfileArea.GetPolygonPlane(
ea.GetPolygon(), out normal, out dist, out area)
&& Math.Abs(area) > Math.Abs(maxArea))
{
maxArea = area;
outerLoop = ea;
}
n = 0;
#if GET_FACES_FROM_OUTER_LOOP
// With the outermost loop, calculate the top faces
foreach( Edge edge in outerLoop )
{
// For each edge, get the neighbouring
// face and check its normal
for( int i = 0; i < 2; ++i )
{
PlanarFace pf = edge.get_Face( i )
as PlanarFace;
if( null == pf )
{
Debug.Print( "Skipped non-planar face on "
+ Util.ElementDescription( e ) );
continue;
}
if( Util.PointsUpwards( pf.Normal, 0.9 ) )
{
if( topFaces.Contains( pf ) )
{
Debug.Print( "Duplicate face on "
+ Util.ElementDescription( e ) );
}
else
{
topFaces.Add( pf );
++n;
}
}
}
}
#endif // GET_FACES_FROM_OUTER_LOOP
var sideVertices = outerLoop.GetPolygon();
// Go over all the faces of the wall and
// determine which ones fulfill the following
// two criteria: (i) planar face pointing
// upwards, and (ii) neighbour of the side
// face outer loop.
var solid = wall.get_Geometry(opt)
.OfType<Solid>()
.First(sol => null != sol);
foreach (Face f in solid.Faces)
if (IsTopFace(f))
{
var faceVertices
= f.Triangulate().Vertices;
//if( sideVertices.Exists( v
// => faceVertices.Contains<XYZ>( v, comparer ) ) )
//{
// topFaces.Add( f );
// ++n;
//}
foreach (var v in faceVertices)
if (sideVertices.Contains(
v, comparer))
{
topFaces.Add(f);
++n;
#if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
// Display face for debugging purposes
foreach (EdgeArray ea in f.EdgeLoops)
{
var curves
= ea.Cast<Edge>()
.Select(
x => x.AsCurve());
foreach (var curve in curves)
//creator.CreateModelCurve( curve.get_Transformed( _t ) ); // 2013
creator.CreateModelCurve(curve.CreateTransformed(_t)); // 2014
}
#endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
break;
}
}
Debug.Print(string.Format(
"{0} top face{1} found on {2} ({3})",
n, Util.PluralSuffix(n),
Util.ElementDescription(e)),
nWalls++);
}
#if CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
t.Commit();
#endif // CREATE_MODEL_CURVES_FOR_TOP_FACE_EDGES
var s = $"{nWalls} wall{Util.PluralSuffix(nWalls)} successfully processed";
n = topFaces.Count;
TaskDialog.Show("Wall Top Faces",
$"{s} with {n} top face{Util.PluralSuffix(n)}.");
return Result.Succeeded;
}
}
}
// C:\tmp\rac_basic_sample_project_walls.rvt
// C:\Program Files\Autodesk\Revit Architecture 2012\Program\Samples\rac_basic_sample_project.rvt
// C:\a\doc\revit\blog\rvt\two_walls_top_face.rvt
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.Steps;
using Boo.Lang.Compiler.TypeSystem.Builders;
using Boo.Lang.Compiler.TypeSystem.Core;
using Boo.Lang.Compiler.TypeSystem.Internal;
using Boo.Lang.Environments;
namespace Boo.Lang.Compiler.TypeSystem.Services
{
internal class AnonymousCallablesManager
{
private TypeSystemServices _tss;
private IDictionary<CallableSignature, AnonymousCallableType> _cache = new Dictionary<CallableSignature, AnonymousCallableType>();
public AnonymousCallablesManager(TypeSystemServices tss)
{
_tss = tss;
}
protected TypeSystemServices TypeSystemServices
{
get { return _tss; }
}
protected BooCodeBuilder CodeBuilder
{
get { return _tss.CodeBuilder; }
}
public ICallableType GetCallableType(CallableSignature signature)
{
AnonymousCallableType type = GetCachedCallableType(signature);
if (type == null)
{
type = new AnonymousCallableType(TypeSystemServices, signature);
_cache.Add(signature, type);
}
return type;
}
private AnonymousCallableType GetCachedCallableType(CallableSignature signature)
{
AnonymousCallableType result;
_cache.TryGetValue(signature, out result);
return result;
}
public IType GetConcreteCallableType(Node sourceNode, CallableSignature signature)
{
var type = GetCallableType(signature);
var anonymous = type as AnonymousCallableType;
return anonymous != null ? GetConcreteCallableType(sourceNode, anonymous) : type;
}
public IType GetConcreteCallableType(Node sourceNode, AnonymousCallableType anonymousType)
{
return anonymousType.ConcreteType ??
(anonymousType.ConcreteType = CreateConcreteCallableType(sourceNode, anonymousType));
}
private IType CreateConcreteCallableType(Node sourceNode, AnonymousCallableType anonymousType)
{
var module = TypeSystemServices.GetCompilerGeneratedTypesModule();
var name = GenerateCallableTypeNameFrom(sourceNode, module);
ClassDefinition cd = My<CallableTypeBuilder>.Instance.CreateEmptyCallableDefinition(name);
cd.Annotate(AnonymousCallableTypeAnnotation);
cd.Modifiers |= TypeMemberModifiers.Public;
cd.LexicalInfo = sourceNode.LexicalInfo;
cd.Members.Add(CreateInvokeMethod(anonymousType));
Method beginInvoke = CreateBeginInvokeMethod(anonymousType);
cd.Members.Add(beginInvoke);
cd.Members.Add(CreateEndInvokeMethod(anonymousType));
AddGenericTypes(cd);
module.Members.Add(cd);
return (IType)cd.Entity;
}
private void AddGenericTypes(ClassDefinition cd)
{
var collector = new GenericTypeCollector(this.CodeBuilder);
collector.Process(cd);
var counter = cd.GenericParameters.Count;
var innerCollector = new DetectInnerGenerics();
cd.Accept(innerCollector);
foreach (Node node in innerCollector.Values)
{
var param = (IGenericParameter)node.Entity;
var gp = cd.GenericParameters.FirstOrDefault(gpd => gpd.Name.Equals(param.Name));
if (gp == null)
{
gp = CodeBuilder.CreateGenericParameterDeclaration(counter, param.Name);
cd.GenericParameters.Add(gp);
++counter;
}
node.Entity = new InternalGenericParameter(this.TypeSystemServices, gp);
gp["InternalGenericParent"] = (param as InternalGenericParameter).Node;
}
}
private string GenerateCallableTypeNameFrom(Node sourceNode, Module module)
{
var enclosing = (sourceNode.GetAncestor(NodeType.ClassDefinition) ?? sourceNode.GetAncestor(NodeType.InterfaceDefinition) ?? sourceNode.GetAncestor(NodeType.EnumDefinition) ?? sourceNode.GetAncestor(NodeType.Module)) as TypeMember;
string prefix = "";
string postfix = "";
if(enclosing != null)
{
prefix += enclosing.Name;
enclosing = (sourceNode.GetAncestor(NodeType.Method)
?? sourceNode.GetAncestor(NodeType.Property)
?? sourceNode.GetAncestor(NodeType.Event)
?? sourceNode.GetAncestor(NodeType.Field)) as TypeMember;
if(enclosing != null)
{
prefix += "_" + enclosing.Name;
}
prefix += "$";
}
else if (!sourceNode.LexicalInfo.Equals(LexicalInfo.Empty))
{
prefix += Path.GetFileNameWithoutExtension(sourceNode.LexicalInfo.FileName) + "$";
}
if(!sourceNode.LexicalInfo.Equals(LexicalInfo.Empty))
{
postfix = "$" + sourceNode.LexicalInfo.Line + "_" + sourceNode.LexicalInfo.Column + postfix;
}
return "__" + prefix + "callable" + module.Members.Count + postfix + "__";
}
Method CreateBeginInvokeMethod(ICallableType anonymousType)
{
Method method = CodeBuilder.CreateRuntimeMethod("BeginInvoke", TypeSystemServices.Map(typeof(IAsyncResult)),
anonymousType.GetSignature().Parameters, false);
int delta = method.Parameters.Count;
method.Parameters.Add(
CodeBuilder.CreateParameterDeclaration(delta + 1, "callback", TypeSystemServices.Map(typeof(AsyncCallback))));
method.Parameters.Add(
CodeBuilder.CreateParameterDeclaration(delta + 1, "asyncState", TypeSystemServices.ObjectType));
return method;
}
public Method CreateEndInvokeMethod(ICallableType anonymousType)
{
CallableSignature signature = anonymousType.GetSignature();
Method method = CodeBuilder.CreateRuntimeMethod("EndInvoke", signature.ReturnType);
int delta = 1;
foreach (IParameter p in signature.Parameters)
{
if (p.IsByRef)
{
method.Parameters.Add(
CodeBuilder.CreateParameterDeclaration(++delta,
p.Name,
p.Type,
true));
}
}
delta = method.Parameters.Count;
method.Parameters.Add(
CodeBuilder.CreateParameterDeclaration(delta + 1, "result", TypeSystemServices.Map(typeof(IAsyncResult))));
return method;
}
Method CreateInvokeMethod(AnonymousCallableType anonymousType)
{
CallableSignature signature = anonymousType.GetSignature();
return CodeBuilder.CreateRuntimeMethod("Invoke", signature.ReturnType, signature.Parameters, signature.AcceptVarArgs);
}
public static readonly object AnonymousCallableTypeAnnotation = new object();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
internal const bool CheckOperationsRequiresSetHandle = true;
internal ThreadPoolBoundHandle _threadPoolBinding;
internal static string GetPipePath(string serverName, string pipeName)
{
string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
if (string.Equals(normalizedPipePath, @"\\.\pipe\" + AnonymousPipeName, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
}
return normalizedPipePath;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
// Check that this handle is infact a handle to a pipe.
if (Interop.Kernel32.GetFileType(safePipeHandle) != Interop.Kernel32.FileTypes.FILE_TYPE_PIPE)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// If the handle is of async type, bind the handle to the ThreadPool so that we can use
// the async operations (it's needed so that our native callbacks get called).
_threadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle);
}
private void DisposeCore(bool disposing)
{
if (disposing)
{
_threadPoolBinding?.Dispose();
}
}
private unsafe int ReadCore(Span<byte> buffer)
{
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, null, out errorCode);
if (r == -1)
{
// If the other side has broken the connection, set state to Broken and return 0
if (errorCode == Interop.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.Errors.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
r = 0;
}
else
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode, string.Empty);
}
}
_isMessageComplete = (errorCode != Interop.Errors.ERROR_MORE_DATA);
Debug.Assert(r >= 0, "PipeStream's ReadCore is likely broken.");
return r;
}
private ValueTask<int> ReadAsyncCore(Memory<byte> buffer, CancellationToken cancellationToken)
{
var completionSource = new ReadWriteCompletionSource(this, buffer, isWrite: false);
// Queue an async ReadFile operation and pass in a packed overlapped
int errorCode = 0;
int r;
unsafe
{
r = ReadFileNative(_handle, buffer.Span, completionSource.Overlapped, out errorCode);
}
// ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper
// returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer read back from this call
// when using overlapped structures! You must not pass in a non-null lpNumBytesRead to
// ReadFile when using overlapped structures! This is by design NT behavior.
if (r == -1)
{
switch (errorCode)
{
// One side has closed its handle or server disconnected.
// Set the state to Broken and do some cleanup work
case Interop.Errors.ERROR_BROKEN_PIPE:
case Interop.Errors.ERROR_PIPE_NOT_CONNECTED:
State = PipeState.Broken;
unsafe
{
// Clear the overlapped status bit for this special case. Failure to do so looks
// like we are freeing a pending overlapped.
completionSource.Overlapped->InternalLow = IntPtr.Zero;
}
completionSource.ReleaseResources();
UpdateMessageCompletion(true);
return new ValueTask<int>(0);
case Interop.Errors.ERROR_IO_PENDING:
break;
default:
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
completionSource.RegisterForCancellation(cancellationToken);
return new ValueTask<int>(completionSource.Task);
}
private unsafe void WriteCore(ReadOnlySpan<byte> buffer)
{
int errorCode = 0;
int r = WriteFileNative(_handle, buffer, null, out errorCode);
if (r == -1)
{
throw WinIOError(errorCode);
}
Debug.Assert(r >= 0, "PipeStream's WriteCore is likely broken.");
}
private Task WriteAsyncCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
var completionSource = new ReadWriteCompletionSource(this, buffer, isWrite: true);
int errorCode = 0;
// Queue an async WriteFile operation and pass in a packed overlapped
int r;
unsafe
{
r = WriteFileNative(_handle, buffer.Span, completionSource.Overlapped, out errorCode);
}
// WriteFile, the OS version, will return 0 on failure, but this WriteFileNative
// wrapper returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer written back from this
// call when using overlapped structures! You must not pass in a non-null
// lpNumBytesWritten to WriteFile when using overlapped structures! This is by design
// NT behavior.
if (r == -1 && errorCode != Interop.Errors.ERROR_IO_PENDING)
{
completionSource.ReleaseResources();
throw WinIOError(errorCode);
}
completionSource.RegisterForCancellation(cancellationToken);
return completionSource.Task;
}
// Blocks until the other end of the pipe has read in all written buffer.
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
// Block until other end of the pipe has read everything.
if (!Interop.Kernel32.FlushFileBuffers(_handle))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public unsafe virtual PipeTransmissionMode TransmissionMode
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (_isFromExistingHandle)
{
uint pipeFlags;
if (!Interop.Kernel32.GetNamedPipeInfo(_handle, &pipeFlags, null, null, null))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
if ((pipeFlags & Interop.Kernel32.PipeOptions.PIPE_TYPE_MESSAGE) != 0)
{
return PipeTransmissionMode.Message;
}
else
{
return PipeTransmissionMode.Byte;
}
}
else
{
return _transmissionMode;
}
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public unsafe virtual int InBufferSize
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
uint inBufferSize;
if (!Interop.Kernel32.GetNamedPipeInfo(_handle, null, null, &inBufferSize, null))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
return (int)inBufferSize;
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public unsafe virtual int OutBufferSize
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
uint outBufferSize;
// Use cached value if direction is out; otherwise get fresh version
if (_pipeDirection == PipeDirection.Out)
{
outBufferSize = _outBufferSize;
}
else if (!Interop.Kernel32.GetNamedPipeInfo(_handle, null, &outBufferSize, null, null))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
return (int)outBufferSize;
}
}
public virtual PipeTransmissionMode ReadMode
{
get
{
CheckPipePropertyOperations();
// get fresh value if it could be stale
if (_isFromExistingHandle || IsHandleExposed)
{
UpdateReadMode();
}
return _readMode;
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
// Nothing fancy here. This is just a wrapper around the Win32 API. Note, that NamedPipeServerStream
// and the AnonymousPipeStreams override this.
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
unsafe
{
int pipeReadType = (int)value << 1;
if (!Interop.Kernel32.SetNamedPipeHandleState(_handle, &pipeReadType, IntPtr.Zero, IntPtr.Zero))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
else
{
_readMode = value;
}
}
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private unsafe int ReadFileNative(SafePipeHandle handle, Span<byte> buffer, NativeOverlapped* overlapped, out int errorCode)
{
DebugAssertHandleValid(handle);
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative.");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int r = 0;
int numBytesRead = 0;
fixed (byte* p = &MemoryMarshal.GetReference(buffer))
{
r = _isAsync ?
Interop.Kernel32.ReadFile(handle, p, buffer.Length, IntPtr.Zero, overlapped) :
Interop.Kernel32.ReadFile(handle, p, buffer.Length, out numBytesRead, IntPtr.Zero);
}
if (r == 0)
{
// In message mode, the ReadFile can inform us that there is more data to come.
errorCode = Marshal.GetLastWin32Error();
return errorCode == Interop.Errors.ERROR_MORE_DATA ?
numBytesRead :
-1;
}
else
{
errorCode = 0;
return numBytesRead;
}
}
private unsafe int WriteFileNative(SafePipeHandle handle, ReadOnlySpan<byte> buffer, NativeOverlapped* overlapped, out int errorCode)
{
DebugAssertHandleValid(handle);
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative.");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int r = 0;
int numBytesWritten = 0;
fixed (byte* p = &MemoryMarshal.GetReference(buffer))
{
r = _isAsync ?
Interop.Kernel32.WriteFile(handle, p, buffer.Length, IntPtr.Zero, overlapped) :
Interop.Kernel32.WriteFile(handle, p, buffer.Length, out numBytesWritten, IntPtr.Zero);
}
if (r == 0)
{
errorCode = Marshal.GetLastWin32Error();
return -1;
}
else
{
errorCode = 0;
return numBytesWritten;
}
}
internal static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability)
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES();
secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES);
secAttrs.bInheritHandle = Interop.BOOL.TRUE;
}
return secAttrs;
}
internal static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability, PipeSecurity pipeSecurity, ref GCHandle pinningHandle)
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES);
secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
secAttrs.bInheritHandle = Interop.BOOL.TRUE;
}
if (pipeSecurity != null)
{
byte[] securityDescriptor = pipeSecurity.GetSecurityDescriptorBinaryForm();
pinningHandle = GCHandle.Alloc(securityDescriptor, GCHandleType.Pinned);
fixed (byte* pSecurityDescriptor = securityDescriptor)
{
secAttrs.lpSecurityDescriptor = (IntPtr)pSecurityDescriptor;
}
}
return secAttrs;
}
/// <summary>
/// Determine pipe read mode from Win32
/// </summary>
private unsafe void UpdateReadMode()
{
uint flags;
if (!Interop.Kernel32.GetNamedPipeHandleStateW(SafePipeHandle, &flags, null, null, null, null, 0))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
if ((flags & Interop.Kernel32.PipeOptions.PIPE_READMODE_MESSAGE) != 0)
{
_readMode = PipeTransmissionMode.Message;
}
else
{
_readMode = PipeTransmissionMode.Byte;
}
}
/// <summary>
/// Filter out all pipe related errors and do some cleanup before calling Error.WinIOError.
/// </summary>
/// <param name="errorCode"></param>
internal Exception WinIOError(int errorCode)
{
switch (errorCode)
{
case Interop.Errors.ERROR_BROKEN_PIPE:
case Interop.Errors.ERROR_PIPE_NOT_CONNECTED:
case Interop.Errors.ERROR_NO_DATA:
// Other side has broken the connection
_state = PipeState.Broken;
return new IOException(SR.IO_PipeBroken, Win32Marshal.MakeHRFromErrorCode(errorCode));
case Interop.Errors.ERROR_HANDLE_EOF:
return Error.GetEndOfFile();
case Interop.Errors.ERROR_INVALID_HANDLE:
// For invalid handles, detect the error and mark our handle
// as invalid to give slightly better error messages. Also
// help ensure we avoid handle recycling bugs.
_handle.SetHandleAsInvalid();
_state = PipeState.Broken;
break;
}
return Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
}
| |
using System;
using System.Collections.Generic;
using ModestTree;
#if !NOT_UNITY3D
using UnityEngine;
#endif
namespace Zenject
{
[NoReflectionBaking]
public class FactoryFromBinderBase : ScopeConcreteIdArgConditionCopyNonLazyBinder
{
public FactoryFromBinderBase(
DiContainer bindContainer, Type contractType, BindInfo bindInfo, FactoryBindInfo factoryBindInfo)
: base(bindInfo)
{
FactoryBindInfo = factoryBindInfo;
BindContainer = bindContainer;
ContractType = contractType;
factoryBindInfo.ProviderFunc =
(container) => new TransientProvider(
ContractType, container, BindInfo.Arguments, BindInfo.ContextInfo, BindInfo.ConcreteIdentifier,
BindInfo.InstantiatedCallback);
}
// Don't use this
internal DiContainer BindContainer
{
get; private set;
}
protected FactoryBindInfo FactoryBindInfo
{
get; private set;
}
// Don't use this
internal Func<DiContainer, IProvider> ProviderFunc
{
get { return FactoryBindInfo.ProviderFunc; }
set { FactoryBindInfo.ProviderFunc = value; }
}
protected Type ContractType
{
get; private set;
}
public IEnumerable<Type> AllParentTypes
{
get
{
yield return ContractType;
foreach (var type in BindInfo.ToTypes)
{
yield return type;
}
}
}
// Note that this isn't necessary to call since it's the default
public ConditionCopyNonLazyBinder FromNew()
{
BindingUtil.AssertIsNotComponent(ContractType);
BindingUtil.AssertIsNotAbstract(ContractType);
return this;
}
public ConditionCopyNonLazyBinder FromResolve()
{
return FromResolve(null);
}
public ConditionCopyNonLazyBinder FromInstance(object instance)
{
BindingUtil.AssertInstanceDerivesFromOrEqual(instance, AllParentTypes);
ProviderFunc =
(container) => new InstanceProvider(ContractType, instance, container, null);
return this;
}
public ConditionCopyNonLazyBinder FromResolve(object subIdentifier)
{
ProviderFunc =
(container) => new ResolveProvider(
ContractType, container,
subIdentifier, false, InjectSources.Any, false);
return this;
}
// Don't use this
internal ConcreteBinderGeneric<T> CreateIFactoryBinder<T>(out Guid factoryId)
{
// Use a random ID so that our provider is the only one that can find it and so it doesn't
// conflict with anything else
factoryId = Guid.NewGuid();
// Very important here that we use NoFlush otherwise the main binding will be finalized early
return BindContainer.BindNoFlush<T>().WithId(factoryId);
}
#if !NOT_UNITY3D
public ConditionCopyNonLazyBinder FromComponentOn(GameObject gameObject)
{
BindingUtil.AssertIsValidGameObject(gameObject);
BindingUtil.AssertIsComponent(ContractType);
BindingUtil.AssertIsNotAbstract(ContractType);
ProviderFunc =
(container) => new GetFromGameObjectComponentProvider(
ContractType, gameObject, true);
return this;
}
public ConditionCopyNonLazyBinder FromComponentOn(Func<InjectContext, GameObject> gameObjectGetter)
{
BindingUtil.AssertIsComponent(ContractType);
BindingUtil.AssertIsNotAbstract(ContractType);
ProviderFunc =
(container) => new GetFromGameObjectGetterComponentProvider(
ContractType, gameObjectGetter, true);
return this;
}
public ConditionCopyNonLazyBinder FromComponentOnRoot()
{
return FromComponentOn(
ctx => BindContainer.Resolve<Context>().gameObject);
}
public ConditionCopyNonLazyBinder FromNewComponentOn(GameObject gameObject)
{
BindingUtil.AssertIsValidGameObject(gameObject);
BindingUtil.AssertIsComponent(ContractType);
BindingUtil.AssertIsNotAbstract(ContractType);
ProviderFunc =
(container) => new AddToExistingGameObjectComponentProvider(
gameObject, container, ContractType,
BindInfo.Arguments, BindInfo.ConcreteIdentifier, BindInfo.InstantiatedCallback);
return this;
}
public ConditionCopyNonLazyBinder FromNewComponentOn(
Func<InjectContext, GameObject> gameObjectGetter)
{
BindingUtil.AssertIsComponent(ContractType);
BindingUtil.AssertIsNotAbstract(ContractType);
ProviderFunc =
(container) => new AddToExistingGameObjectComponentProviderGetter(
gameObjectGetter, container, ContractType,
BindInfo.Arguments, BindInfo.ConcreteIdentifier, BindInfo.InstantiatedCallback);
return this;
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder FromNewComponentOnNewGameObject()
{
BindingUtil.AssertIsComponent(ContractType);
BindingUtil.AssertIsNotAbstract(ContractType);
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new AddToNewGameObjectComponentProvider(
container, ContractType,
BindInfo.Arguments, gameObjectInfo, BindInfo.ConcreteIdentifier, BindInfo.InstantiatedCallback);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder FromNewComponentOnNewPrefab(UnityEngine.Object prefab)
{
BindingUtil.AssertIsValidPrefab(prefab);
BindingUtil.AssertIsComponent(ContractType);
BindingUtil.AssertIsNotAbstract(ContractType);
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new InstantiateOnPrefabComponentProvider(
ContractType,
new PrefabInstantiator(
container, gameObjectInfo,
ContractType, new [] { ContractType }, BindInfo.Arguments,
new PrefabProvider(prefab), BindInfo.InstantiatedCallback));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentInNewPrefab(UnityEngine.Object prefab)
{
BindingUtil.AssertIsValidPrefab(prefab);
BindingUtil.AssertIsInterfaceOrComponent(ContractType);
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new GetFromPrefabComponentProvider(
ContractType,
new PrefabInstantiator(
container, gameObjectInfo,
ContractType, new [] { ContractType }, BindInfo.Arguments,
new PrefabProvider(prefab),
BindInfo.InstantiatedCallback), true);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentInNewPrefabResource(string resourcePath)
{
BindingUtil.AssertIsValidResourcePath(resourcePath);
BindingUtil.AssertIsInterfaceOrComponent(ContractType);
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new GetFromPrefabComponentProvider(
ContractType,
new PrefabInstantiator(
container, gameObjectInfo,
ContractType, new [] { ContractType }, BindInfo.Arguments,
new PrefabProviderResource(resourcePath), BindInfo.InstantiatedCallback), true);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder FromNewComponentOnNewPrefabResource(string resourcePath)
{
BindingUtil.AssertIsValidResourcePath(resourcePath);
BindingUtil.AssertIsComponent(ContractType);
BindingUtil.AssertIsNotAbstract(ContractType);
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new InstantiateOnPrefabComponentProvider(
ContractType,
new PrefabInstantiator(
container, gameObjectInfo,
ContractType, new [] { ContractType }, BindInfo.Arguments,
new PrefabProviderResource(resourcePath),
BindInfo.InstantiatedCallback));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public ConditionCopyNonLazyBinder FromNewScriptableObjectResource(string resourcePath)
{
BindingUtil.AssertIsValidResourcePath(resourcePath);
BindingUtil.AssertIsInterfaceOrScriptableObject(ContractType);
ProviderFunc =
(container) => new ScriptableObjectResourceProvider(
resourcePath, ContractType, container, BindInfo.Arguments,
true, null, BindInfo.InstantiatedCallback);
return this;
}
public ConditionCopyNonLazyBinder FromScriptableObjectResource(string resourcePath)
{
BindingUtil.AssertIsValidResourcePath(resourcePath);
BindingUtil.AssertIsInterfaceOrScriptableObject(ContractType);
ProviderFunc =
(container) => new ScriptableObjectResourceProvider(
resourcePath, ContractType, container, BindInfo.Arguments,
false, null, BindInfo.InstantiatedCallback);
return this;
}
public ConditionCopyNonLazyBinder FromResource(string resourcePath)
{
BindingUtil.AssertDerivesFromUnityObject(ContractType);
ProviderFunc =
(container) => new ResourceProvider(resourcePath, ContractType, true);
return this;
}
#endif
}
}
| |
using System;
using System.Drawing;
#if XAMCORE_2_0
using UIKit;
using Foundation;
using CoreGraphics;
#else
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using MonoTouch.CoreGraphics;
#endif
#if !XAMCORE_2_0
using nint = global::System.Int32;
using nuint = global::System.UInt32;
using nfloat = global::System.Single;
using CGSize = global::System.Drawing.SizeF;
using CGPoint = global::System.Drawing.PointF;
using CGRect = global::System.Drawing.RectangleF;
#endif
namespace MonoTouch.Dialog {
public partial class MessageSummaryView : UIView {
static UIFont SenderFont = UIFont.BoldSystemFontOfSize (19);
static UIFont SubjectFont = UIFont.SystemFontOfSize (14);
static UIFont TextFont = UIFont.SystemFontOfSize (13);
static UIFont CountFont = UIFont.BoldSystemFontOfSize (13);
public string Sender { get; private set; }
public string Body { get; private set; }
public string Subject { get; private set; }
public DateTime Date { get; private set; }
public bool NewFlag { get; private set; }
public int MessageCount { get; private set; }
static CGGradient gradient;
static MessageSummaryView ()
{
using (var colorspace = CGColorSpace.CreateDeviceRGB ()){
gradient = new CGGradient (colorspace, new nfloat [] { /* first */ .52f, .69f, .96f, 1, /* second */ .12f, .31f, .67f, 1 }, null); //new float [] { 0, 1 });
}
}
public MessageSummaryView ()
{
BackgroundColor = UIColor.White;
}
public void Update (string sender, string body, string subject, DateTime date, bool newFlag, int messageCount)
{
Sender = sender;
Body = body;
Subject = subject;
Date = date;
NewFlag = newFlag;
MessageCount = messageCount;
SetNeedsDisplay ();
}
public override void Draw (CGRect rect)
{
const int padright = 21;
var ctx = UIGraphics.GetCurrentContext ();
nfloat boxWidth;
CGSize ssize;
if (MessageCount > 0){
var ms = MessageCount.ToString ();
ssize = ms.StringSize (CountFont);
boxWidth = (nfloat)Math.Min (22 + ssize.Width, 18);
var crect = new CGRect (Bounds.Width-20-boxWidth, 32, boxWidth, 16);
UIColor.Gray.SetFill ();
GraphicsUtil.FillRoundedRect (ctx, crect, 3);
UIColor.White.SetColor ();
crect.X += 5;
ms.DrawString (crect, CountFont);
boxWidth += padright;
} else
boxWidth = 0;
UIColor.FromRGB (36, 112, 216).SetColor ();
var diff = DateTime.Now - Date;
var now = DateTime.Now;
string label;
if (now.Day == Date.Day && now.Month == Date.Month && now.Year == Date.Year)
label = Date.ToShortTimeString ();
else if (diff <= TimeSpan.FromHours (24))
label = "Yesterday".GetText ();
else if (diff < TimeSpan.FromDays (6))
label = Date.ToString ("dddd");
else
label = Date.ToShortDateString ();
ssize = label.StringSize (SubjectFont);
nfloat dateSize = ssize.Width + padright + 5;
label.DrawString (new CGRect (Bounds.Width-dateSize, 6, dateSize, 14), SubjectFont, UILineBreakMode.Clip, UITextAlignment.Left);
const int offset = 33;
nfloat bw = Bounds.Width-offset;
UIColor.Black.SetColor ();
Sender.DrawString (new CGPoint (offset, 2), (float)(bw-dateSize), SenderFont, UILineBreakMode.TailTruncation);
Subject.DrawString (new CGPoint (offset, 23), (float)(bw-offset-boxWidth), SubjectFont, UILineBreakMode.TailTruncation);
//UIColor.Black.SetFill ();
//ctx.FillRect (new CGRect (offset, 40, bw-boxWidth, 34));
UIColor.Gray.SetColor ();
Body.DrawString (new CGRect (offset, 40, bw-boxWidth, 34), TextFont, UILineBreakMode.TailTruncation, UITextAlignment.Left);
if (NewFlag){
ctx.SaveState ();
ctx.AddEllipseInRect (new CGRect (10, 32, 12, 12));
ctx.Clip ();
ctx.DrawLinearGradient (gradient, new CGPoint (10, 32), new CGPoint (22, 44), CGGradientDrawingOptions.DrawsAfterEndLocation);
ctx.RestoreState ();
}
#if WANT_SHADOWS
ctx.SaveState ();
UIColor.FromRGB (78, 122, 198).SetStroke ();
ctx.SetShadow (new CGSize (1, 1), 3);
ctx.StrokeEllipseInRect (new CGRect (10, 32, 12, 12));
ctx.RestoreState ();
#endif
}
}
public class MessageElement : Element, IElementSizing {
static NSString mKey = new NSString ("MessageElement");
public string Sender, Body, Subject;
public DateTime Date;
public bool NewFlag;
public int MessageCount;
class MessageCell : UITableViewCell {
MessageSummaryView view;
public MessageCell () : base (UITableViewCellStyle.Default, mKey)
{
view = new MessageSummaryView ();
ContentView.Add (view);
Accessory = UITableViewCellAccessory.DisclosureIndicator;
}
public void Update (MessageElement me)
{
view.Update (me.Sender, me.Body, me.Subject, me.Date, me.NewFlag, me.MessageCount);
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
view.Frame = ContentView.Bounds;
view.SetNeedsDisplay ();
}
}
public MessageElement () : base ("")
{
}
public MessageElement (Action<DialogViewController,UITableView,NSIndexPath> tapped) : base ("")
{
Tapped += tapped;
}
public override UITableViewCell GetCell (UITableView tv)
{
var cell = tv.DequeueReusableCell (mKey) as MessageCell;
if (cell == null)
cell = new MessageCell ();
cell.Update (this);
return cell;
}
public nfloat GetHeight (UITableView tableView, NSIndexPath indexPath)
{
return 78;
}
public event Action<DialogViewController, UITableView, NSIndexPath> Tapped;
public override void Selected (DialogViewController dvc, UITableView tableView, NSIndexPath path)
{
if (Tapped != null)
Tapped (dvc, tableView, path);
}
public override bool Matches (string text)
{
if (Sender != null && Sender.IndexOf (text, StringComparison.CurrentCultureIgnoreCase) != -1)
return true;
if (Body != null && Body.IndexOf (text, StringComparison.CurrentCultureIgnoreCase) != -1)
return true;
if (Subject != null && Subject.IndexOf (text, StringComparison.CurrentCultureIgnoreCase) != -1)
return true;
return false;
}
}
}
| |
//
// CFRunLoop.cs: Main Loop
//
// Authors:
// Miguel de Icaza ([email protected])
// Martin Baulig ([email protected])
//
// Copyright 2011, 2012 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 System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
namespace MonoMac.CoreFoundation {
public enum CFRunLoopExitReason {
Finished = 1,
Stopped = 2,
TimedOut = 3,
HandledSource = 4
}
[StructLayout (LayoutKind.Sequential)]
internal struct CFRunLoopSourceContext {
public CFIndex Version;
public IntPtr Info;
public IntPtr Retain;
public IntPtr Release;
public IntPtr CopyDescription;
public IntPtr Equal;
public IntPtr Hash;
public IntPtr Schedule;
public IntPtr Cancel;
public IntPtr Perform;
}
public class CFRunLoopSource : INativeObject, IDisposable {
internal IntPtr handle;
internal CFRunLoopSource (IntPtr handle)
: this (handle, false)
{
}
internal CFRunLoopSource (IntPtr handle, bool ownsHandle)
{
if (!ownsHandle)
CFObject.CFRetain (handle);
this.handle = handle;
}
~CFRunLoopSource ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static CFIndex CFRunLoopSourceGetOrder (IntPtr source);
public int Order {
get {
return CFRunLoopSourceGetOrder (handle);
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopSourceInvalidate (IntPtr source);
public void Invalidate ()
{
CFRunLoopSourceInvalidate (handle);
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static int CFRunLoopSourceIsValid (IntPtr source);
public bool IsValid {
get {
return CFRunLoopSourceIsValid (handle) != 0;
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopSourceSignal (IntPtr source);
public void Signal ()
{
CFRunLoopSourceSignal (handle);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero) {
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
}
public abstract class CFRunLoopSourceCustom : CFRunLoopSource {
GCHandle gch;
[DllImport (Constants.CoreFoundationLibrary)]
extern static IntPtr CFRunLoopSourceCreate (IntPtr allocator, int order, IntPtr context);
protected CFRunLoopSourceCustom ()
: base (IntPtr.Zero, true)
{
gch = GCHandle.Alloc (this);
var ctx = new CFRunLoopSourceContext ();
ctx.Info = GCHandle.ToIntPtr (gch);
ctx.Schedule = Marshal.GetFunctionPointerForDelegate ((ScheduleCallback)Schedule);
ctx.Cancel = Marshal.GetFunctionPointerForDelegate ((CancelCallback)Cancel);
ctx.Perform = Marshal.GetFunctionPointerForDelegate ((PerformCallback)Perform);
var ptr = Marshal.AllocHGlobal (Marshal.SizeOf (typeof(CFRunLoopSourceContext)));
try {
Marshal.StructureToPtr (ctx, ptr, false);
handle = CFRunLoopSourceCreate (IntPtr.Zero, 0, ptr);
} finally {
Marshal.FreeHGlobal (ptr);
}
if (handle == IntPtr.Zero)
throw new NotSupportedException ();
}
delegate void ScheduleCallback (IntPtr info, IntPtr runLoop, IntPtr mode);
[MonoPInvokeCallback (typeof(ScheduleCallback))]
static void Schedule (IntPtr info, IntPtr runLoop, IntPtr mode)
{
var source = GCHandle.FromIntPtr (info).Target as CFRunLoopSourceCustom;
var loop = new CFRunLoop (runLoop);
var mstring = new CFString (mode);
try {
source.OnSchedule (loop, (string)mstring);
} finally {
loop.Dispose ();
mstring.Dispose ();
}
}
protected abstract void OnSchedule (CFRunLoop loop, string mode);
delegate void CancelCallback (IntPtr info, IntPtr runLoop, IntPtr mode);
[MonoPInvokeCallback (typeof(CancelCallback))]
static void Cancel (IntPtr info, IntPtr runLoop, IntPtr mode)
{
var source = GCHandle.FromIntPtr (info).Target as CFRunLoopSourceCustom;
var loop = new CFRunLoop (runLoop);
var mstring = new CFString (mode);
try {
source.OnCancel (loop, (string)mstring);
} finally {
loop.Dispose ();
mstring.Dispose ();
}
}
protected abstract void OnCancel (CFRunLoop loop, string mode);
delegate void PerformCallback (IntPtr info);
[MonoPInvokeCallback (typeof(PerformCallback))]
static void Perform (IntPtr info)
{
var source = GCHandle.FromIntPtr (info).Target as CFRunLoopSourceCustom;
source.OnPerform ();
}
protected abstract void OnPerform ();
public override void Dispose (bool disposing)
{
if (disposing) {
if (gch.IsAllocated)
gch.Free ();
}
base.Dispose (disposing);
}
}
public class CFRunLoop : INativeObject, IDisposable {
static IntPtr CoreFoundationLibraryHandle = Dlfcn.dlopen (Constants.CoreFoundationLibrary, 0);
internal IntPtr handle;
static NSString _CFDefaultRunLoopMode;
public static NSString CFDefaultRunLoopMode {
get {
if (_CFDefaultRunLoopMode == null)
_CFDefaultRunLoopMode = Dlfcn.GetStringConstant (CoreFoundationLibraryHandle, ModeDefault);
return _CFDefaultRunLoopMode;
}
}
static NSString _CFRunLoopCommonModes;
public static NSString CFRunLoopCommonModes {
get {
if (_CFRunLoopCommonModes == null)
_CFRunLoopCommonModes = Dlfcn.GetStringConstant (CoreFoundationLibraryHandle, ModeCommon);
return _CFRunLoopCommonModes;
}
}
// Note: This is a broken binding... we do not know what the values of the constant strings are, just their variable names and things are done by comparing CFString pointers, not a string compare anyway.
public const string ModeDefault = "kCFRunLoopDefaultMode";
public const string ModeCommon = "kCFRunLoopCommonModes";
[DllImport (Constants.CoreFoundationLibrary)]
extern static IntPtr CFRunLoopGetCurrent ();
static public CFRunLoop Current {
get {
return new CFRunLoop (CFRunLoopGetCurrent ());
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static IntPtr CFRunLoopGetMain ();
static public CFRunLoop Main {
get {
return new CFRunLoop (CFRunLoopGetMain ());
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopRun ();
public void Run ()
{
CFRunLoopRun ();
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopStop (IntPtr loop);
public void Stop ()
{
CFRunLoopStop (handle);
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopWakeUp (IntPtr loop);
public void WakeUp ()
{
CFRunLoopWakeUp (handle);
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static int CFRunLoopIsWaiting (IntPtr loop);
public bool IsWaiting {
get {
return CFRunLoopIsWaiting (handle) != 0;
}
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static int CFRunLoopRunInMode (IntPtr mode, double seconds, int returnAfterSourceHandled);
public CFRunLoopExitReason RunInMode (NSString mode, double seconds, bool returnAfterSourceHandled)
{
if (mode == null)
throw new ArgumentNullException ("mode");
return (CFRunLoopExitReason) CFRunLoopRunInMode (mode.Handle, seconds, returnAfterSourceHandled ? 1 : 0);
}
[Obsolete ("Use the NSString version of CFRunLoop.RunInMode() instead.")]
public CFRunLoopExitReason RunInMode (string mode, double seconds, bool returnAfterSourceHandled)
{
if (mode == null)
throw new ArgumentNullException ("mode");
CFString s = new CFString (mode);
var v = CFRunLoopRunInMode (s.Handle, seconds, returnAfterSourceHandled ? 1 : 0);
s.Dispose ();
return (CFRunLoopExitReason) v;
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static void CFRunLoopAddSource (IntPtr loop, IntPtr source, IntPtr mode);
public void AddSource (CFRunLoopSource source, NSString mode)
{
if (mode == null)
throw new ArgumentNullException ("mode");
CFRunLoopAddSource (handle, source.Handle, mode.Handle);
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static bool CFRunLoopContainsSource (IntPtr loop, IntPtr source, IntPtr mode);
public bool ContainsSource (CFRunLoopSource source, NSString mode)
{
if (mode == null)
throw new ArgumentNullException ("mode");
return CFRunLoopContainsSource (handle, source.Handle, mode.Handle);
}
[DllImport (Constants.CoreFoundationLibrary)]
extern static bool CFRunLoopRemoveSource (IntPtr loop, IntPtr source, IntPtr mode);
public bool RemoveSource (CFRunLoopSource source, NSString mode)
{
if (mode == null)
throw new ArgumentNullException ("mode");
return CFRunLoopRemoveSource (handle, source.Handle, mode.Handle);
}
internal CFRunLoop (IntPtr handle)
: this (handle, false)
{
}
[Preserve (Conditional = true)]
internal CFRunLoop (IntPtr handle, bool owns)
{
if (!owns)
CFObject.CFRetain (handle);
this.handle = handle;
}
~CFRunLoop ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
public static bool operator == (CFRunLoop a, CFRunLoop b)
{
return Object.Equals (a, b);
}
public static bool operator != (CFRunLoop a, CFRunLoop b)
{
return !Object.Equals (a, b);
}
public override int GetHashCode ()
{
return handle.GetHashCode ();
}
public override bool Equals (object other)
{
CFRunLoop cfother = other as CFRunLoop;
if (cfother == null)
return false;
return cfother.Handle == Handle;
}
}
}
| |
// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Annotations;
using NodaTime.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
namespace NodaTime.TimeZones
{
/// <summary>
/// Equality comparer for time zones, comparing specific aspects of the zone intervals within
/// a time zone for a specific interval of the time line.
/// </summary>
/// <remarks>
/// The default behaviour of this comparator is to consider two time zones to be equal if they share the same wall
/// offsets at all points within a given time interval, regardless of other aspects of each
/// <see cref="ZoneInterval"/> within the two time zones. This behaviour can be changed using the
/// <see cref="WithOptions"/> method.
/// </remarks>
[Immutable]
public sealed class ZoneEqualityComparer : IEqualityComparer<DateTimeZone?>
{
/// <summary>
/// Options to use when comparing time zones for equality. Each option makes the comparison more restrictive.
/// </summary>
/// <remarks>
/// <para>
/// By default, the comparer only compares the wall offset (total of standard offset and any daylight saving offset)
/// at every instant within the interval over which the comparer operates. In practice, this is done by comparing each
/// <see cref="ZoneInterval"/> which includes an instant within the interval (using <see cref="DateTimeZone.GetZoneIntervals(Interval)"/>).
/// For most purposes, this is all that's required: from the simple perspective of a time zone being just a function from instants to local time,
/// the default option of <see cref="OnlyMatchWallOffset"/> effectively checks that the function gives the same result across the two time
/// zones being compared, for any given instant within the interval.
/// </para>
/// <para>
/// It's possible for a time zone to have a transition from one <c>ZoneInterval</c> to another which doesn't adjust the offset: it
/// might just change the name, or the balance between standard offset to daylight saving offset. (As an example, at midnight local
/// time on October 27th 1968, the Europe/London time zone went from a standard offset of 0 and a daylight saving offset of 1 hour
/// to a standard offset of 1 and a daylight saving offset of 0... which left the clocks unchanged.) This transition is irrelevant
/// to the default options, so the two zone intervals involved are effectively coalesced.
/// </para>
/// <para>
/// The options available change what sort of comparison is performed - which can also change which zone intervals can be coalesced. For
/// example, by specifying just the <see cref="MatchAllTransitions"/> option, you would indicate that even though you don't care about the name within a zone
/// interval or how the wall offset is calculated, you do care about the fact that there was a transition at all, and when it occurred.
/// With that option enabled, zone intervals are never coalesced and the transition points within the operating interval are checked.
/// </para>
/// <para>Similarly, the <see cref="MatchStartAndEndTransitions"/> option is the only one where instants outside the operating interval are
/// relevant. For example, consider a comparer which operates over the interval [2000-01-01T00:00:00Z, 2011-01-01T00:00:00Z). Normally,
/// anything that happens before the year 2000 (UTC) would be irrelevant - but with this option enabled, the transitions of the first and last zone
/// intervals are part of the comparison... so if one time zone has a zone interval 1999-09-01T00:00:00Z to 2000-03-01T00:00:00Z and the other has
/// a zone interval 1999-10-15T00:00:00Z to 2000-03-01T00:00:Z, the two zones would be considered unequal, despite the fact that the only instants observing
/// the difference occur outside the operating interval.
/// </para>
/// </remarks>
[Flags]
public enum Options
{
/// <summary>
/// The default comparison, which only cares about the wall offset at any particular
/// instant, within the interval of the comparer. In other words, if <see cref="DateTimeZone.GetUtcOffset"/>
/// returns the same value for all instants in the interval, the comparer will consider the zones to be equal.
/// </summary>
OnlyMatchWallOffset = 0,
/// <summary>
/// Instead of only comparing wall offsets, the standard/savings split is also considered. So when this
/// option is used, two zones which both have a wall offset of +2 at one instant would be considered
/// unequal if one of those offsets was +1 standard, +1 savings and the other was +2 standard with no daylight
/// saving.
/// </summary>
MatchOffsetComponents = 1 << 0,
/// <summary>
/// Compare the names of zone intervals as well as offsets.
/// </summary>
MatchNames = 1 << 1,
/// <summary>
/// This option prevents adjacent zone intervals from being coalesced, even if they are otherwise considered
/// equivalent according to other options.
/// </summary>
MatchAllTransitions = 1 << 2,
/// <summary>
/// Includes the transitions into the first zone interval and out of the
/// last zone interval as part of the comparison, even if they do not affect
/// the offset or name for any instant within the operating interval.
/// </summary>
MatchStartAndEndTransitions = 1 << 3,
/// <summary>
/// The combination of all available match options.
/// </summary>
StrictestMatch = MatchNames | MatchOffsetComponents | MatchAllTransitions | MatchStartAndEndTransitions
}
/// <summary>
/// Checks whether the given set of options includes the candidate one. This would be an extension method, but
/// that causes problems on Mono at the moment.
/// </summary>
private static bool CheckOption(Options options, Options candidate)
{
return (options & candidate) != 0;
}
private readonly Interval interval;
private readonly Options options;
/// <summary>
/// Returns the interval over which this comparer operates.
/// </summary>
[VisibleForTesting]
internal Interval IntervalForTest => interval;
/// <summary>
/// Returns the options used by this comparer.
/// </summary>
[VisibleForTesting]
internal Options OptionsForTest => options;
private readonly ZoneIntervalEqualityComparer zoneIntervalComparer;
/// <summary>
/// Creates a new comparer for the given interval, with the given comparison options.
/// </summary>
/// <param name="interval">The interval within the time line to use for comparisons.</param>
/// <param name="options">The options to use when comparing time zones.</param>
/// <exception cref="ArgumentOutOfRangeException">The specified options are invalid.</exception>
private ZoneEqualityComparer(Interval interval, Options options)
{
this.interval = interval;
this.options = options;
if ((options & ~Options.StrictestMatch) != 0)
{
throw new ArgumentOutOfRangeException(nameof(options), $"The value {options} is not defined within ZoneEqualityComparer.Options");
}
zoneIntervalComparer = new ZoneIntervalEqualityComparer(options, interval);
}
/// <summary>
/// Returns a <see cref="ZoneEqualityComparer"/> for the given interval with the default options.
/// </summary>
/// <remarks>
/// The default behaviour of this comparator is to consider two time zones to be equal if they share the same wall
/// offsets at all points within a given interval.
/// To specify non-default options, call the <see cref="WithOptions"/> method on the result
/// of this method.</remarks>
/// <param name="interval">The interval over which to compare time zones. This must have both a start and an end.</param>
/// <returns>A ZoneEqualityComparer for the given interval with the default options.</returns>
public static ZoneEqualityComparer ForInterval(Interval interval)
{
Preconditions.CheckArgument(interval.HasStart && interval.HasEnd, nameof(interval),
"The interval must have both a start and an end.");
return new ZoneEqualityComparer(interval, Options.OnlyMatchWallOffset);
}
/// <summary>
/// Returns a comparer operating over the same interval as this one, but with the given
/// set of options.
/// </summary>
/// <remarks>
/// This method does not modify the comparer on which it's called.
/// </remarks>
/// <param name="options">New set of options, which must consist of flags defined within the <see cref="Options"/> enum.</param>
/// <exception cref="ArgumentOutOfRangeException">The specified options are invalid.</exception>
/// <returns>A comparer operating over the same interval as this one, but with the given set of options.</returns>
public ZoneEqualityComparer WithOptions(Options options)
{
return this.options == options ? this : new ZoneEqualityComparer(this.interval, options);
}
/// <summary>
/// Compares two time zones for equality according to the options and interval provided to this comparer.
/// </summary>
/// <param name="x">The first <see cref="DateTimeZone"/> to compare.</param>
/// <param name="y">The second <see cref="DateTimeZone"/> to compare.</param>
/// <returns><c>true</c> if the specified time zones are equal under the options and interval of this comparer; otherwise, <c>false</c>.</returns>
public bool Equals(DateTimeZone? x, DateTimeZone? y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null || y is null)
{
return false;
}
// If we ever need to port this to a platform which doesn't support LINQ,
// we'll need to reimplement this. Until then, it would seem pointless...
return GetIntervals(x).SequenceEqual(GetIntervals(y), zoneIntervalComparer);
}
/// <summary>
/// Returns a hash code for the specified time zone.
/// </summary>
/// <remarks>
/// The hash code generated by any instance of <c>ZoneEqualityComparer</c> will be equal to the hash code
/// generated by any other instance constructed with the same options and interval, for the same time zone (or equal ones).
/// Two instances of <c>ZoneEqualityComparer</c> with different options or intervals may (but may not) produce
/// different hash codes for the same zone.
/// </remarks>
/// <param name="obj">The time zone to compute a hash code for.</param>
/// <returns>A hash code for the specified object.</returns>
public int GetHashCode(DateTimeZone? obj)
{
Preconditions.CheckNotNull(obj!, nameof(obj));
unchecked
{
int hash = 19;
foreach (var zoneInterval in GetIntervals(obj!))
{
hash = hash * 31 + zoneIntervalComparer.GetHashCode(zoneInterval);
}
return hash;
}
}
private IEnumerable<ZoneInterval> GetIntervals(DateTimeZone zone)
{
var allIntervals = zone.GetZoneIntervals(interval.Start, interval.End);
return CheckOption(options, Options.MatchAllTransitions) ? allIntervals : zoneIntervalComparer.CoalesceIntervals(allIntervals);
}
internal sealed class ZoneIntervalEqualityComparer : IEqualityComparer<ZoneInterval>
{
private readonly Options options;
private readonly Interval interval;
internal ZoneIntervalEqualityComparer(Options options, Interval interval)
{
this.options = options;
this.interval = interval;
}
internal IEnumerable<ZoneInterval> CoalesceIntervals(IEnumerable<ZoneInterval> zoneIntervals)
{
ZoneInterval? current = null;
foreach (var zoneInterval in zoneIntervals)
{
if (current is null)
{
current = zoneInterval;
continue;
}
if (EqualExceptStartAndEnd(current, zoneInterval))
{
current = current.WithEnd(zoneInterval.RawEnd);
}
else
{
yield return current;
current = zoneInterval;
}
}
// current will only be null if start == end...
if (current != null)
{
yield return current;
}
}
public bool Equals(ZoneInterval x, ZoneInterval y)
{
if (!EqualExceptStartAndEnd(x, y))
{
return false;
}
return GetEffectiveStart(x) == GetEffectiveStart(y) &&
GetEffectiveEnd(x) == GetEffectiveEnd(y);
}
public int GetHashCode(ZoneInterval obj)
{
var hash = HashCodeHelper.Initialize();
if (CheckOption(options, Options.MatchOffsetComponents))
{
hash = hash.Hash(obj.StandardOffset).Hash(obj.Savings);
}
else
{
hash = hash.Hash(obj.WallOffset);
}
if (CheckOption(options, Options.MatchNames))
{
hash = hash.Hash(obj.Name);
}
return hash.Hash(GetEffectiveStart(obj)).Hash(GetEffectiveEnd(obj)).Value;
}
private Instant GetEffectiveStart(ZoneInterval zoneInterval) =>
CheckOption(options, Options.MatchStartAndEndTransitions)
? zoneInterval.RawStart : Instant.Max(zoneInterval.RawStart, interval.Start);
private Instant GetEffectiveEnd(ZoneInterval zoneInterval) =>
CheckOption(options, Options.MatchStartAndEndTransitions)
? zoneInterval.RawEnd : Instant.Min(zoneInterval.RawEnd, interval.End);
/// <summary>
/// Compares the parts of two zone intervals which are deemed "interesting" by the options.
/// The wall offset is always compared, regardless of options, but the start/end points are
/// never compared.
/// </summary>
private bool EqualExceptStartAndEnd(ZoneInterval x, ZoneInterval y)
{
if (x.WallOffset != y.WallOffset)
{
return false;
}
// As we've already compared wall offsets, we only need to compare savings...
// If the savings are equal, the standard offset will be too.
if (CheckOption(options, Options.MatchOffsetComponents) && x.Savings != y.Savings)
{
return false;
}
if (CheckOption(options, Options.MatchNames) && x.Name != y.Name)
{
return false;
}
return true;
}
}
}
}
| |
//
// LuaTransparentClrObject.cs
//
// Authors:
// Chris Howie <[email protected]>
// Tom Roostan <[email protected]>
//
// Copyright (c) 2013 Chris Howie
// Copyright (c) 2015 Tom Roostan
//
// 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 Eluant.ObjectBinding;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
namespace Eluant
{
public class LuaTransparentClrObject : LuaClrObjectValue, IEquatable<LuaTransparentClrObject>, IBindingContext
{
private static readonly IBindingSecurityPolicy defaultSecurityPolicy = new BasicBindingSecurityPolicy(MemberSecurityPolicy.Deny);
public IBindingSecurityPolicy BindingSecurityPolicy { get; private set; }
public ILuaBinder Binder { get; private set; }
private TransparentClrObjectProxy proxy;
public LuaTransparentClrObject(object obj) : this(obj, null, null) { }
public LuaTransparentClrObject(object obj, ILuaBinder binder, IBindingSecurityPolicy bindingSecurityPolicy) : base(obj)
{
Binder = binder ?? BasicLuaBinder.Instance;
BindingSecurityPolicy = bindingSecurityPolicy ?? defaultSecurityPolicy;
proxy = new TransparentClrObjectProxy(this);
}
internal override void Push(LuaRuntime runtime)
{
runtime.PushCustomClrObject(this);
}
public override bool Equals(LuaValue other)
{
return Equals(other as LuaTransparentClrObject);
}
public bool Equals(LuaTransparentClrObject obj)
{
return obj != null && obj.ClrObject == ClrObject;
}
internal override object BackingCustomObject
{
get { return proxy; }
}
internal override MetamethodAttribute[] BackingCustomObjectMetamethods(LuaRuntime runtime)
{
return TransparentClrObjectProxy.Metamethods;
}
private class TransparentClrObjectProxy : ILuaTableBinding, ILuaEqualityBinding
{
public static readonly MetamethodAttribute[] Metamethods = LuaClrObjectValue.Metamethods(typeof(TransparentClrObjectProxy));
private LuaTransparentClrObject clrObject;
public TransparentClrObjectProxy(LuaTransparentClrObject obj)
{
clrObject = obj;
}
private static LuaTransparentClrObject GetObjectValue(LuaValue v)
{
var r = v as LuaClrObjectReference;
if (r != null) {
return r.ClrObjectValue as LuaTransparentClrObject;
}
return null;
}
#region ILuaEqualityBinding implementation
public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right)
{
var leftObj = GetObjectValue(left);
var rightObj = GetObjectValue(right);
if (object.ReferenceEquals(leftObj, rightObj)) {
return true;
}
if (leftObj == null || rightObj == null) {
return false;
}
return leftObj.ClrObject == rightObj.ClrObject &&
leftObj.Binder == rightObj.Binder &&
leftObj.BindingSecurityPolicy == rightObj.BindingSecurityPolicy;
}
#endregion
private static string KeyToString(LuaValue key)
{
var str = key as LuaString;
if (str != null) {
return str.Value;
}
var num = key as LuaNumber;
if (num != null) {
return num.Value.ToString();
}
return null;
}
private List<MemberInfo> GetMembers(LuaValue keyValue)
{
var key = KeyToString(keyValue);
if (key != null) {
return clrObject.Binder.GetMembersByName(clrObject.ClrObject, key)
.Where(i => clrObject.BindingSecurityPolicy.GetMemberSecurityPolicy(i) == MemberSecurityPolicy.Permit)
.ToList();
}
return new List<MemberInfo>();
}
#region ILuaTableBinding implementation
public LuaValue this[LuaRuntime runtime, LuaValue keyValue]
{
get {
var members = GetMembers(keyValue);
if (members.Count == 1) {
var method = members[0] as MethodInfo;
if (method != null) {
return runtime.CreateFunctionFromMethodWrapper(new LuaRuntime.MethodWrapper(clrObject.ClrObject, method));
}
var property = members[0] as PropertyInfo;
if (property != null) {
var getter = property.GetGetMethod();
if (getter == null) {
throw new LuaException("Property is write-only.");
}
if (getter.GetParameters().Length != 0) {
throw new LuaException("Cannot get an indexer.");
}
return clrObject.Binder.ObjectToLuaValue(property.GetValue(clrObject.ClrObject, null), clrObject, runtime);
}
var field = members[0] as FieldInfo;
if (field != null) {
return clrObject.Binder.ObjectToLuaValue(field.GetValue(clrObject.ClrObject), clrObject, runtime);
}
}
return LuaNil.Instance;
}
set {
var members = GetMembers(keyValue);
if (members.Count == 1) {
var property = members[0] as PropertyInfo;
if (property != null) {
var setter = property.GetSetMethod();
if (setter == null) {
throw new LuaException("Property is read-only.");
}
if (setter.GetParameters().Length != 1) {
throw new LuaException("Cannot set an indexer.");
}
object v;
try {
v = value.ToClrType(property.PropertyType);
} catch {
throw new LuaException("Value is incompatible with this property.");
}
property.SetValue(clrObject.ClrObject, v, null);
return;
}
var field = members[0] as FieldInfo;
if (field != null) {
object v;
try {
v = value.ToClrType(field.FieldType);
} catch {
throw new LuaException("Value is incompatible with this property.");
}
field.SetValue(clrObject.ClrObject, v);
return;
}
}
throw new LuaException("Property/field not found: " + keyValue.ToString());
}
}
#endregion
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Threading;
using OpenADK.Library.Infra;
namespace OpenADK.Library.Impl
{
/// <summary> An protocol handler implementation for HTTP. Each zone that is registered
/// with a ZIS using the HTTP or HTTPS protocol has an instance of this class
/// as its protocol handler. It implements the HttpHandler interface to process
/// SIF messages received by the agent's internal Jetty HTTP Server. When a
/// message is received via that interface it is delegated to the zone's
/// MessageDispatcher. HttpProtocolHandler also implements the IProtocolHandler
/// interface so it can send outgoing messages received by the
/// MessageDispatcher.
///
///
/// An instance of this class runs in a separate thread only when the agent is
/// registered with the ZIS in Pull mode. In this case it does not accept
/// messages from the HttpHandler interface but instead periodically queries the
/// ZIS for new messages waiting in the agent's queue. Messages are delegated to
/// the MessageDispatcher for processing.
///
///
/// </summary>
/// <author> Eric Petersen
/// </author>
/// <version> Adk 1.0
/// </version>
internal class HttpPullProtocolHandler : BaseHttpProtocolHandler
{
private Thread fThread;
private bool fRunning;
public HttpPullProtocolHandler( HttpTransport transport ) : base( transport )
{
}
#region overrides of BaseHttpTransportProtocol
/// <summary> Starts the handler's polling thread if running in Pull mode</summary>
public override void Start()
{
lock ( this ) {
if ( this.Zone.Properties.MessagingMode == AgentMessagingMode.Pull ) {
// Polling thread already running?
if ( fThread != null && fThread.ThreadState == ThreadState.Running ) {
this.Zone.Log.Debug
( "Polling thread (HTTP/HTTPS) already running for zone" );
return;
}
if ( (Adk.Debug & AdkDebugFlags.Transport) != 0 ) {
this.Zone.Log.Debug
( "Starting polling thread (HTTP/HTTPS), zone connected in Pull mode..." );
}
// Run in a thread for pull mode operation
fThread = new Thread( new ThreadStart( this.Run ) );
fThread.Name = Name;
fThread.Start();
}
else {
throw new AdkException
( this.GetType().FullName + " is not able to Start in PUSH mode", this.Zone );
}
}
}
/// <summary> Stops the handler's polling thread if running in Pull mode</summary>
public override void Shutdown()
{
lock ( this ) {
if ( fThread != null & fThread.ThreadState == ThreadState.Running ) {
fThread.Interrupt();
}
}
fRunning = false;
}
/// <summary> Close this ProtocolHandler for a zone</summary>
public override void Close( IZone zone )
{
lock ( this ) {
// Stop the polling thread if we were registered in Pull mode
if ( fThread != null ) {
fRunning = false;
fThread.Interrupt();
fThread = null;
}
}
}
#endregion
/// <summary> Thread periodically sends a SIF_GetMessage request to the ZIS to get
/// the next message waiting in the agent queue
/// </summary>
private void Run()
{
fRunning = true;
TimeSpan freq = this.Zone.Properties.PullFrequency;
TimeSpan delay = this.Zone.Properties.PullDelayOnError;
if ( (Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0 ) {
this.Zone.Log.Debug
( "Polling thread (HTTP/HTTPS) started with frequency " + freq.ToString() +
" seconds" );
}
while ( fRunning ) {
try {
if ( this.Zone.IsShutdown ) {
if ( (Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0 ) {
this.Zone.Log.Debug
( "Polling thread (HTTP/HTTPS) will stop, zone has shut down" );
}
break;
}
else if ( !this.Zone.Connected ) {
if ( (Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0 ) {
this.Zone.Log.Debug
( "Polling thread (HTTP/HTTPS) will delay " + delay.Seconds +
" seconds, zone is no longer connected" );
}
Thread.Sleep( delay );
}
else {
int i = this.Zone.Dispatcher.Pull();
if ( i == - 1 ) {
// The zone is sleeping
if ( (Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0 ) {
this.Zone.Log.Debug
( "Polling thread (HTTP/HTTPS) will delay " + delay.Seconds +
" seconds, zone is sleeping" );
}
Thread.Sleep( delay );
}
else {
Thread.Sleep( freq );
}
}
}
catch ( LifecycleException ) {
// Agent was shutdown - exit gracefully
break;
}
catch ( ThreadInterruptedException ) {
if ( (Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0 ) {
this.Zone.Log.Debug( "Polling thread (HTTP/HTTPS) interrupted" );
}
break;
}
catch ( Exception adke ) {
if ( (Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0 ) {
this.Zone.Log.Debug
( "Polling thread (HTTP/HTTPS) failed to retrieve message: " + adke );
}
//
// Special Check: If registered in Push mode and we're still
// pulling, stop the thread - there is no sense in continuing.
// This should not happen, but just in case...
//
if ( adke is AdkException &&
((AdkException) adke).HasSifError
( SifErrorCategoryCode.Registration, SifErrorCodes.REG_PUSH_EXPECTED_9 )
) {
if ( (Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0 ) {
this.Zone.Log.Debug
( "Polling thread (HTTP/HTTPS) will now stop because agent is registered in Push mode" );
}
break;
}
try {
// Sleep for the regular frequency before pulling next message
Thread.Sleep( freq );
}
catch ( ThreadInterruptedException ) {
// App is shutting down
break;
}
}
}
fRunning = false;
if ( (Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0 ) {
this.Zone.Log.Debug( "Polling thread (HTTP/HTTPS) has ended" );
}
}
/// <summary>
/// Returns true if the protocol and underlying transport are currently active
/// for this zone
/// </summary>
/// <param name="zone"></param>
/// <returns>True if the protocol handler and transport are active</returns>
public override bool IsActive( ZoneImpl zone )
{
return fRunning;
}
/// <summary>
/// Creates the SIF_Protocol object that will be included with a SIF_Register
/// message sent to the zone associated with this Transport.</Summary>
/// <remarks>
/// The base class implementation creates an empty SIF_Protocol with zero
/// or more SIF_Property elements according to the parameters that have been
/// defined by the client via setParameter. Derived classes should therefore
/// call the superclass implementation first, then add to the resulting
/// SIF_Protocol element as needed.
/// </remarks>
/// <param name="zone"></param>
/// <returns></returns>
public override SIF_Protocol MakeSIF_Protocol( IZone zone )
{
// No SIF_Protocol element is necessary in pull mode
return null;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="AppDomainFactory.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* AppDomain factory -- creates app domains on demand from ISAPI
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Hosting {
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Text;
using System.Web;
using System.Web.Compilation;
using System.Web.Util;
//
// IAppDomainFactory / AppDomainFactory are obsolete and stay public
// only to avoid breaking changes.
//
// The new code uses IAppManagerAppDomainFactory / AppAppManagerDomainFactory
//
/// <internalonly/>
[ComImport, Guid("e6e21054-a7dc-4378-877d-b7f4a2d7e8ba"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface IAppDomainFactory {
#if !FEATURE_PAL // FEATURE_PAL does not enable COM
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
[return: MarshalAs(UnmanagedType.Interface)]
Object Create(
[In, MarshalAs(UnmanagedType.BStr)]
String module,
[In, MarshalAs(UnmanagedType.BStr)]
String typeName,
[In, MarshalAs(UnmanagedType.BStr)]
String appId,
[In, MarshalAs(UnmanagedType.BStr)]
String appPath,
[In, MarshalAs(UnmanagedType.BStr)]
String strUrlOfAppOrigin,
[In, MarshalAs(UnmanagedType.I4)]
int iZone);
#else // !FEATURE_PAL
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
[return: MarshalAs(UnmanagedType.Error)]
Object Create(
[In, MarshalAs(UnmanagedType.Error)]
String module,
[In, MarshalAs(UnmanagedType.Error)]
String typeName,
[In, MarshalAs(UnmanagedType.Error)]
String appId,
[In, MarshalAs(UnmanagedType.Error)]
String appPath,
[In, MarshalAs(UnmanagedType.Error)]
String strUrlOfAppOrigin,
[In, MarshalAs(UnmanagedType.I4)]
int iZone);
#endif // FEATURE_PAL
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
/// <internalonly/>
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public sealed class AppDomainFactory : IAppDomainFactory {
private AppManagerAppDomainFactory _realFactory;
public AppDomainFactory() {
_realFactory = new AppManagerAppDomainFactory();
}
/*
* Creates an app domain with an object inside
*/
#if !FEATURE_PAL // FEATURE_PAL does not enable COM
[return: MarshalAs(UnmanagedType.Interface)]
#endif // !FEATURE_PAL
public Object Create(String module, String typeName, String appId, String appPath,
String strUrlOfAppOrigin, int iZone) {
return _realFactory.Create(appId, appPath);
}
}
//
// The new code -- IAppManagerAppDomainFactory / AppAppManagerDomainFactory
//
/// <internalonly/>
[ComImport, Guid("02998279-7175-4d59-aa5a-fb8e44d4ca9d"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface IAppManagerAppDomainFactory {
#if !FEATURE_PAL // FEATURE_PAL does not enable COM
[return: MarshalAs(UnmanagedType.Interface)]
#else // !FEATURE_PAL
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
Object Create(String appId, String appPath);
#endif // !FEATURE_PAL
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
Object Create([In, MarshalAs(UnmanagedType.BStr)] String appId,
[In, MarshalAs(UnmanagedType.BStr)] String appPath);
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
void Stop();
}
/// <internalonly/>
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public sealed class AppManagerAppDomainFactory : IAppManagerAppDomainFactory {
private ApplicationManager _appManager;
public AppManagerAppDomainFactory() {
_appManager = ApplicationManager.GetApplicationManager();
_appManager.Open();
}
/*
* Creates an app domain with an object inside
*/
#if FEATURE_PAL // FEATURE_PAL does not enable COM
[return: MarshalAs(UnmanagedType.Error)]
#else // FEATURE_PAL
[return: MarshalAs(UnmanagedType.Interface)]
#endif // FEATURE_PAL
public Object Create(String appId, String appPath) {
try {
//
// Fill app a Dictionary with 'binding rules' -- name value string pairs
// for app domain creation
//
//
if (appPath[0] == '.') {
System.IO.FileInfo file = new System.IO.FileInfo(appPath);
appPath = file.FullName;
}
if (!StringUtil.StringEndsWith(appPath, '\\')) {
appPath = appPath + "\\";
}
// Create new app domain via App Manager
#if FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
throw new NotImplementedException("ROTORTODO");
#else // FEATURE_PAL
ISAPIApplicationHost appHost = new ISAPIApplicationHost(appId, appPath, false /*validatePhysicalPath*/);
ISAPIRuntime isapiRuntime = (ISAPIRuntime)_appManager.CreateObjectInternal(appId, typeof(ISAPIRuntime), appHost,
false /*failIfExists*/, null /*hostingParameters*/);
isapiRuntime.StartProcessing();
return new ObjectHandle(isapiRuntime);
#endif // FEATURE_PAL
}
catch (Exception e) {
Debug.Trace("internal", "AppDomainFactory::Create failed with " + e.GetType().FullName + ": " + e.Message + "\r\n" + e.StackTrace);
throw;
}
}
public void Stop() {
// wait for all app domains to go away
_appManager.Close();
}
internal static String ConstructSimpleAppName(string virtPath) {
// devdiv 710164: Still repro - ctrl-f5 a WAP project might show "Cannot create/shadow copy when a file exists" error
// since the hash file lists are different, IISExpress launched by VS cannot reuse the build result from VS build.
// It deletes the build files generated by CBM and starts another round of build. This causes interruption between IISExpress and VS
// and leads to this shallow copy exception.
// fix: make the dev IISExpress build to a special drop location
if (virtPath.Length <= 1) { // root?
if (!BuildManagerHost.InClientBuildManager && HostingEnvironment.IsDevelopmentEnvironment)
return "vs";
else
return "root";
}
else
return virtPath.Substring(1).ToLower(CultureInfo.InvariantCulture).Replace('/', '_');
}
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Sce.Atf;
using Sce.Atf.Adaptation;
using Sce.Lua.Utilities;
using Sce.Sled.Shared;
using Sce.Sled.Shared.Dom;
using Sce.Sled.Shared.Plugin;
using Sce.Sled.Shared.Services;
using Sce.Sled.Shared.Utilities;
namespace Sce.Sled.Lua
{
[Export(typeof(IInitializable))]
[Export(typeof(ISledLuaVariableParserService))]
[Export(typeof(SledLuaVariableParserService))]
[PartCreationPolicy(CreationPolicy.Shared)]
sealed class SledLuaVariableParserService : IInitializable, ISledLuaVariableParserService
{
#region IInitializable Interface
void IInitializable.Initialize()
{
m_languageParserService.RegisterFilesParserFunction(m_luaLanguagePlugin, ParseFiles, this);
m_languageParserService.FilesParserFinished += LanguageParserServiceFilesParserFinished;
m_projectService.Opened += ProjectServiceOpened;
m_projectService.Created += ProjectServiceCreated;
m_projectService.FileRemoving += ProjectServiceFileRemoving;
m_projectService.Closed += ProjectServiceClosed;
}
#endregion
#region ISledLuaVariableParser Interface
public Dictionary<string, List<VariableResult>> ParsedGlobals
{
get { return m_parsedGlobals; }
}
public Dictionary<string, List<VariableResult>> ParsedLocals
{
get { return m_parsedLocals; }
}
public Dictionary<string, List<VariableResult>> ParsedUpvalues
{
get { return m_parsedUpvalues; }
}
public IEnumerable<int> ValidBreakpointLineNumbers(SledProjectFilesFileType file)
{
List<int> lines;
if (!m_validBreakpoints.TryGetValue(file, out lines))
yield break;
foreach (var line in lines)
yield return line;
}
public IEnumerable<SledProjectFilesFileType> AllParsedFiles
{
get { return m_parsedResults.Keys; }
}
public event EventHandler ParsingFiles;
public event EventHandler<SledLuaVariableParserServiceEventArgs> ParsingFile;
public event EventHandler<SledLuaVariableParserServiceEventArgs> ParsedFile;
public event EventHandler ParsedFiles;
#endregion
#region ISledLanguageParserService Events
private void LanguageParserServiceFilesParserFinished(object sender, SledLanguageParserEventArgs e)
{
ParsingFiles.Raise(this, EventArgs.Empty);
m_parsedGlobals.Clear();
m_parsedLocals.Clear();
m_parsedUpvalues.Clear();
m_validBreakpoints.Clear();
foreach (var kv in e.FilesAndResults)
{
ParsingFile.Raise(
this,
new SledLuaVariableParserServiceEventArgs(kv.Key, EmptyEnumerable<Result>.Instance));
List<SledLanguageParserResult> items;
if (m_parsedResults.TryGetValue(kv.Key, out items))
{
// Clear data on existing key
items.Clear();
// Add latest results
items.AddRange(kv.Value);
}
else
{
// Completely new key with new results
items = new List<SledLanguageParserResult>(kv.Value);
m_parsedResults.Add(kv.Key, items);
}
ParsedFile.Raise(
this,
new SledLuaVariableParserServiceEventArgs(kv.Key, items.Cast<Result>()));
}
// Pull out some specific information
foreach (var kv in m_parsedResults)
{
var file = kv.Key;
var results = kv.Value;
// Grab all variables
{
var variables = results
.Where(item => item.Is<VariableResult>())
.Select(item => item.As<VariableResult>());
foreach (var variable in variables)
{
Dictionary<string, List<VariableResult>> container = null;
switch (variable.VariableType)
{
case VariableResultType.Global:
container = m_parsedGlobals;
break;
case VariableResultType.Local:
container = m_parsedLocals;
break;
case VariableResultType.Upvalue:
container = m_parsedUpvalues;
break;
}
if (container == null)
continue;
List<VariableResult> items;
if (container.TryGetValue(variable.Name, out items))
{
items.Add(variable);
}
else
{
items = new List<VariableResult> { variable };
container.Add(variable.Name, items);
}
}
}
// Grab valid line nubmers for breakpoints
{
var validBpLineNumbers = results
.Where(item => item.Is<BreakpointResult>())
.Select(item => item.As<BreakpointResult>())
.Select(item => item.Line);
m_validBreakpoints.Add(file, validBpLineNumbers.ToList());
}
}
ParsedFiles.Raise(this, EventArgs.Empty);
}
#endregion
#region ISledProjectService Events
private void ProjectServiceCreated(object sender, SledProjectServiceProjectEventArgs e)
{
ClearAll();
}
private void ProjectServiceOpened(object sender, SledProjectServiceProjectEventArgs e)
{
ClearAll();
}
private void ProjectServiceFileRemoving(object sender, SledProjectServiceFileEventArgs e)
{
m_parsedResults.Remove(e.File);
m_validBreakpoints.Remove(e.File);
}
private void ProjectServiceClosed(object sender, SledProjectServiceProjectEventArgs e)
{
ClearAll();
}
#endregion
#region Public Classes
public abstract class Result : SledLanguageParserResult
{
protected Result(ISledLanguagePlugin plugin, SledProjectFilesFileType file, int line)
: base(plugin, file)
{
Line = line;
}
public int Line { get; private set; }
}
public enum VariableResultType
{
Global,
Local,
Upvalue,
}
public sealed class VariableResult : Result
{
public VariableResult(ISledLanguagePlugin plugin, SledProjectFilesFileType file, string name, int line, int occurence, VariableResultType variableType)
: base(plugin, file, line)
{
Name = name;
Occurence = occurence;
VariableType = variableType;
}
public string Name { get; private set; }
public int Occurence { get; private set; }
public VariableResultType VariableType { get; private set; }
}
public sealed class FunctionResult : Result
{
public FunctionResult(ISledLanguagePlugin plugin, SledProjectFilesFileType file, string name, int lineDefined, int lastLineDefined)
: base(plugin, file, lineDefined)
{
Name = name;
LineDefined = lineDefined;
LastLineDefined = lastLineDefined;
}
public string Name { get; private set; }
public int LineDefined { get; private set; }
public int LastLineDefined { get; private set; }
}
public sealed class BreakpointResult : Result
{
public BreakpointResult(ISledLanguagePlugin plugin, SledProjectFilesFileType file, int line)
: base(plugin, file, line)
{
}
}
#endregion
#region Member Methods
private void ClearAll()
{
m_parsedResults.Clear();
m_parsedGlobals.Clear();
m_parsedLocals.Clear();
m_parsedUpvalues.Clear();
m_validBreakpoints.Clear();
}
private static IEnumerable<SledLanguageParserResult> ParseFiles(IEnumerable<SledProjectFilesFileType> files, SledLanguageParserVerbosity verbosity, object userData, SledUtil.BoolWrapper shouldCancel)
{
SledHiPerfTimer timer = null;
var enumeratedFiles = new List<SledProjectFilesFileType>(files);
var results = new List<SledLanguageParserResult>();
var fileCount = enumeratedFiles.Count;
try
{
if (verbosity > SledLanguageParserVerbosity.None)
{
timer = new SledHiPerfTimer();
timer.Start();
}
var allWorkItems = new ParserWorkItem[fileCount];
for (var i = 0; i < fileCount; ++i)
allWorkItems[i] = new ParserWorkItem(enumeratedFiles[i], verbosity, userData, shouldCancel);
var workerCount = Math.Min(ProducerConsumerQueue.WorkerCount, fileCount);
using (var pcqueue = new ProducerConsumerQueue(workerCount, shouldCancel))
{
pcqueue.EnqueueWorkItems(allWorkItems);
}
if (shouldCancel.Value)
return EmptyEnumerable<SledLanguageParserResult>.Instance;
// gather all results from all work items
foreach (var workItem in allWorkItems)
results.AddRange(workItem.Results);
}
catch (Exception ex)
{
SledOutDevice.OutLine(
SledMessageType.Error,
"{0}: Exception parsing files: {1}",
typeof(SledLuaVariableParserService), ex.Message);
}
finally
{
if ((timer != null) && (!shouldCancel.Value))
{
SledOutDevice.OutLine(
SledMessageType.Info,
"[Lua] Parsed {0} files in {1} seconds",
fileCount, timer.Elapsed);
}
}
return results;
}
#endregion
#pragma warning disable 649 // Field is never assigned to and will always have its default value null
[Import]
private ISledProjectService m_projectService;
[Import]
private ISledLanguageParserService m_languageParserService;
[Import]
private SledLuaLanguagePlugin m_luaLanguagePlugin;
#pragma warning restore 649
private readonly Dictionary<string, List<VariableResult>> m_parsedGlobals =
new Dictionary<string, List<VariableResult>>();
private readonly Dictionary<string, List<VariableResult>> m_parsedLocals =
new Dictionary<string, List<VariableResult>>();
private readonly Dictionary<string, List<VariableResult>> m_parsedUpvalues =
new Dictionary<string, List<VariableResult>>();
private readonly Dictionary<SledProjectFilesFileType, List<int>> m_validBreakpoints =
new Dictionary<SledProjectFilesFileType, List<int>>();
private readonly Dictionary<SledProjectFilesFileType, List<SledLanguageParserResult>> m_parsedResults =
new Dictionary<SledProjectFilesFileType, List<SledLanguageParserResult>>();
#region Private Classes
private class ParserWorkItem : ProducerConsumerQueue.IWork
{
public ParserWorkItem(SledProjectFilesFileType file, SledLanguageParserVerbosity verbosity, object userData, SledUtil.BoolWrapper shouldCancel)
{
m_file = file;
m_verbosity = verbosity;
m_userData = userData;
m_shouldCancel = shouldCancel;
Results = new List<SledLanguageParserResult>();
}
public void WorkCallback()
{
if (m_shouldCancel.Value)
return;
var results = (List<SledLanguageParserResult>)Results;
var plugin = ((SledLuaVariableParserService)m_userData).m_luaLanguagePlugin;
try
{
using (var parser = SledLuaVariableParserFactory.Create())
{
try
{
parser.LogHandler = LuaLogHandler;
if (m_shouldCancel.Value)
return;
var success = parser.Parse(new Uri(m_file.AbsolutePath));
if (!success)
{
if (m_verbosity > SledLanguageParserVerbosity.Overall)
{
var error = parser.Error;
SledOutDevice.OutLine(
SledMessageType.Info,
"{0}: Parse error in \"{1}\": {2}",
typeof(SledLuaVariableParserService), m_file.AbsolutePath, error);
}
return;
}
if (m_shouldCancel.Value)
return;
foreach (var result in parser.Globals)
{
results.Add(new VariableResult(plugin, m_file, result.Name, result.Line, result.Occurrence, VariableResultType.Global));
}
foreach (var result in parser.Locals)
{
results.Add(new VariableResult(plugin, m_file, result.Name, result.Line, result.Occurrence, VariableResultType.Local));
}
foreach (var result in parser.Upvalues)
{
results.Add(new VariableResult(plugin, m_file, result.Name, result.Line, result.Occurrence, VariableResultType.Upvalue));
}
foreach (var result in parser.Functions)
{
results.Add(new FunctionResult(plugin, m_file, result.Name, result.LineDefined, result.LastLineDefined));
}
foreach (var line in parser.ValidBreakpointLines)
{
results.Add(new BreakpointResult(plugin, m_file, line));
}
}
catch (Exception ex)
{
if (m_verbosity > SledLanguageParserVerbosity.None)
{
SledOutDevice.OutLine(
SledMessageType.Error,
"{0}: Exception parsing \"{1}\": {2}",
this, m_file.AbsolutePath, ex.Message);
}
}
}
}
catch (Exception ex)
{
SledOutDevice.OutLine(
SledMessageType.Error,
"{0}: Exception creating Lua parser: {1}",
this, ex.Message);
}
}
public IEnumerable<SledLanguageParserResult> Results { get; private set; }
private void LuaLogHandler(string message)
{
SledOutDevice.OutLine(SledMessageType.Info, "{0}: {1}", this, message);
}
private readonly SledProjectFilesFileType m_file;
private readonly SledLanguageParserVerbosity m_verbosity;
private readonly object m_userData;
private readonly SledUtil.BoolWrapper m_shouldCancel;
}
private static class SledLuaVariableParserFactory
{
public static ILuaParser Create()
{
try
{
if (s_luaVersionService == null)
s_luaVersionService = SledServiceInstance.TryGet<ISledLuaLuaVersionService>();
if (s_luaVersionService == null)
return new Sce.Lua.Utilities.Lua51.x86.LuaParser();
switch (s_luaVersionService.CurrentLuaVersion)
{
case LuaVersion.Lua51: return new Sce.Lua.Utilities.Lua51.x86.LuaParser();
case LuaVersion.Lua52: return new Sce.Lua.Utilities.Lua52.x86.LuaParser();
default: throw new NullReferenceException("Unknown Lua version!");
}
}
catch (Exception ex)
{
SledOutDevice.OutLine(
SledMessageType.Error,
"{0}: Exception creating Lua variable parser: {1}",
typeof(SledLuaVariableParserFactory), ex.Message);
return null;
}
}
private static ISledLuaLuaVersionService s_luaVersionService;
}
#endregion
}
internal class SledLuaVariableParserServiceEventArgs : EventArgs
{
public SledLuaVariableParserServiceEventArgs(SledProjectFilesFileType file, IEnumerable<SledLuaVariableParserService.Result> results)
{
File = file;
Results = new List<SledLuaVariableParserService.Result>(results);
}
public SledProjectFilesFileType File { get; private set; }
public IEnumerable<SledLuaVariableParserService.Result> Results { get; private set; }
}
interface ISledLuaVariableParserService
{
Dictionary<string, List<SledLuaVariableParserService.VariableResult>> ParsedGlobals { get; }
Dictionary<string, List<SledLuaVariableParserService.VariableResult>> ParsedLocals { get; }
Dictionary<string, List<SledLuaVariableParserService.VariableResult>> ParsedUpvalues { get; }
IEnumerable<int> ValidBreakpointLineNumbers(SledProjectFilesFileType file);
IEnumerable<SledProjectFilesFileType> AllParsedFiles { get; }
event EventHandler ParsingFiles;
event EventHandler<SledLuaVariableParserServiceEventArgs> ParsingFile;
event EventHandler<SledLuaVariableParserServiceEventArgs> ParsedFile;
event EventHandler ParsedFiles;
}
}
| |
using System;
using UnityEngine;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Wire Node", "Misc", "Wire Node", null, KeyCode.None, false )]
public sealed class WireNode : ParentNode
{
private bool m_markedToDelete = false;
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddInputPort( WirePortDataType.OBJECT, false, string.Empty );
AddOutputPort( WirePortDataType.OBJECT, Constants.EmptyPortValue );
m_drawPreview = false;
m_drawPreviewExpander = false;
m_canExpand = false;
m_previewShaderGUID = "fa1e3e404e6b3c243b5527b82739d682";
}
public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
{
base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode );
m_inputPorts[ 0 ].MatchPortToConnection();
m_outputPorts[ 0 ].ChangeType( m_inputPorts[ 0 ].DataType, false );
}
public override void OnOutputPortConnected( int portId, int otherNodeId, int otherPortId )
{
base.OnOutputPortConnected( portId, otherNodeId, otherPortId );
if ( m_outputPorts[ portId ].ConnectionCount > 1 )
{
for ( int i = 0; i < m_outputPorts[ portId ].ExternalReferences.Count; i++ )
{
if ( m_outputPorts[ portId ].ExternalReferences[ i ].PortId != otherPortId )
{
UIUtils.DeleteConnection( true, m_outputPorts[ portId ].ExternalReferences[ i ].NodeId, m_outputPorts[ portId ].ExternalReferences[ i ].PortId, false, true );
}
}
}
}
public override void OnConnectedOutputNodeChanges( int outputPortId, int otherNodeId, int otherPortId, string name, WirePortDataType type )
{
base.OnConnectedOutputNodeChanges( outputPortId, otherNodeId, otherPortId, name, type );
m_inputPorts[ 0 ].MatchPortToConnection();
m_outputPorts[ 0 ].ChangeType( m_inputPorts[ 0 ].DataType, false );
//UIUtils.CurrentWindow.CurrentGraph.DestroyNode( UniqueId );
}
public override void OnInputPortDisconnected( int portId )
{
base.OnInputPortDisconnected( portId );
TestIfValid();
}
public override void OnOutputPortDisconnected( int portId )
{
base.OnOutputPortDisconnected( portId );
TestIfValid();
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar );
return m_inputPorts[ 0 ].GeneratePortInstructions( ref dataCollector );
}
public override void DrawProperties()
{
if ( m_markedToDelete )
return;
base.DrawProperties();
}
public override void Draw( DrawInfo drawInfo )
{
if ( m_markedToDelete )
return;
if ( m_repopulateDictionaries )
{
m_repopulateDictionaries = false;
m_inputPortsDict.Clear();
int inputCount = m_inputPorts.Count;
for ( int i = 0; i < inputCount; i++ )
{
m_inputPortsDict.Add( m_inputPorts[ i ].PortId, m_inputPorts[ i ] );
}
m_outputPortsDict.Clear();
int outputCount = m_outputPorts.Count;
for ( int i = 0; i < outputCount; i++ )
{
m_outputPortsDict.Add( m_outputPorts[ i ].PortId, m_outputPorts[ i ] );
}
}
if ( m_initialized )
{
if ( m_sizeIsDirty )
{
m_sizeIsDirty = false;
m_extraSize.Set( 20f, 20f );
m_position.width = m_extraSize.x + UIUtils.PortsSize.x;
m_position.height = m_extraSize.y + UIUtils.PortsSize.y;
Vec2Position -= Position.size * 0.5f;
//m_cachedPos = m_position;
if ( OnNodeChangeSizeEvent != null )
{
OnNodeChangeSizeEvent( this );
}
ChangeSizeFinished();
}
CalculatePositionAndVisibility( drawInfo );
Color colorBuffer = GUI.color;
if ( m_anchorAdjust < 0 )
{
m_anchorAdjust = UIUtils.GetCustomStyle( CustomStyle.PortEmptyIcon ).normal.background.width;
}
//GUI.Box(m_globalPosition, string.Empty, UIUtils.CurrentWindow.CustomStylesInstance.Box);
//Input ports
{
Rect currInputPortPos = m_globalPosition;
currInputPortPos.width = drawInfo.InvertedZoom * UIUtils.PortsSize.x;
currInputPortPos.height = drawInfo.InvertedZoom * UIUtils.PortsSize.y;
currInputPortPos.x += m_position.width * 0.5f * drawInfo.InvertedZoom - currInputPortPos.width * 0.5f;
currInputPortPos.y += m_position.height * 0.5f * drawInfo.InvertedZoom - currInputPortPos.height * 0.5f;
int inputCount = m_inputPorts.Count;
for ( int i = 0; i < inputCount; i++ )
{
if ( m_inputPorts[ i ].Visible )
{
// Button
m_inputPorts[ i ].Position = currInputPortPos;
GUIStyle style = m_inputPorts[ i ].IsConnected ? UIUtils.GetCustomStyle( CustomStyle.PortFullIcon ) : UIUtils.GetCustomStyle( CustomStyle.PortEmptyIcon );
Rect portPos = currInputPortPos;
portPos.x -= Constants.PORT_X_ADJUST;
m_inputPorts[ i ].ActivePortArea = portPos;
if ( m_isVisible )
{
if ( UIUtils.CurrentWindow.Options.ColoredPorts )
GUI.color = Selected ? UIUtils.GetColorFromWireStatus( WireStatus.Highlighted ) : UIUtils.GetColorForDataType( m_inputPorts[ i ].DataType, false, false );
else
GUI.color = Selected ? UIUtils.GetColorFromWireStatus( WireStatus.Highlighted ) : UIUtils.GetColorForDataType( m_inputPorts[ i ].DataType, true, true );
GUI.Box( currInputPortPos, string.Empty, style );
}
GUI.color = colorBuffer;
}
}
}
//Output Ports
{
Rect currOutputPortPos = m_globalPosition;
currOutputPortPos.width = drawInfo.InvertedZoom * UIUtils.PortsSize.x;
currOutputPortPos.height = drawInfo.InvertedZoom * UIUtils.PortsSize.y;
currOutputPortPos.x += m_position.width * 0.5f * drawInfo.InvertedZoom - currOutputPortPos.width * 0.5f;
currOutputPortPos.y += m_position.height * 0.5f * drawInfo.InvertedZoom - currOutputPortPos.height * 0.5f;
int outputCount = m_outputPorts.Count;
for ( int i = 0; i < outputCount; i++ )
{
if ( m_outputPorts[ i ].Visible )
{
//Button
m_outputPorts[ i ].Position = currOutputPortPos;
GUIStyle style = m_isVisible ? ( m_outputPorts[ i ].IsConnected ? UIUtils.GetCustomStyle( CustomStyle.PortFullIcon ) : UIUtils.GetCustomStyle( CustomStyle.PortEmptyIcon ) ) : null;
Rect portPos = currOutputPortPos;
m_outputPorts[ i ].ActivePortArea = portPos;
if ( m_isVisible )
{
if ( UIUtils.CurrentWindow.Options.ColoredPorts )
GUI.color = Selected ? UIUtils.GetColorFromWireStatus( WireStatus.Highlighted ) : UIUtils.GetColorForDataType( m_outputPorts[ i ].DataType, false, false );
else
GUI.color = Selected ? UIUtils.GetColorFromWireStatus( WireStatus.Highlighted ) : UIUtils.GetColorForDataType( m_outputPorts[ i ].DataType, true, false );
GUI.Box( currOutputPortPos, string.Empty, style );
}
GUI.color = colorBuffer;
}
}
}
GUI.color = colorBuffer;
TestIfValid();
}
}
void TestIfValid()
{
if ( !m_inputPorts[ 0 ].IsConnected )
{
if ( !UIUtils.InputPortReference.IsValid || UIUtils.InputPortReference.IsValid && UIUtils.InputPortReference.NodeId != m_uniqueId )
UIUtils.CurrentWindow.CurrentGraph.MarkWireNodeSequence( this, true );
}
if ( !m_outputPorts[ 0 ].IsConnected )
{
if ( !UIUtils.OutputPortReference.IsValid || UIUtils.OutputPortReference.IsValid && UIUtils.OutputPortReference.NodeId != m_uniqueId )
UIUtils.CurrentWindow.CurrentGraph.MarkWireNodeSequence( this, false );
}
}
public Vector3 TangentDirection
{
get
{
ParentNode otherInputNode = null;
ParentNode otherOutputNode = null;
//defaults to itself so it can still calculate tangents
WirePort otherInputPort = m_outputPorts[ 0 ];
WirePort otherOutputPort = m_inputPorts[ 0 ];
if ( m_outputPorts[ 0 ].ConnectionCount > 0 )
{
otherInputNode = UIUtils.GetNode( m_outputPorts[ 0 ].ExternalReferences[ 0 ].NodeId );
otherInputPort = otherInputNode.GetInputPortByUniqueId( m_outputPorts[ 0 ].ExternalReferences[ 0 ].PortId );
}
if ( m_inputPorts[ 0 ].ConnectionCount > 0 )
{
otherOutputNode = UIUtils.GetNode( m_inputPorts[ 0 ].ExternalReferences[ 0 ].NodeId );
otherOutputPort = otherOutputNode.GetOutputPortByUniqueId( m_inputPorts[ 0 ].ExternalReferences[ 0 ].PortId );
}
//TODO: it still generates crooked lines if wire nodes get too close to non-wire nodes (the fix would be to calculate the non-wire nodes magnitude properly)
float mag = Constants.HORIZONTAL_TANGENT_SIZE * UIUtils.CurrentWindow.CameraDrawInfo.InvertedZoom;
Vector2 outPos;
if ( otherOutputNode != null && otherOutputNode.GetType() != typeof( WireNode ) )
outPos = otherOutputPort.Position.position + Vector2.right * mag;
else
outPos = otherOutputPort.Position.position;
Vector2 inPos;
if ( otherInputNode != null && otherInputNode.GetType() != typeof( WireNode ) )
inPos = otherInputPort.Position.position - Vector2.right * mag;
else
inPos = otherInputPort.Position.position;
Vector2 tangent = ( outPos - inPos ).normalized;
return new Vector3( tangent.x, tangent.y );
}
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
m_extraSize.Set( 20f, 20f );
m_position.width = m_extraSize.x + UIUtils.PortsSize.x;
m_position.height = m_extraSize.y + UIUtils.PortsSize.y;
Vec2Position += Position.size * 0.5f;
}
public WireReference FindNewValidInputNode( WireNode current )
{
if ( current.InputPorts[ 0 ].IsConnected )
{
ParentNode node = UIUtils.GetNode( current.InputPorts[ 0 ].ExternalReferences[ 0 ].NodeId );
if ( node != null )
{
WireNode wireNode = node as WireNode;
if ( wireNode != null && wireNode.MarkToDelete )
{
return FindNewValidInputNode( wireNode );
}
else
{
return current.InputPorts[ 0 ].ExternalReferences[ 0 ];
}
}
}
return null;
}
public WireReference FindNewValidOutputNode( WireNode current )
{
if ( current.OutputPorts[ 0 ].IsConnected )
{
ParentNode node = UIUtils.GetNode( current.OutputPorts[ 0 ].ExternalReferences[ 0 ].NodeId );
if ( node != null )
{
WireNode wireNode = node as WireNode;
if ( wireNode != null && wireNode.MarkToDelete )
{
return FindNewValidOutputNode( wireNode );
}
else
{
return current.OutputPorts[ 0 ].ExternalReferences[ 0 ];
}
}
}
return null;
}
public override void Rewire()
{
//if ( m_inputPorts[ 0 ].ExternalReferences != null && m_inputPorts[ 0 ].ExternalReferences.Count > 0 )
//{
//WireReference backPort = m_inputPorts[ 0 ].ExternalReferences[ 0 ];
//for ( int i = 0; i < m_outputPorts[ 0 ].ExternalReferences.Count; i++ )
//{
// UIUtils.CurrentWindow.ConnectInputToOutput( m_outputPorts[ 0 ].ExternalReferences[ i ].NodeId, m_outputPorts[ 0 ].ExternalReferences[ i ].PortId, backPort.NodeId, backPort.PortId );
//}
//}
MarkToDelete = true;
WireReference outputReference = FindNewValidInputNode( this );
WireReference inputReference = FindNewValidOutputNode( this );
if ( outputReference != null && inputReference != null )
{
UIUtils.CurrentWindow.ConnectInputToOutput( inputReference.NodeId, inputReference.PortId, outputReference.NodeId, outputReference.PortId );
}
}
public bool MarkToDelete
{
get { return m_markedToDelete; }
set { m_markedToDelete = value; }
}
}
}
| |
using Shouldly;
using StructureMap.Pipeline;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget3;
using StructureMap.TypeRules;
using System;
using System.Linq;
using Xunit;
namespace StructureMap.Testing.Configuration.DSL
{
public class CreatePluginFamilyTester
{
public interface SomethingElseEntirely : Something, SomethingElse
{
}
public interface SomethingElse
{
}
public interface Something
{
}
public class OrangeSomething : SomethingElseEntirely
{
public readonly Guid Id = Guid.NewGuid();
public override string ToString()
{
return string.Format("OrangeSomething: {0}", Id);
}
protected bool Equals(OrangeSomething other)
{
return Id.Equals(other.Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((OrangeSomething)obj);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
public class RedSomething : Something
{
}
public class GreenSomething : Something
{
}
public class ClassWithStringInConstructor
{
public ClassWithStringInConstructor(string name)
{
}
}
[Fact]
public void Add_an_instance_by_lambda()
{
var container = new Container(r => { r.For<IWidget>().Add(c => new AWidget()); });
container.GetAllInstances<IWidget>()
.First()
.ShouldBeOfType<AWidget>();
}
[Fact]
public void add_an_instance_by_literal_object()
{
var aWidget = new AWidget();
var container = new Container(x => { x.For<IWidget>().Use(aWidget); });
container.GetAllInstances<IWidget>().First().ShouldBeTheSameAs(aWidget);
}
[Fact]
public void AddInstanceByNameOnlyAddsOneInstanceToStructureMap()
{
var container = new Container(r => { r.For<Something>().Add<RedSomething>().Named("Red"); });
container.GetAllInstances<Something>().Count().ShouldBe(1);
}
[Fact]
public void AddInstanceWithNameOnlyAddsOneInstanceToStructureMap()
{
var container = new Container(x => { x.For<Something>().Add<RedSomething>().Named("Red"); });
container.GetAllInstances<Something>()
.Count().ShouldBe(1);
}
[Fact]
public void as_another_lifecycle()
{
var registry = new Registry();
registry.For<IGateway>(Lifecycles.ThreadLocal).ShouldNotBeNull();
var pluginGraph = registry.Build();
var family = pluginGraph.Families[typeof(IGateway)];
family.Lifecycle.ShouldBeOfType<ThreadLocalStorageLifecycle>();
}
[Fact]
public void BuildInstancesOfType()
{
var registry = new Registry();
registry.For<IGateway>();
var pluginGraph = registry.Build();
pluginGraph.Families.Has(typeof(IGateway)).ShouldBeTrue();
}
[Fact]
public void BuildPluginFamilyAsPerRequest()
{
var registry = new Registry();
var pluginGraph = registry.Build();
var family = pluginGraph.Families[typeof(IGateway)];
family.Lifecycle.ShouldBeNull();
}
[Fact]
public void BuildPluginFamilyAsSingleton()
{
var registry = new Registry();
registry.For<IGateway>().Singleton()
.ShouldNotBeNull();
var pluginGraph = registry.Build();
var family = pluginGraph.Families[typeof(IGateway)];
family.Lifecycle.ShouldBeOfType<SingletonLifecycle>();
}
[Fact]
public void CanOverrideTheDefaultInstance1()
{
var registry = new Registry();
// Specify the default implementation for an interface
registry.For<IGateway>().Use<StubbedGateway>();
var pluginGraph = registry.Build();
pluginGraph.Families.Has(typeof(IGateway)).ShouldBeTrue();
var manager = new Container(pluginGraph);
var gateway = (IGateway)manager.GetInstance(typeof(IGateway));
gateway.ShouldBeOfType<StubbedGateway>();
}
[Fact]
public void CanOverrideTheDefaultInstanceAndCreateAnAllNewPluginOnTheFly()
{
var registry = new Registry();
registry.For<IGateway>().Use<FakeGateway>();
var pluginGraph = registry.Build();
pluginGraph.Families.Has(typeof(IGateway)).ShouldBeTrue();
var container = new Container(pluginGraph);
var gateway = (IGateway)container.GetInstance(typeof(IGateway));
gateway.ShouldBeOfType<FakeGateway>();
}
[Fact]
public void CreatePluginFamilyWithADefault()
{
var container = new Container(r =>
{
r.For<IWidget>().Use<ColorWidget>()
.Ctor<string>("color").Is("Red");
});
container.GetInstance<IWidget>().ShouldBeOfType<ColorWidget>().Color.ShouldBe("Red");
}
[Fact]
public void weird_generics_casting()
{
typeof(SomethingElseEntirely).CanBeCastTo<SomethingElse>()
.ShouldBeTrue();
}
[Fact]
public void CreatePluginFamilyWithReferenceToAnotherFamily()
{
var container = new Container(r =>
{
// Had to be a SingletonThing for this to work
r.ForSingletonOf<SomethingElseEntirely>().Use<OrangeSomething>();
r.For<SomethingElse>().Use(context =>
// If the return is cast to OrangeSomething, this works.
context.GetInstance<SomethingElseEntirely>());
r.For<Something>().Use(context =>
// If the return is cast to OrangeSomething, this works.
context.GetInstance<SomethingElseEntirely>());
});
var orangeSomething = container.GetInstance<SomethingElseEntirely>();
orangeSomething.ShouldBeOfType<OrangeSomething>();
container.GetInstance<SomethingElse>()
.ShouldBeOfType<OrangeSomething>()
.ShouldBe(orangeSomething);
container.GetInstance<Something>()
.ShouldBeOfType<OrangeSomething>()
.ShouldBe(orangeSomething);
}
[Fact]
public void PutAnInterceptorIntoTheInterceptionChainOfAPluginFamilyInTheDSL()
{
var lifecycle = new StubbedLifecycle();
var registry = new Registry();
registry.For<IGateway>().LifecycleIs(lifecycle);
var pluginGraph = registry.Build();
pluginGraph.Families[typeof(IGateway)].Lifecycle.ShouldBeTheSameAs(lifecycle);
}
[Fact]
public void Set_the_default_by_a_lambda()
{
var manager =
new Container(
registry => registry.For<IWidget>().Use(() => new AWidget()));
manager.GetInstance<IWidget>().ShouldBeOfType<AWidget>();
}
[Fact]
public void Set_the_default_to_a_built_object()
{
var aWidget = new AWidget();
var manager =
new Container(
registry => registry.For<IWidget>().Use(aWidget));
aWidget.ShouldBeTheSameAs(manager.GetInstance<IWidget>());
}
// Guid test based on problems encountered by Paul Segaro. See http://groups.google.com/group/structuremap-users/browse_thread/thread/34ddaf549ebb14f7?hl=en
[Fact]
public void TheDefaultInstanceIsALambdaForGuidNewGuid()
{
var manager =
new Container(
registry => registry.For<Guid>().Use(() => Guid.NewGuid()));
manager.GetInstance<Guid>().ShouldBeOfType<Guid>();
}
[Fact]
public void TheDefaultInstanceIsConcreteType()
{
IContainer manager = new Container(
registry => registry.For<Rule>().Use<ARule>());
manager.GetInstance<Rule>().ShouldBeOfType<ARule>();
}
}
public class StubbedLifecycle : ILifecycle
{
public void EjectAll(ILifecycleContext context)
{
throw new NotImplementedException();
}
public IObjectCache FindCache(ILifecycleContext context)
{
throw new NotImplementedException();
}
public string Description
{
get { return "Stubbed"; }
}
}
}
| |
using System;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
namespace Domain.Data.Query
{
public partial class Node
{
[Obsolete("This entity is virtual, consider making entity Neo4jBase concrete or use another entity as your starting point.", true)]
public static Neo4jBaseNode Neo4jBase { get { return new Neo4jBaseNode(); } }
}
public partial class Neo4jBaseNode : Blueprint41.Query.Node
{
protected override string GetNeo4jLabel()
{
return null;
}
internal Neo4jBaseNode() { }
internal Neo4jBaseNode(Neo4jBaseAlias alias, bool isReference = false)
{
NodeAlias = alias;
IsReference = isReference;
}
internal Neo4jBaseNode(RELATIONSHIP relationship, DirectionEnum direction, string neo4jLabel = null) : base(relationship, direction, neo4jLabel) { }
public Neo4jBaseNode Alias(out Neo4jBaseAlias alias)
{
alias = new Neo4jBaseAlias(this);
NodeAlias = alias;
return this;
}
public Neo4jBaseNode UseExistingAlias(AliasResult alias)
{
NodeAlias = alias;
return this;
}
public SchemaBaseNode CastToSchemaBase()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new SchemaBaseNode(FromRelationship, Direction, this.Neo4jLabel);
}
public AddressNode CastToAddress()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new AddressNode(FromRelationship, Direction, this.Neo4jLabel);
}
public AddressTypeNode CastToAddressType()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new AddressTypeNode(FromRelationship, Direction, this.Neo4jLabel);
}
public BillOfMaterialsNode CastToBillOfMaterials()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new BillOfMaterialsNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ContactTypeNode CastToContactType()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ContactTypeNode(FromRelationship, Direction, this.Neo4jLabel);
}
public CountryRegionNode CastToCountryRegion()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new CountryRegionNode(FromRelationship, Direction, this.Neo4jLabel);
}
public CreditCardNode CastToCreditCard()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new CreditCardNode(FromRelationship, Direction, this.Neo4jLabel);
}
public CultureNode CastToCulture()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new CultureNode(FromRelationship, Direction, this.Neo4jLabel);
}
public CurrencyNode CastToCurrency()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new CurrencyNode(FromRelationship, Direction, this.Neo4jLabel);
}
public CurrencyRateNode CastToCurrencyRate()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new CurrencyRateNode(FromRelationship, Direction, this.Neo4jLabel);
}
public CustomerNode CastToCustomer()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new CustomerNode(FromRelationship, Direction, this.Neo4jLabel);
}
public DepartmentNode CastToDepartment()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new DepartmentNode(FromRelationship, Direction, this.Neo4jLabel);
}
public DocumentNode CastToDocument()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new DocumentNode(FromRelationship, Direction, this.Neo4jLabel);
}
public EmailAddressNode CastToEmailAddress()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new EmailAddressNode(FromRelationship, Direction, this.Neo4jLabel);
}
public EmployeeNode CastToEmployee()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new EmployeeNode(FromRelationship, Direction, this.Neo4jLabel);
}
public EmployeeDepartmentHistoryNode CastToEmployeeDepartmentHistory()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new EmployeeDepartmentHistoryNode(FromRelationship, Direction, this.Neo4jLabel);
}
public EmployeePayHistoryNode CastToEmployeePayHistory()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new EmployeePayHistoryNode(FromRelationship, Direction, this.Neo4jLabel);
}
public IllustrationNode CastToIllustration()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new IllustrationNode(FromRelationship, Direction, this.Neo4jLabel);
}
public JobCandidateNode CastToJobCandidate()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new JobCandidateNode(FromRelationship, Direction, this.Neo4jLabel);
}
public LocationNode CastToLocation()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new LocationNode(FromRelationship, Direction, this.Neo4jLabel);
}
public PasswordNode CastToPassword()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new PasswordNode(FromRelationship, Direction, this.Neo4jLabel);
}
public PersonNode CastToPerson()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new PersonNode(FromRelationship, Direction, this.Neo4jLabel);
}
public PhoneNumberTypeNode CastToPhoneNumberType()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new PhoneNumberTypeNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductNode CastToProduct()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductCategoryNode CastToProductCategory()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductCategoryNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductCostHistoryNode CastToProductCostHistory()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductCostHistoryNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductDescriptionNode CastToProductDescription()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductDescriptionNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductInventoryNode CastToProductInventory()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductInventoryNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductListPriceHistoryNode CastToProductListPriceHistory()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductListPriceHistoryNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductModelNode CastToProductModel()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductModelNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductPhotoNode CastToProductPhoto()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductPhotoNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductProductPhotoNode CastToProductProductPhoto()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductProductPhotoNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductReviewNode CastToProductReview()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductReviewNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ProductVendorNode CastToProductVendor()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ProductVendorNode(FromRelationship, Direction, this.Neo4jLabel);
}
public PurchaseOrderDetailNode CastToPurchaseOrderDetail()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new PurchaseOrderDetailNode(FromRelationship, Direction, this.Neo4jLabel);
}
public PurchaseOrderHeaderNode CastToPurchaseOrderHeader()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new PurchaseOrderHeaderNode(FromRelationship, Direction, this.Neo4jLabel);
}
public SalesOrderDetailNode CastToSalesOrderDetail()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new SalesOrderDetailNode(FromRelationship, Direction, this.Neo4jLabel);
}
public SalesOrderHeaderNode CastToSalesOrderHeader()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new SalesOrderHeaderNode(FromRelationship, Direction, this.Neo4jLabel);
}
public SalesPersonNode CastToSalesPerson()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new SalesPersonNode(FromRelationship, Direction, this.Neo4jLabel);
}
public SalesPersonQuotaHistoryNode CastToSalesPersonQuotaHistory()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new SalesPersonQuotaHistoryNode(FromRelationship, Direction, this.Neo4jLabel);
}
public SalesReasonNode CastToSalesReason()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new SalesReasonNode(FromRelationship, Direction, this.Neo4jLabel);
}
public SalesTaxRateNode CastToSalesTaxRate()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new SalesTaxRateNode(FromRelationship, Direction, this.Neo4jLabel);
}
public SalesTerritoryNode CastToSalesTerritory()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new SalesTerritoryNode(FromRelationship, Direction, this.Neo4jLabel);
}
public SalesTerritoryHistoryNode CastToSalesTerritoryHistory()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new SalesTerritoryHistoryNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ScrapReasonNode CastToScrapReason()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ScrapReasonNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ShiftNode CastToShift()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ShiftNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ShipMethodNode CastToShipMethod()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ShipMethodNode(FromRelationship, Direction, this.Neo4jLabel);
}
public ShoppingCartItemNode CastToShoppingCartItem()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new ShoppingCartItemNode(FromRelationship, Direction, this.Neo4jLabel);
}
public SpecialOfferNode CastToSpecialOffer()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new SpecialOfferNode(FromRelationship, Direction, this.Neo4jLabel);
}
public StateProvinceNode CastToStateProvince()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new StateProvinceNode(FromRelationship, Direction, this.Neo4jLabel);
}
public StoreNode CastToStore()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new StoreNode(FromRelationship, Direction, this.Neo4jLabel);
}
public TransactionHistoryNode CastToTransactionHistory()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new TransactionHistoryNode(FromRelationship, Direction, this.Neo4jLabel);
}
public TransactionHistoryArchiveNode CastToTransactionHistoryArchive()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new TransactionHistoryArchiveNode(FromRelationship, Direction, this.Neo4jLabel);
}
public UnitMeasureNode CastToUnitMeasure()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new UnitMeasureNode(FromRelationship, Direction, this.Neo4jLabel);
}
public VendorNode CastToVendor()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new VendorNode(FromRelationship, Direction, this.Neo4jLabel);
}
public WorkOrderNode CastToWorkOrder()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new WorkOrderNode(FromRelationship, Direction, this.Neo4jLabel);
}
public WorkOrderRoutingNode CastToWorkOrderRouting()
{
if (this.Neo4jLabel == null)
throw new InvalidOperationException("Casting is not supported for virtual entities.");
if (FromRelationship == null)
throw new InvalidOperationException("Please use the right type immediately, casting is only support after you have match through a relationship.");
return new WorkOrderRoutingNode(FromRelationship, Direction, this.Neo4jLabel);
}
}
public class Neo4jBaseAlias : AliasResult
{
internal Neo4jBaseAlias(Neo4jBaseNode parent)
{
Node = parent;
}
public override IReadOnlyDictionary<string, FieldResult> AliasFields
{
get
{
if (m_AliasFields == null)
{
m_AliasFields = new Dictionary<string, FieldResult>()
{
{ "Uid", new StringResult(this, "Uid", Datastore.AdventureWorks.Model.Entities["Neo4jBase"], Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]) },
};
}
return m_AliasFields;
}
}
private IReadOnlyDictionary<string, FieldResult> m_AliasFields = null;
public StringResult Uid
{
get
{
if ((object)m_Uid == null)
m_Uid = (StringResult)AliasFields["Uid"];
return m_Uid;
}
}
private StringResult m_Uid = null;
}
}
| |
#pragma warning disable CS1587,IDE1006
/**
* 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Text;
using Thrift.Transport;
namespace Thrift.Protocol
{
class TBinaryProtocol : TProtocol
{
protected const uint VERSION_MASK = 0xffff0000;
protected const uint VERSION_1 = 0x80010000;
protected bool strictRead_ = false;
protected bool strictWrite_ = true;
#region BinaryProtocol Factory
/**
* Factory
*/
public class Factory : TProtocolFactory {
protected bool strictRead_ = false;
protected bool strictWrite_ = true;
public Factory()
:this(false, true)
{
}
public Factory(bool strictRead, bool strictWrite)
{
strictRead_ = strictRead;
strictWrite_ = strictWrite;
}
public TProtocol GetProtocol(TTransport trans) {
return new TBinaryProtocol(trans, strictRead_, strictWrite_);
}
}
#endregion
public TBinaryProtocol(TTransport trans)
: this(trans, false, true)
{
}
public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite)
:base(trans)
{
strictRead_ = strictRead;
strictWrite_ = strictWrite;
}
#region Write Methods
public override void WriteMessageBegin(TMessage message)
{
if (strictWrite_)
{
uint version = VERSION_1 | (uint)(message.Type);
WriteI32((int)version);
WriteString(message.Name);
WriteI32(message.SeqID);
}
else
{
WriteString(message.Name);
WriteByte((sbyte)message.Type);
WriteI32(message.SeqID);
}
}
public override void WriteMessageEnd()
{
}
public override void WriteStructBegin(TStruct struc)
{
}
public override void WriteStructEnd()
{
}
public override void WriteFieldBegin(TField field)
{
WriteByte((sbyte)field.Type);
WriteI16(field.ID);
}
public override void WriteFieldEnd()
{
}
public override void WriteFieldStop()
{
WriteByte((sbyte)TType.Stop);
}
public override void WriteMapBegin(TMap map)
{
WriteByte((sbyte)map.KeyType);
WriteByte((sbyte)map.ValueType);
WriteI32(map.Count);
}
public override void WriteMapEnd()
{
}
public override void WriteListBegin(TList list)
{
WriteByte((sbyte)list.ElementType);
WriteI32(list.Count);
}
public override void WriteListEnd()
{
}
public override void WriteSetBegin(TSet set)
{
WriteByte((sbyte)set.ElementType);
WriteI32(set.Count);
}
public override void WriteSetEnd()
{
}
public override void WriteBool(bool b)
{
WriteByte(b ? (sbyte)1 : (sbyte)0);
}
private byte[] bout = new byte[1];
public override void WriteByte(sbyte b)
{
bout[0] = (byte)b;
trans.Write(bout, 0, 1);
}
private byte[] i16out = new byte[2];
public override void WriteI16(short s)
{
i16out[0] = (byte)(0xff & (s >> 8));
i16out[1] = (byte)(0xff & s);
trans.Write(i16out, 0, 2);
}
private byte[] i32out = new byte[4];
public override void WriteI32(int i32)
{
i32out[0] = (byte)(0xff & (i32 >> 24));
i32out[1] = (byte)(0xff & (i32 >> 16));
i32out[2] = (byte)(0xff & (i32 >> 8));
i32out[3] = (byte)(0xff & i32);
trans.Write(i32out, 0, 4);
}
private byte[] i64out = new byte[8];
public override void WriteI64(long i64)
{
i64out[0] = (byte)(0xff & (i64 >> 56));
i64out[1] = (byte)(0xff & (i64 >> 48));
i64out[2] = (byte)(0xff & (i64 >> 40));
i64out[3] = (byte)(0xff & (i64 >> 32));
i64out[4] = (byte)(0xff & (i64 >> 24));
i64out[5] = (byte)(0xff & (i64 >> 16));
i64out[6] = (byte)(0xff & (i64 >> 8));
i64out[7] = (byte)(0xff & i64);
trans.Write(i64out, 0, 8);
}
public override void WriteDouble(double d)
{
#if !SILVERLIGHT
WriteI64(BitConverter.DoubleToInt64Bits(d));
#else
var bytes = BitConverter.GetBytes(d);
WriteI64(BitConverter.ToInt64(bytes, 0));
#endif
}
public override void WriteBinary(byte[] b)
{
WriteI32(b.Length);
trans.Write(b, 0, b.Length);
}
#endregion
#region ReadMethods
public override TMessage ReadMessageBegin()
{
TMessage message = new TMessage();
int size = ReadI32();
if (size < 0)
{
uint version = (uint)size & VERSION_MASK;
if (version != VERSION_1)
{
throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in ReadMessageBegin: " + version);
}
message.Type = (TMessageType)(size & 0x000000ff);
message.Name = ReadString();
message.SeqID = ReadI32();
}
else
{
if (strictRead_)
{
throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?");
}
message.Name = ReadStringBody(size);
message.Type = (TMessageType)ReadByte();
message.SeqID = ReadI32();
}
return message;
}
public override void ReadMessageEnd()
{
}
public override TStruct ReadStructBegin()
{
return new TStruct();
}
public override void ReadStructEnd()
{
}
public override TField ReadFieldBegin()
{
TField field = new TField();
field.Type = (TType)ReadByte();
if (field.Type != TType.Stop)
{
field.ID = ReadI16();
}
return field;
}
public override void ReadFieldEnd()
{
}
public override TMap ReadMapBegin()
{
TMap map = new TMap();
map.KeyType = (TType)ReadByte();
map.ValueType = (TType)ReadByte();
map.Count = ReadI32();
return map;
}
public override void ReadMapEnd()
{
}
public override TList ReadListBegin()
{
TList list = new TList();
list.ElementType = (TType)ReadByte();
list.Count = ReadI32();
return list;
}
public override void ReadListEnd()
{
}
public override TSet ReadSetBegin()
{
TSet set = new TSet();
set.ElementType = (TType)ReadByte();
set.Count = ReadI32();
return set;
}
public override void ReadSetEnd()
{
}
public override bool ReadBool()
{
return ReadByte() == 1;
}
private byte[] bin = new byte[1];
public override sbyte ReadByte()
{
ReadAll(bin, 0, 1);
return (sbyte)bin[0];
}
private byte[] i16in = new byte[2];
public override short ReadI16()
{
ReadAll(i16in, 0, 2);
return (short)(((i16in[0] & 0xff) << 8) | ((i16in[1] & 0xff)));
}
private byte[] i32in = new byte[4];
public override int ReadI32()
{
ReadAll(i32in, 0, 4);
return (int)(((i32in[0] & 0xff) << 24) | ((i32in[1] & 0xff) << 16) | ((i32in[2] & 0xff) << 8) | ((i32in[3] & 0xff)));
}
#pragma warning disable 675
private byte[] i64in = new byte[8];
public override long ReadI64()
{
ReadAll(i64in, 0, 8);
unchecked {
return (long)(
((long)(i64in[0] & 0xff) << 56) |
((long)(i64in[1] & 0xff) << 48) |
((long)(i64in[2] & 0xff) << 40) |
((long)(i64in[3] & 0xff) << 32) |
((long)(i64in[4] & 0xff) << 24) |
((long)(i64in[5] & 0xff) << 16) |
((long)(i64in[6] & 0xff) << 8) |
((long)(i64in[7] & 0xff)));
}
}
#pragma warning restore 675
public override double ReadDouble()
{
#if !SILVERLIGHT
return BitConverter.Int64BitsToDouble(ReadI64());
#else
var value = ReadI64();
var bytes = BitConverter.GetBytes(value);
return BitConverter.ToDouble(bytes, 0);
#endif
}
public override byte[] ReadBinary()
{
int size = ReadI32();
byte[] buf = new byte[size];
trans.ReadAll(buf, 0, size);
return buf;
}
private string ReadStringBody(int size)
{
byte[] buf = new byte[size];
trans.ReadAll(buf, 0, size);
return Encoding.UTF8.GetString(buf, 0, buf.Length);
}
private int ReadAll(byte[] buf, int off, int len)
{
return trans.ReadAll(buf, off, len);
}
#endregion
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2015 Microsoft Corporation
//
// 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.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.OneDrive.Sdk
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
/// <summary>
/// The type ItemRequest.
/// </summary>
public partial class ItemRequest : BaseRequest, IItemRequest
{
/// <summary>
/// Constructs a new ItemRequest.
/// </summary>
/// <param name="requestUrl">The request URL.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query option name value pairs for the request.</param>
public ItemRequest(
string requestUrl,
IBaseClient client,
IList<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified Item using PUT.
/// </summary>
/// <param name="item">The Item to create.</param>
/// <returns>The created Item.</returns>
public async Task<Item> CreateAsync(Item item)
{
this.ContentType = "application/json";
this.Method = "PUT";
var entity = await this.SendAsync<Item>(item);
this.InitializeCollectionProperties(entity);
return entity;
}
/// <summary>
/// Deletes the specified Item.
/// </summary>
/// <returns>The task to await.</returns>
public async Task DeleteAsync()
{
this.Method = "DELETE";
await this.SendAsync<Item>(null);
}
/// <summary>
/// Gets the Item.
/// </summary>
/// <returns>The Item.</returns>
public async Task<Item> GetAsync()
{
this.Method = "GET";
var entity = await this.SendAsync<Item>(null);
this.InitializeCollectionProperties(entity);
return entity;
}
/// <summary>
/// Updates the specified Item using PATCH.
/// </summary>
/// <param name="item">The Item to update.</param>
/// <returns>The updated Item.</returns>
public async Task<Item> UpdateAsync(Item item)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var entity = await this.SendAsync<Item>(item);
this.InitializeCollectionProperties(entity);
return entity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IItemRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IItemRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IItemRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="item">The <see cref="Item"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(Item item)
{
if (item != null && item.AdditionalData != null)
{
if (item.Permissions != null && item.Permissions.CurrentPage != null)
{
item.Permissions.AdditionalData = item.AdditionalData;
object nextPageLink;
item.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
item.Permissions.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (item.Versions != null && item.Versions.CurrentPage != null)
{
item.Versions.AdditionalData = item.AdditionalData;
object nextPageLink;
item.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
item.Versions.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (item.Children != null && item.Children.CurrentPage != null)
{
item.Children.AdditionalData = item.AdditionalData;
object nextPageLink;
item.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
item.Children.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (item.Thumbnails != null && item.Thumbnails.CurrentPage != null)
{
item.Thumbnails.AdditionalData = item.AdditionalData;
object nextPageLink;
item.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
item.Thumbnails.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions.Interpreter
{
internal abstract class OffsetInstruction : Instruction
{
internal const int Unknown = Int32.MinValue;
internal const int CacheSize = 32;
// the offset to jump to (relative to this instruction):
protected int _offset = Unknown;
public abstract Instruction[] Cache { get; }
public Instruction Fixup(int offset)
{
Debug.Assert(_offset == Unknown && offset != Unknown);
_offset = offset;
var cache = Cache;
if (cache != null && offset >= 0 && offset < cache.Length)
{
return cache[offset] ?? (cache[offset] = this);
}
return this;
}
public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects)
{
return ToString() + (_offset != Unknown ? " -> " + (instructionIndex + _offset) : "");
}
public override string ToString()
{
return InstructionName + (_offset == Unknown ? "(?)" : "(" + _offset + ")");
}
}
internal sealed class BranchFalseInstruction : OffsetInstruction
{
private static Instruction[] s_cache;
public override string InstructionName
{
get { return "BranchFalse"; }
}
public override Instruction[] Cache
{
get
{
if (s_cache == null)
{
s_cache = new Instruction[CacheSize];
}
return s_cache;
}
}
internal BranchFalseInstruction()
{
}
public override int ConsumedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
if (!(bool)frame.Pop())
{
return _offset;
}
return +1;
}
}
internal sealed class BranchTrueInstruction : OffsetInstruction
{
private static Instruction[] s_cache;
public override string InstructionName
{
get { return "BranchTrue"; }
}
public override Instruction[] Cache
{
get
{
if (s_cache == null)
{
s_cache = new Instruction[CacheSize];
}
return s_cache;
}
}
internal BranchTrueInstruction()
{
}
public override int ConsumedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
if ((bool)frame.Pop())
{
return _offset;
}
return +1;
}
}
internal sealed class CoalescingBranchInstruction : OffsetInstruction
{
private static Instruction[] s_cache;
public override string InstructionName
{
get { return "CoalescingBranch"; }
}
public override Instruction[] Cache
{
get
{
if (s_cache == null)
{
s_cache = new Instruction[CacheSize];
}
return s_cache;
}
}
internal CoalescingBranchInstruction()
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
if (frame.Peek() != null)
{
return _offset;
}
return +1;
}
}
internal class BranchInstruction : OffsetInstruction
{
private static Instruction[][][] s_caches;
public override string InstructionName
{
get { return "Branch"; }
}
public override Instruction[] Cache
{
get
{
if (s_caches == null)
{
s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] };
}
return s_caches[ConsumedStack][ProducedStack] ?? (s_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]);
}
}
internal readonly bool _hasResult;
internal readonly bool _hasValue;
internal BranchInstruction()
: this(false, false)
{
}
public BranchInstruction(bool hasResult, bool hasValue)
{
_hasResult = hasResult;
_hasValue = hasValue;
}
public override int ConsumedStack
{
get { return _hasValue ? 1 : 0; }
}
public override int ProducedStack
{
get { return _hasResult ? 1 : 0; }
}
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
return _offset;
}
}
internal abstract class IndexedBranchInstruction : Instruction
{
protected const int CacheSize = 32;
internal readonly int _labelIndex;
public IndexedBranchInstruction(int labelIndex)
{
_labelIndex = labelIndex;
}
public RuntimeLabel GetLabel(InterpretedFrame frame)
{
Debug.Assert(_labelIndex != UnknownInstrIndex);
return frame.Interpreter._labels[_labelIndex];
}
public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects)
{
Debug.Assert(_labelIndex != UnknownInstrIndex);
int targetIndex = labelIndexer(_labelIndex);
return ToString() + (targetIndex != BranchLabel.UnknownIndex ? " -> " + targetIndex : "");
}
public override string ToString()
{
Debug.Assert(_labelIndex != UnknownInstrIndex);
return InstructionName + "[" + _labelIndex + "]";
}
}
/// <summary>
/// This instruction implements a goto expression that can jump out of any expression.
/// It pops values (arguments) from the evaluation stack that the expression tree nodes in between
/// the goto expression and the target label node pushed and not consumed yet.
/// A goto expression can jump into a node that evaluates arguments only if it carries
/// a value and jumps right after the first argument (the carried value will be used as the first argument).
/// Goto can jump into an arbitrary child of a BlockExpression since the block doesn't accumulate values
/// on evaluation stack as its child expressions are being evaluated.
///
/// Goto needs to execute any finally blocks on the way to the target label.
/// <example>
/// {
/// f(1, 2, try { g(3, 4, try { goto L } finally { ... }, 6) } finally { ... }, 7, 8)
/// L: ...
/// }
/// </example>
/// The goto expression here jumps to label L while having 4 items on evaluation stack (1, 2, 3 and 4).
/// The jump needs to execute both finally blocks, the first one on stack level 4 the
/// second one on stack level 2. So, it needs to jump the first finally block, pop 2 items from the stack,
/// run second finally block and pop another 2 items from the stack and set instruction pointer to label L.
///
/// Goto also needs to rethrow ThreadAbortException iff it jumps out of a catch handler and
/// the current thread is in "abort requested" state.
/// </summary>
internal sealed class GotoInstruction : IndexedBranchInstruction
{
private const int Variants = 8;
private static readonly GotoInstruction[] s_cache = new GotoInstruction[Variants * CacheSize];
public override string InstructionName
{
get { return "Goto"; }
}
private readonly bool _hasResult;
private readonly bool _hasValue;
private readonly bool _labelTargetGetsValue;
// The values should technically be Consumed = 1, Produced = 1 for gotos that target a label whose continuation depth
// is different from the current continuation depth. This is because we will consume one continuation from the _continuations
// and at meantime produce a new _pendingContinuation. However, in case of forward gotos, we don't not know that is the
// case until the label is emitted. By then the consumed and produced stack information is useless.
// The important thing here is that the stack balance is 0.
public override int ConsumedContinuations { get { return 0; } }
public override int ProducedContinuations { get { return 0; } }
public override int ConsumedStack
{
get { return _hasValue ? 1 : 0; }
}
public override int ProducedStack
{
get { return _hasResult ? 1 : 0; }
}
private GotoInstruction(int targetIndex, bool hasResult, bool hasValue, bool labelTargetGetsValue)
: base(targetIndex)
{
_hasResult = hasResult;
_hasValue = hasValue;
_labelTargetGetsValue = labelTargetGetsValue;
}
internal static GotoInstruction Create(int labelIndex, bool hasResult, bool hasValue, bool labelTargetGetsValue)
{
if (labelIndex < CacheSize)
{
var index = Variants * labelIndex | (labelTargetGetsValue ? 4 : 0) | (hasResult ? 2 : 0) | (hasValue ? 1 : 0);
return s_cache[index] ?? (s_cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue));
}
return new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue);
}
public override int Run(InterpretedFrame frame)
{
// Are we jumping out of catch/finally while aborting the current thread?
#if FEATURE_THREAD_ABORT
Interpreter.AbortThreadIfRequested(frame, _labelIndex);
#endif
// goto the target label or the current finally continuation:
object value = _hasValue ? frame.Pop() : Interpreter.NoValue;
return frame.Goto(_labelIndex, _labelTargetGetsValue ? value : Interpreter.NoValue, gotoExceptionHandler: false);
}
}
internal sealed class EnterTryCatchFinallyInstruction : IndexedBranchInstruction
{
private readonly bool _hasFinally = false;
private TryCatchFinallyHandler _tryHandler;
internal void SetTryHandler(TryCatchFinallyHandler tryHandler)
{
Debug.Assert(_tryHandler == null && tryHandler != null, "the tryHandler can be set only once");
_tryHandler = tryHandler;
}
public override int ProducedContinuations { get { return _hasFinally ? 1 : 0; } }
private EnterTryCatchFinallyInstruction(int targetIndex, bool hasFinally)
: base(targetIndex)
{
_hasFinally = hasFinally;
}
internal static EnterTryCatchFinallyInstruction CreateTryFinally(int labelIndex)
{
return new EnterTryCatchFinallyInstruction(labelIndex, true);
}
internal static EnterTryCatchFinallyInstruction CreateTryCatch()
{
return new EnterTryCatchFinallyInstruction(UnknownInstrIndex, false);
}
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_tryHandler != null, "the tryHandler must be set already");
if (_hasFinally)
{
// Push finally.
frame.PushContinuation(_labelIndex);
}
int prevInstrIndex = frame.InstructionIndex;
frame.InstructionIndex++;
// Start to run the try/catch/finally blocks
var instructions = frame.Interpreter.Instructions.Instructions;
ExceptionHandler exHandler;
try
{
// run the try block
int index = frame.InstructionIndex;
while (index >= _tryHandler.TryStartIndex && index < _tryHandler.TryEndIndex)
{
index += instructions[index].Run(frame);
frame.InstructionIndex = index;
}
// we finish the try block and is about to jump out of the try/catch blocks
if (index == _tryHandler.GotoEndTargetIndex)
{
// run the 'Goto' that jumps out of the try/catch/finally blocks
Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumps out the try/catch/finally");
frame.InstructionIndex += instructions[index].Run(frame);
}
}
catch (RethrowException)
{
// a rethrow instruction in the try handler gets to run
throw;
}
catch (Exception exception) when (_tryHandler.HasHandler(frame, ref exception, out exHandler))
{
frame.InstructionIndex += frame.Goto(exHandler.LabelIndex, exception, gotoExceptionHandler: true);
#if FEATURE_THREAD_ABORT
// stay in the current catch so that ThreadAbortException is not rethrown by CLR:
var abort = exception as ThreadAbortException;
if (abort != null)
{
Interpreter.AnyAbortException = abort;
frame.CurrentAbortHandler = exHandler;
}
#endif
bool rethrow = false;
try
{
// run the catch block
int index = frame.InstructionIndex;
while (index >= exHandler.HandlerStartIndex && index < exHandler.HandlerEndIndex)
{
index += instructions[index].Run(frame);
frame.InstructionIndex = index;
}
// we finish the catch block and is about to jump out of the try/catch blocks
if (index == _tryHandler.GotoEndTargetIndex)
{
// run the 'Goto' that jumps out of the try/catch/finally blocks
Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumps out the try/catch/finally");
frame.InstructionIndex += instructions[index].Run(frame);
}
}
catch (RethrowException)
{
// a rethrow instruction in a catch block gets to run
rethrow = true;
}
if (rethrow) { throw; }
}
finally
{
if (_tryHandler.IsFinallyBlockExist)
{
// We get to the finally block in two paths:
// 1. Jump from the try/catch blocks. This includes two sub-routes:
// a. 'Goto' instruction in the middle of try/catch block
// b. try/catch block runs to its end. Then the 'Goto(end)' will be trigger to jump out of the try/catch block
// 2. Exception thrown from the try/catch blocks
// In the first path, the continuation mechanism works and frame.InstructionIndex will be updated to point to the first instruction of the finally block
// In the second path, the continuation mechanism is not involved and frame.InstructionIndex is not updated
#if DEBUG
bool isFromJump = frame.IsJumpHappened();
Debug.Assert(!isFromJump || (isFromJump && _tryHandler.FinallyStartIndex == frame.InstructionIndex), "we should already jump to the first instruction of the finally");
#endif
// run the finally block
// we cannot jump out of the finally block, and we cannot have an immediate rethrow in it
int index = frame.InstructionIndex = _tryHandler.FinallyStartIndex;
while (index >= _tryHandler.FinallyStartIndex && index < _tryHandler.FinallyEndIndex)
{
index += instructions[index].Run(frame);
frame.InstructionIndex = index;
}
}
}
return frame.InstructionIndex - prevInstrIndex;
}
public override string InstructionName
{
get { return _hasFinally ? "EnterTryFinally" : "EnterTryCatch"; }
}
public override string ToString()
{
return _hasFinally ? "EnterTryFinally[" + _labelIndex + "]" : "EnterTryCatch";
}
}
/// <summary>
/// The first instruction of finally block.
/// </summary>
internal sealed class EnterFinallyInstruction : IndexedBranchInstruction
{
private readonly static EnterFinallyInstruction[] s_cache = new EnterFinallyInstruction[CacheSize];
public override string InstructionName
{
get { return "EnterFinally"; }
}
public override int ProducedStack { get { return 2; } }
public override int ConsumedContinuations { get { return 1; } }
private EnterFinallyInstruction(int labelIndex)
: base(labelIndex)
{
}
internal static EnterFinallyInstruction Create(int labelIndex)
{
if (labelIndex < CacheSize)
{
return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFinallyInstruction(labelIndex));
}
return new EnterFinallyInstruction(labelIndex);
}
public override int Run(InterpretedFrame frame)
{
// If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown
// in this case we need to set the stack depth
// Else we were getting into this finally block from a 'Goto' jump, and the stack depth is already set properly
if (!frame.IsJumpHappened())
{
frame.SetStackDepth(GetLabel(frame).StackDepth);
}
frame.PushPendingContinuation();
frame.RemoveContinuation();
return 1;
}
}
/// <summary>
/// The last instruction of finally block.
/// </summary>
internal sealed class LeaveFinallyInstruction : Instruction
{
internal static readonly Instruction Instance = new LeaveFinallyInstruction();
public override int ConsumedStack { get { return 2; } }
public override string InstructionName
{
get { return "LeaveFinally"; }
}
private LeaveFinallyInstruction()
{
}
public override int Run(InterpretedFrame frame)
{
frame.PopPendingContinuation();
// If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown
// In this case we just return 1, and the real instruction index will be calculated by GotoHandler later
if (!frame.IsJumpHappened()) { return 1; }
// jump to goto target or to the next finally:
return frame.YieldToPendingContinuation();
}
}
// no-op: we need this just to balance the stack depth and aid debugging of the instruction list.
internal sealed class EnterExceptionFilterInstruction : Instruction
{
internal static readonly EnterExceptionFilterInstruction Instance = new EnterExceptionFilterInstruction();
private EnterExceptionFilterInstruction()
{
}
public override string InstructionName => "EnterExceptionFilter";
public override int ConsumedStack => 0;
// The exception is pushed onto the stack in the filter runner.
public override int ProducedStack => 1;
[ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution.
public override int Run(InterpretedFrame frame) => 1;
}
// no-op: we need this just to balance the stack depth and aid debugging of the instruction list.
internal sealed class LeaveExceptionFilterInstruction : Instruction
{
internal static readonly LeaveExceptionFilterInstruction Instance = new LeaveExceptionFilterInstruction();
private LeaveExceptionFilterInstruction()
{
}
public override string InstructionName => "LeaveExceptionFilter";
// The boolean result is popped from the stack in the filter runner.
public override int ConsumedStack => 1;
public override int ProducedStack => 0;
[ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution.
public override int Run(InterpretedFrame frame) => 1;
}
// no-op: we need this just to balance the stack depth.
internal sealed class EnterExceptionHandlerInstruction : Instruction
{
internal static readonly EnterExceptionHandlerInstruction Void = new EnterExceptionHandlerInstruction(false);
internal static readonly EnterExceptionHandlerInstruction NonVoid = new EnterExceptionHandlerInstruction(true);
// True if try-expression is non-void.
private readonly bool _hasValue;
public override string InstructionName
{
get { return "EnterExceptionHandler"; }
}
private EnterExceptionHandlerInstruction(bool hasValue)
{
_hasValue = hasValue;
}
// If an exception is throws in try-body the expression result of try-body is not evaluated and loaded to the stack.
// So the stack doesn't contain the try-body's value when we start executing the handler.
// However, while emitting instructions try block falls thru the catch block with a value on stack.
// We need to declare it consumed so that the stack state upon entry to the handler corresponds to the real
// stack depth after throw jumped to this catch block.
public override int ConsumedStack { get { return _hasValue ? 1 : 0; } }
// A variable storing the current exception is pushed to the stack by exception handling.
// Catch handlers: The value is immediately popped and stored into a local.
// Fault handlers: The value is kept on stack during fault handler evaluation.
public override int ProducedStack { get { return 1; } }
[ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution.
public override int Run(InterpretedFrame frame)
{
// nop (the exception value is pushed by the interpreter in HandleCatch)
return 1;
}
}
/// <summary>
/// The last instruction of a catch exception handler.
/// </summary>
internal sealed class LeaveExceptionHandlerInstruction : IndexedBranchInstruction
{
private static LeaveExceptionHandlerInstruction[] s_cache = new LeaveExceptionHandlerInstruction[2 * CacheSize];
private readonly bool _hasValue;
public override string InstructionName
{
get { return "LeaveExceptionHandler"; }
}
// The catch block yields a value if the body is non-void. This value is left on the stack.
public override int ConsumedStack
{
get { return _hasValue ? 1 : 0; }
}
public override int ProducedStack
{
get { return _hasValue ? 1 : 0; }
}
private LeaveExceptionHandlerInstruction(int labelIndex, bool hasValue)
: base(labelIndex)
{
_hasValue = hasValue;
}
internal static LeaveExceptionHandlerInstruction Create(int labelIndex, bool hasValue)
{
if (labelIndex < CacheSize)
{
int index = (2 * labelIndex) | (hasValue ? 1 : 0);
return s_cache[index] ?? (s_cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue));
}
return new LeaveExceptionHandlerInstruction(labelIndex, hasValue);
}
public override int Run(InterpretedFrame frame)
{
// CLR rethrows ThreadAbortException when leaving catch handler if abort is requested on the current thread.
#if FEATURE_THREAD_ABORT
Interpreter.AbortThreadIfRequested(frame, _labelIndex);
#endif
return GetLabel(frame).Index - frame.InstructionIndex;
}
}
/// <summary>
/// The last instruction of a fault exception handler.
/// </summary>
internal sealed class LeaveFaultInstruction : Instruction
{
internal static readonly Instruction NonVoid = new LeaveFaultInstruction(true);
internal static readonly Instruction Void = new LeaveFaultInstruction(false);
private readonly bool _hasValue;
public override string InstructionName
{
get { return "LeaveFault"; }
}
// The fault block has a value if the body is non-void, but the value is never used.
// We compile the body of a fault block as void.
// However, we keep the exception object that was pushed upon entering the fault block on the stack during execution of the block
// and pop it at the end.
public override int ConsumedStack
{
get { return 1; }
}
// While emitting instructions a non-void try-fault expression is expected to produce a value.
public override int ProducedStack
{
get { return _hasValue ? 1 : 0; }
}
private LeaveFaultInstruction(bool hasValue)
{
_hasValue = hasValue;
}
public override int Run(InterpretedFrame frame)
{
object exception = frame.Pop();
throw new RethrowException();
}
}
internal sealed class ThrowInstruction : Instruction
{
internal static readonly ThrowInstruction Throw = new ThrowInstruction(true, false);
internal static readonly ThrowInstruction VoidThrow = new ThrowInstruction(false, false);
internal static readonly ThrowInstruction Rethrow = new ThrowInstruction(true, true);
internal static readonly ThrowInstruction VoidRethrow = new ThrowInstruction(false, true);
private readonly bool _hasResult, _rethrow;
public override string InstructionName
{
get { return "Throw"; }
}
private ThrowInstruction(bool hasResult, bool isRethrow)
{
_hasResult = hasResult;
_rethrow = isRethrow;
}
public override int ProducedStack
{
get { return _hasResult ? 1 : 0; }
}
public override int ConsumedStack
{
get
{
return 1;
}
}
public override int Run(InterpretedFrame frame)
{
var ex = (Exception)frame.Pop();
if (_rethrow)
{
throw new RethrowException();
}
throw ex;
}
}
internal sealed class IntSwitchInstruction<T> : Instruction
{
private readonly Dictionary<T, int> _cases;
public override string InstructionName
{
get { return "IntSwitch"; }
}
internal IntSwitchInstruction(Dictionary<T, int> cases)
{
Assert.NotNull(cases);
_cases = cases;
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 0; } }
public override int Run(InterpretedFrame frame)
{
int target;
return _cases.TryGetValue((T)frame.Pop(), out target) ? target : 1;
}
}
internal sealed class StringSwitchInstruction : Instruction
{
private readonly Dictionary<string, int> _cases;
private readonly StrongBox<int> _nullCase;
public override string InstructionName
{
get { return "StringSwitch"; }
}
internal StringSwitchInstruction(Dictionary<string, int> cases, StrongBox<int> nullCase)
{
Assert.NotNull(cases);
Assert.NotNull(nullCase);
_cases = cases;
_nullCase = nullCase;
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 0; } }
public override int Run(InterpretedFrame frame)
{
object value = frame.Pop();
if (value == null)
{
return _nullCase.Value;
}
int target;
return _cases.TryGetValue((string)value, out target) ? target : 1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class DeflateStreamTests
{
static string gzTestFile(String fileName) { return Path.Combine("GZTestData", fileName); }
[Fact]
public void BaseStream1()
{
var writeStream = new MemoryStream();
var zip = new DeflateStream(writeStream, CompressionMode.Compress);
Assert.Same(zip.BaseStream, writeStream);
writeStream.Dispose();
}
[Fact]
public void BaseStream2()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Decompress);
Assert.Same(zip.BaseStream, ms);
ms.Dispose();
}
[Fact]
public async Task ModifyBaseStream()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var newMs = StripHeaderAndFooter.Strip(ms);
var zip = new DeflateStream(newMs, CompressionMode.Decompress);
int size = 1024;
Byte[] bytes = new Byte[size];
zip.BaseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writeable as expected
zip.BaseStream.Position = 0;
await zip.BaseStream.ReadAsync(bytes, 0, size);
}
[Fact]
public void DecompressCanRead()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Decompress);
Assert.True(zip.CanRead);
zip.Dispose();
Assert.False(zip.CanRead);
}
[Fact]
public void CompressCanWrite()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Compress);
Assert.True(zip.CanWrite);
zip.Dispose();
Assert.False(zip.CanWrite);
}
[Fact]
public void CanDisposeBaseStream()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Compress);
ms.Dispose(); // This would throw if this was invalid
}
[Fact]
public void CanDisposeDeflateStream()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Compress);
zip.Dispose();
// Base Stream should be null after dispose
Assert.Null(zip.BaseStream);
zip.Dispose(); // Should be a no-op
}
[Fact]
public async Task CanReadBaseStreamAfterDispose()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var newMs = StripHeaderAndFooter.Strip(ms);
var zip = new DeflateStream(newMs, CompressionMode.Decompress, true);
var baseStream = zip.BaseStream;
zip.Dispose();
int size = 1024;
Byte[] bytes = new Byte[size];
baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writeable as expected
baseStream.Position = 0;
await baseStream.ReadAsync(bytes, 0, size);
}
[Fact]
public async Task DecompressWorks()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithBinaryFile()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc.gz"));
await DecompressAsync(compareStream, gzStream);
}
// Making this async since regular read/write are tested below
private async Task DecompressAsync(MemoryStream compareStream, MemoryStream gzStream)
{
var strippedMs = StripHeaderAndFooter.Strip(gzStream);
var ms = new MemoryStream();
var zip = new DeflateStream(strippedMs, CompressionMode.Decompress);
var deflateStream = new MemoryStream();
int _bufferSize = 1024;
var bytes = new Byte[_bufferSize];
bool finished = false;
int retCount;
while (!finished)
{
retCount = await zip.ReadAsync(bytes, 0, _bufferSize);
if (retCount != 0)
await deflateStream.WriteAsync(bytes, 0, retCount);
else
finished = true;
}
deflateStream.Position = 0;
compareStream.Position = 0;
byte[] compareArray = compareStream.ToArray();
byte[] writtenArray = deflateStream.ToArray();
Assert.Equal(compareArray.Length, writtenArray.Length);
for (int i = 0; i < compareArray.Length; i++)
{
Assert.Equal(compareArray[i], writtenArray[i]);
}
}
[Fact]
public async Task DecompressFailsWithRealGzStream()
{
String[] files = { gzTestFile("GZTestDocument.doc.gz"), gzTestFile("GZTestDocument.txt.gz") };
foreach (String fileName in files)
{
var baseStream = await LocalMemoryStream.readAppFileAsync(fileName);
var zip = new DeflateStream(baseStream, CompressionMode.Decompress);
int _bufferSize = 2048;
var bytes = new Byte[_bufferSize];
Assert.Throws<InvalidDataException>(() => { zip.Read(bytes, 0, _bufferSize); });
zip.Dispose();
}
}
[Fact]
public void DisposedBaseStreamThrows()
{
var ms = new MemoryStream();
ms.Dispose();
Assert.Throws<ArgumentException>(() =>
{
var deflate = new DeflateStream(ms, CompressionMode.Decompress);
});
Assert.Throws<ArgumentException>(() =>
{
var deflate = new DeflateStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void ReadOnlyStreamThrowsOnCompress()
{
var ms = new LocalMemoryStream();
ms.SetCanWrite(false);
Assert.Throws<ArgumentException>(() =>
{
var gzip = new DeflateStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void WriteOnlyStreamThrowsOnDecompress()
{
var ms = new LocalMemoryStream();
ms.SetCanRead(false);
Assert.Throws<ArgumentException>(() =>
{
var gzip = new DeflateStream(ms, CompressionMode.Decompress);
});
}
[Fact]
public void TestCtors()
{
CompressionLevel[] legalValues = new CompressionLevel[] { CompressionLevel.Optimal, CompressionLevel.Fastest, CompressionLevel.NoCompression };
foreach (CompressionLevel level in legalValues)
{
bool[] boolValues = new bool[] { true, false };
foreach (bool remainsOpen in boolValues)
{
TestCtor(level, remainsOpen);
}
}
}
[Fact]
public void TestLevelOptimial()
{
TestCtor(CompressionLevel.Optimal);
}
[Fact]
public void TestLevelNoCompression()
{
TestCtor(CompressionLevel.NoCompression);
}
[Fact]
public void TestLevelFastest()
{
TestCtor(CompressionLevel.Fastest);
}
private static void TestCtor(CompressionLevel level, bool? leaveOpen = null)
{
//Create the DeflateStream
int _bufferSize = 1024;
var bytes = new Byte[_bufferSize];
var baseStream = new MemoryStream(bytes, true);
DeflateStream ds;
if (leaveOpen == null)
{
ds = new DeflateStream(baseStream, level);
}
else
{
ds = new DeflateStream(baseStream, level, leaveOpen ?? false);
}
//Write some data and Close the stream
String strData = "Test Data";
var encoding = Encoding.UTF8;
Byte[] data = encoding.GetBytes(strData);
ds.Write(data, 0, data.Length);
ds.Flush();
ds.Dispose();
if (leaveOpen != true)
{
//Check that Close has really closed the underlying stream
Assert.Throws<ObjectDisposedException>(() => { baseStream.Write(bytes, 0, bytes.Length); });
}
//Read the data
Byte[] data2 = new Byte[_bufferSize];
baseStream = new MemoryStream(bytes, false);
ds = new DeflateStream(baseStream, CompressionMode.Decompress);
int size = ds.Read(data2, 0, _bufferSize - 5);
//Verify the data roundtripped
for (int i = 0; i < size + 5; i++)
{
if (i < data.Length)
{
Assert.Equal(data[i], data2[i]);
}
else
{
Assert.Equal(data2[i], (byte)0);
}
}
}
[Fact]
public void CtorArgumentValidation()
{
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionLevel.Fastest));
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Decompress));
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Compress));
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionLevel.Fastest, true));
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Decompress, false));
Assert.Throws<ArgumentNullException>(() => new DeflateStream(null, CompressionMode.Compress, true));
Assert.Throws<ArgumentException>(() => new DeflateStream(new MemoryStream(), (CompressionMode)42));
Assert.Throws<ArgumentException>(() => new DeflateStream(new MemoryStream(), (CompressionMode)43, true));
Assert.Throws<ArgumentException>(() => new DeflateStream(new MemoryStream(new byte[1], writable: false), CompressionLevel.Optimal));
}
[Fact]
public async Task Flush()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Flush();
await ds.FlushAsync();
}
[Fact]
public void DoubleFlush()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Flush();
ds.Flush();
}
[Fact]
public void DoubleDispose()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Dispose();
ds.Dispose();
}
[Fact]
public void FlushThenDispose()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Flush();
ds.Dispose();
}
[Fact]
public void FlushFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Dispose();
Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); });
}
[Fact]
public async Task FlushAsyncFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Dispose();
await Assert.ThrowsAsync<ObjectDisposedException>(async () =>
{
await ds.FlushAsync();
});
}
[Fact]
public void TestSeekMethodsDecompress()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Decompress);
Assert.False(zip.CanSeek, "CanSeek should be false");
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
}
[Fact]
public void TestSeekMethodsCompress()
{
var ms = new MemoryStream();
var zip = new DeflateStream(ms, CompressionMode.Compress);
Assert.False(zip.CanSeek, "CanSeek should be false");
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
}
[Fact]
public void ReadWriteArgumentValidation()
{
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<ArgumentNullException>(() => ds.Write(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Write(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Write(new byte[1], 0, -1));
Assert.Throws<ArgumentException>(() => ds.Write(new byte[1], 0, 2));
Assert.Throws<ArgumentException>(() => ds.Write(new byte[1], 1, 1));
Assert.Throws<InvalidOperationException>(() => ds.Read(new byte[1], 0, 1));
ds.Write(new byte[1], 0, 0);
}
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<ArgumentNullException>(() => { ds.WriteAsync(null, 0, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.WriteAsync(new byte[1], -1, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.WriteAsync(new byte[1], 0, -1); });
Assert.Throws<ArgumentException>(() => { ds.WriteAsync(new byte[1], 0, 2); });
Assert.Throws<ArgumentException>(() => { ds.WriteAsync(new byte[1], 1, 1); });
Assert.Throws<InvalidOperationException>(() => { ds.Read(new byte[1], 0, 1); });
}
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress))
{
Assert.Throws<ArgumentNullException>(() => ds.Read(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Read(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Read(new byte[1], 0, -1));
Assert.Throws<ArgumentException>(() => ds.Read(new byte[1], 0, 2));
Assert.Throws<ArgumentException>(() => ds.Read(new byte[1], 1, 1));
Assert.Throws<InvalidOperationException>(() => ds.Write(new byte[1], 0, 1));
var data = new byte[1] { 42 };
Assert.Equal(0, ds.Read(data, 0, 0));
Assert.Equal(42, data[0]);
}
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress))
{
Assert.Throws<ArgumentNullException>(() => { ds.ReadAsync(null, 0, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.ReadAsync(new byte[1], -1, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.ReadAsync(new byte[1], 0, -1); });
Assert.Throws<ArgumentException>(() => { ds.ReadAsync(new byte[1], 0, 2); });
Assert.Throws<ArgumentException>(() => { ds.ReadAsync(new byte[1], 1, 1); });
Assert.Throws<InvalidOperationException>(() => { ds.Write(new byte[1], 0, 1); });
}
}
[Fact]
public void Precancellation()
{
var ms = new MemoryStream();
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress, leaveOpen: true))
{
Assert.True(ds.WriteAsync(new byte[1], 0, 1, new CancellationToken(true)).IsCanceled);
Assert.True(ds.FlushAsync(new CancellationToken(true)).IsCanceled);
}
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true))
{
Assert.True(ds.ReadAsync(new byte[1], 0, 1, new CancellationToken(true)).IsCanceled);
}
}
[Fact]
public async Task RoundtripCompressDecompress()
{
await RoundtripCompressDecompress(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest);
await RoundtripCompressDecompress(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal);
}
[Fact]
public async Task RoundTripWithFlush()
{
await RoundTripWithFlush(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest);
await RoundTripWithFlush(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal);
}
[Fact]
public async Task WriteAfterFlushing()
{
await WriteAfterFlushing(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest);
await WriteAfterFlushing(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal);
}
[Fact]
public async Task FlushBeforeFirstWrites()
{
await FlushBeforeFirstWrites(useAsync: false, useGzip: false, chunkSize: 1, totalSize: 10, level: CompressionLevel.Fastest);
await FlushBeforeFirstWrites(useAsync: true, useGzip: true, chunkSize: 1024, totalSize: 8192, level: CompressionLevel.Optimal);
}
public static IEnumerable<object[]> RoundtripCompressDecompressOuterData
{
get
{
foreach (bool useAsync in new[] { true, false }) // whether to use Read/Write or ReadAsync/WriteAsync
{
foreach (bool useGzip in new[] { true, false }) // whether to add on gzip headers/footers
{
foreach (var level in new[] { CompressionLevel.Fastest, CompressionLevel.Optimal, CompressionLevel.NoCompression }) // compression level
{
yield return new object[] { useAsync, useGzip, 1, 5, level }; // smallest possible writes
yield return new object[] { useAsync, useGzip, 1023, 1023 * 10, level }; // overflowing internal buffer
yield return new object[] { useAsync, useGzip, 1024 * 1024, 1024 * 1024, level }; // large single write
}
}
}
}
}
[OuterLoop]
[Theory]
[MemberData("RoundtripCompressDecompressOuterData")]
public async Task RoundtripCompressDecompress(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level)
{
byte[] data = new byte[totalSize];
new Random(42).NextBytes(data);
var compressed = new MemoryStream();
using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true))
{
for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test
{
switch (useAsync)
{
case true: await compressor.WriteAsync(data, i, chunkSize); break;
case false: compressor.Write(data, i, chunkSize); break;
}
}
}
compressed.Position = 0;
await ValidateCompressedData(useAsync, useGzip, chunkSize, compressed, data);
compressed.Dispose();
}
[OuterLoop]
[Theory]
[MemberData("RoundtripCompressDecompressOuterData")]
public async Task RoundTripWithFlush(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level)
{
byte[] data = new byte[totalSize];
new Random(42).NextBytes(data);
using (var compressed = new MemoryStream())
using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true))
{
for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test
{
switch (useAsync)
{
case true: await compressor.WriteAsync(data, i, chunkSize); break;
case false: compressor.Write(data, i, chunkSize); break;
}
}
switch (useAsync)
{
case true: await compressor.FlushAsync(); break;
case false: compressor.Flush(); break;
}
compressed.Position = 0;
await ValidateCompressedData(useAsync, useGzip, chunkSize, compressed, data);
}
}
[OuterLoop]
[Theory]
[MemberData("RoundtripCompressDecompressOuterData")]
public async Task WriteAfterFlushing(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level)
{
byte[] data = new byte[totalSize];
List<byte> expected = new List<byte>();
new Random(42).NextBytes(data);
using (var compressed = new MemoryStream())
using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true))
{
for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test
{
switch (useAsync)
{
case true: await compressor.WriteAsync(data, i, chunkSize); break;
case false: compressor.Write(data, i, chunkSize); break;
}
for (int j = i; j < i + chunkSize; j++)
expected.Insert(j, data[j]);
switch (useAsync)
{
case true: await compressor.FlushAsync(); break;
case false: compressor.Flush(); break;
}
MemoryStream partiallyCompressed = new MemoryStream(compressed.ToArray());
partiallyCompressed.Position = 0;
await ValidateCompressedData(useAsync, useGzip, chunkSize, partiallyCompressed, expected.ToArray());
}
}
}
[OuterLoop]
[Theory]
[MemberData("RoundtripCompressDecompressOuterData")]
public async Task FlushBeforeFirstWrites(bool useAsync, bool useGzip, int chunkSize, int totalSize, CompressionLevel level)
{
byte[] data = new byte[totalSize];
new Random(42).NextBytes(data);
using (var compressed = new MemoryStream())
using (var compressor = useGzip ? (Stream)new GZipStream(compressed, level, true) : new DeflateStream(compressed, level, true))
{
switch (useAsync)
{
case true: await compressor.FlushAsync(); break;
case false: compressor.Flush(); break;
}
for (int i = 0; i < data.Length; i += chunkSize) // not using CopyTo{Async} due to optimizations in MemoryStream's implementation that avoid what we're trying to test
{
switch (useAsync)
{
case true: await compressor.WriteAsync(data, i, chunkSize); break;
case false: compressor.Write(data, i, chunkSize); break;
}
}
switch (useAsync)
{
case true: await compressor.FlushAsync(); break;
case false: compressor.Flush(); break;
}
compressed.Position = 0;
await ValidateCompressedData(useAsync, useGzip, chunkSize, compressed, data);
}
}
/// <summary>
/// Given a MemoryStream of compressed data and a byte array of desired output, decompresses
/// the stream and validates that it is equal to the expected array.
/// </summary>
private async Task ValidateCompressedData(bool useAsync, bool useGzip, int chunkSize, MemoryStream compressed, byte[] expected)
{
using (MemoryStream decompressed = new MemoryStream())
using (Stream decompressor = useGzip ? (Stream)new GZipStream(compressed, CompressionMode.Decompress, true) : new DeflateStream(compressed, CompressionMode.Decompress, true))
{
if (useAsync)
decompressor.CopyTo(decompressed, chunkSize);
else
await decompressor.CopyToAsync(decompressed, chunkSize, CancellationToken.None);
Assert.Equal<byte>(expected, decompressed.ToArray());
}
}
[Fact]
public void SequentialReadsOnMemoryStream_Return_SameBytes()
{
byte[] data = new byte[1024 * 10];
new Random(42).NextBytes(data);
var compressed = new MemoryStream();
using (var compressor = new DeflateStream(compressed, CompressionMode.Compress, true))
{
for (int i = 0; i < data.Length; i += 1024)
{
compressor.Write(data, i, 1024);
}
}
compressed.Position = 0;
using (var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true))
{
int i, j;
byte[] array = new byte[100];
byte[] array2 = new byte[100];
// only read in the first 100 bytes
decompressor.Read(array, 0, array.Length);
for (i = 0; i < array.Length; i++)
Assert.Equal(data[i], array[i]);
// read in the next 100 bytes and make sure nothing is missing
decompressor.Read(array2, 0, array2.Length);
for (j = 0; j < array2.Length; j++)
Assert.Equal(data[j], array[j]);
}
}
[Fact]
public void Roundtrip_Write_ReadByte()
{
byte[] data = new byte[1024 * 10];
new Random(42).NextBytes(data);
var compressed = new MemoryStream();
using (var compressor = new DeflateStream(compressed, CompressionMode.Compress, true))
{
compressor.Write(data, 0, data.Length);
}
compressed.Position = 0;
using (var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true))
{
for (int i = 0; i < data.Length; i++)
Assert.Equal(data[i], decompressor.ReadByte());
}
}
[Fact]
public async Task WrapNullReturningTasksStream()
{
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnNullTasks), CompressionMode.Decompress))
await Assert.ThrowsAsync<InvalidOperationException>(() => ds.ReadAsync(new byte[1024], 0, 1024));
}
[Fact]
public async Task WrapStreamReturningBadReadValues()
{
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress))
Assert.Throws<InvalidDataException>(() => ds.Read(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress))
await Assert.ThrowsAsync<InvalidDataException>(() => ds.ReadAsync(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress))
Assert.Equal(0, ds.Read(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress))
Assert.Equal(0, await ds.ReadAsync(new byte[1024], 0, 1024));
}
private sealed class BadWrappedStream : Stream
{
public enum Mode
{
Default,
ReturnNullTasks,
ReturnTooSmallCounts,
ReturnTooLargeCounts,
}
private readonly Mode _mode;
public BadWrappedStream(Mode mode) { _mode = mode; }
public override int Read(byte[] buffer, int offset, int count)
{
switch (_mode)
{
case Mode.ReturnTooSmallCounts: return -1;
case Mode.ReturnTooLargeCounts: return buffer.Length + 1;
default: return 0;
}
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _mode == Mode.ReturnNullTasks ?
null :
base.ReadAsync(buffer, offset, count, cancellationToken);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _mode == Mode.ReturnNullTasks ?
null :
base.WriteAsync(buffer, offset, count, cancellationToken);
}
public override void Write(byte[] buffer, int offset, int count) { }
public override void Flush() { }
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return true; } }
public override long Length { get { throw new NotSupportedException(); } }
public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
public override void SetLength(long value) { throw new NotSupportedException(); }
}
}
}
| |
// 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 ExtractVector128UInt641()
{
var test = new ExtractVector128Test__ExtractVector128UInt641();
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 ExtractVector128Test__ExtractVector128UInt641
{
private struct TestStruct
{
public Vector256<UInt64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(ExtractVector128Test__ExtractVector128UInt641 testClass)
{
var result = Avx2.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<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector256<UInt64> _clsVar;
private Vector256<UInt64> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static ExtractVector128Test__ExtractVector128UInt641()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
}
public ExtractVector128Test__ExtractVector128UInt641()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ExtractVector128(
Unsafe.Read<Vector256<UInt64>>(_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 = Avx2.ExtractVector128(
Avx.LoadVector256((UInt64*)(_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 = Avx2.ExtractVector128(
Avx.LoadAlignedVector256((UInt64*)(_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(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.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<UInt64>>(_dataTable.inArrayPtr);
var result = Avx2.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((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.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((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ExtractVector128Test__ExtractVector128UInt641();
var result = Avx2.ExtractVector128(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.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 = Avx2.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<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != firstOp[2])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((result[i] != firstOp[i + 2]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ExtractVector128)}<UInt64>(Vector256<UInt64><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 NUnit.Framework;
using Python.Runtime;
using System;
using System.Linq;
using System.Threading;
namespace Python.EmbeddingTest
{
public class TestFinalizer
{
private int _oldThreshold;
[SetUp]
public void SetUp()
{
_oldThreshold = Finalizer.Instance.Threshold;
PythonEngine.Initialize();
Exceptions.Clear();
}
[TearDown]
public void TearDown()
{
Finalizer.Instance.Threshold = _oldThreshold;
PythonEngine.Shutdown();
}
private static void FullGCCollect()
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
}
[Test]
public void CollectBasicObject()
{
Assert.IsTrue(Finalizer.Instance.Enable);
Finalizer.Instance.Threshold = 1;
bool called = false;
var objectCount = 0;
EventHandler<Finalizer.CollectArgs> handler = (s, e) =>
{
objectCount = e.ObjectCount;
called = true;
};
Assert.IsFalse(called, "The event handler was called before it was installed");
Finalizer.Instance.CollectOnce += handler;
WeakReference shortWeak;
WeakReference longWeak;
{
MakeAGarbage(out shortWeak, out longWeak);
}
FullGCCollect();
// The object has been resurrected
Warn.If(
shortWeak.IsAlive,
"The referenced object is alive although it should have been collected",
shortWeak
);
Assert.IsTrue(
longWeak.IsAlive,
"The reference object is not alive although it should still be",
longWeak
);
{
var garbage = Finalizer.Instance.GetCollectedObjects();
Assert.NotZero(garbage.Count, "There should still be garbage around");
Warn.Unless(
garbage.Any(T => ReferenceEquals(T.Target, longWeak.Target)),
$"The {nameof(longWeak)} reference doesn't show up in the garbage list",
garbage
);
}
try
{
Finalizer.Instance.Collect(forceDispose: false);
}
finally
{
Finalizer.Instance.CollectOnce -= handler;
}
Assert.IsTrue(called, "The event handler was not called during finalization");
Assert.GreaterOrEqual(objectCount, 1);
}
private static void MakeAGarbage(out WeakReference shortWeak, out WeakReference longWeak)
{
PyLong obj = new PyLong(1024);
shortWeak = new WeakReference(obj);
longWeak = new WeakReference(obj, true);
obj = null;
}
private static long CompareWithFinalizerOn(PyObject pyCollect, bool enbale)
{
// Must larger than 512 bytes make sure Python use
string str = new string('1', 1024);
Finalizer.Instance.Enable = true;
FullGCCollect();
FullGCCollect();
pyCollect.Invoke();
Finalizer.Instance.Collect();
Finalizer.Instance.Enable = enbale;
// Estimate unmanaged memory size
long before = Environment.WorkingSet - GC.GetTotalMemory(true);
for (int i = 0; i < 10000; i++)
{
// Memory will leak when disable Finalizer
new PyString(str);
}
FullGCCollect();
FullGCCollect();
pyCollect.Invoke();
if (enbale)
{
Finalizer.Instance.Collect();
}
FullGCCollect();
FullGCCollect();
long after = Environment.WorkingSet - GC.GetTotalMemory(true);
return after - before;
}
/// <summary>
/// Because of two vms both have their memory manager,
/// this test only prove the finalizer has take effect.
/// </summary>
[Test]
[Ignore("Too many uncertainties, only manual on when debugging")]
public void SimpleTestMemory()
{
bool oldState = Finalizer.Instance.Enable;
try
{
using (PyObject gcModule = PythonEngine.ImportModule("gc"))
using (PyObject pyCollect = gcModule.GetAttr("collect"))
{
long span1 = CompareWithFinalizerOn(pyCollect, false);
long span2 = CompareWithFinalizerOn(pyCollect, true);
Assert.Less(span2, span1);
}
}
finally
{
Finalizer.Instance.Enable = oldState;
}
}
class MyPyObject : PyObject
{
public MyPyObject(IntPtr op) : base(op)
{
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
GC.SuppressFinalize(this);
throw new Exception("MyPyObject");
}
internal static void CreateMyPyObject(IntPtr op)
{
Runtime.Runtime.XIncref(op);
new MyPyObject(op);
}
}
[Test]
public void ErrorHandling()
{
bool called = false;
var errorMessage = "";
EventHandler<Finalizer.ErrorArgs> handleFunc = (sender, args) =>
{
called = true;
errorMessage = args.Error.Message;
};
Finalizer.Instance.Threshold = 1;
Finalizer.Instance.ErrorHandler += handleFunc;
try
{
WeakReference shortWeak;
WeakReference longWeak;
{
MakeAGarbage(out shortWeak, out longWeak);
var obj = (PyLong)longWeak.Target;
IntPtr handle = obj.Handle;
shortWeak = null;
longWeak = null;
MyPyObject.CreateMyPyObject(handle);
obj.Dispose();
obj = null;
}
FullGCCollect();
Finalizer.Instance.Collect();
Assert.IsTrue(called);
}
finally
{
Finalizer.Instance.ErrorHandler -= handleFunc;
}
Assert.AreEqual(errorMessage, "MyPyObject");
}
[Test]
public void ValidateRefCount()
{
if (!Finalizer.Instance.RefCountValidationEnabled)
{
Assert.Pass("Only run with FINALIZER_CHECK");
}
IntPtr ptr = IntPtr.Zero;
bool called = false;
Finalizer.IncorrectRefCntHandler handler = (s, e) =>
{
called = true;
Assert.AreEqual(ptr, e.Handle);
Assert.AreEqual(2, e.ImpactedObjects.Count);
// Fix for this test, don't do this on general environment
Runtime.Runtime.XIncref(e.Handle);
return false;
};
Finalizer.Instance.IncorrectRefCntResolver += handler;
try
{
ptr = CreateStringGarbage();
FullGCCollect();
Assert.Throws<Finalizer.IncorrectRefCountException>(() => Finalizer.Instance.Collect());
Assert.IsTrue(called);
}
finally
{
Finalizer.Instance.IncorrectRefCntResolver -= handler;
}
}
private static IntPtr CreateStringGarbage()
{
PyString s1 = new PyString("test_string");
// s2 steal a reference from s1
PyString s2 = new PyString(s1.Handle);
return s1.Handle;
}
}
}
| |
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
namespace Alphaleonis.Win32.Filesystem
{
public static partial class Directory
{
/// <summary>Creates a new directory with the attributes of a specified template directory (if one is specified).
/// If the underlying file system supports security on files and directories, the function applies the specified security descriptor to the new directory.
/// The new directory retains the other attributes of the specified template directory.
/// </summary>
/// <returns>
/// <para>Returns an object that represents the directory at the specified path.</para>
/// <para>This object is returned regardless of whether a directory at the specified path already exists.</para>
/// </returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="returnNull">When <c>true</c> returns <c>null</c> instead of a <see cref="DirectoryInfo"/> instance.</param>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to create.</param>
/// <param name="templatePath">The path of the directory to use as a template when creating the new directory. May be <c>null</c> to indicate that no template should be used.</param>
/// <param name="directorySecurity">The <see cref="DirectorySecurity"/> access control to apply to the directory, may be null.</param>
/// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
internal static DirectoryInfo CreateDirectoryCore(bool returnNull, KernelTransaction transaction, string path, string templatePath, ObjectSecurity directorySecurity, bool compress, PathFormat pathFormat)
{
var longPath = path;
if (pathFormat != PathFormat.LongFullPath)
{
if (null == path)
throw new ArgumentNullException("path");
Path.CheckSupportedPathFormat(path, true, true);
Path.CheckSupportedPathFormat(templatePath, true, true);
longPath = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);
pathFormat = PathFormat.LongFullPath;
}
if (!char.IsWhiteSpace(longPath[longPath.Length - 1]))
{
// Return DirectoryInfo instance if the directory specified by path already exists.
if (File.ExistsCore(transaction, true, longPath, PathFormat.LongFullPath))
// We are not always interested in a new DirectoryInfo instance.
return returnNull ? null : new DirectoryInfo(transaction, longPath, PathFormat.LongFullPath);
}
// MSDN: .NET 3.5+: IOException: The directory specified by path is a file or the network name was not found.
if (File.ExistsCore(transaction, false, longPath, PathFormat.LongFullPath))
NativeError.ThrowException(Win32Errors.ERROR_ALREADY_EXISTS, longPath);
var templatePathLp = Utils.IsNullOrWhiteSpace(templatePath)
? null
: Path.GetExtendedLengthPathCore(transaction, templatePath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);
var list = ConstructFullPath(transaction, longPath);
// Directory security.
using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(directorySecurity))
{
// Create the directory paths.
while (list.Count > 0)
{
var folderLp = list.Pop();
// CreateDirectory() / CreateDirectoryEx()
// 2013-01-13: MSDN confirms LongPath usage.
if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista
? (templatePathLp == null
? NativeMethods.CreateDirectory(folderLp, securityAttributes)
: NativeMethods.CreateDirectoryEx(templatePathLp, folderLp, securityAttributes))
: NativeMethods.CreateDirectoryTransacted(templatePathLp, folderLp, securityAttributes, transaction.SafeHandle)))
{
var lastError = Marshal.GetLastWin32Error();
switch ((uint) lastError)
{
// MSDN: .NET 3.5+: If the directory already exists, this method does nothing.
// MSDN: .NET 3.5+: IOException: The directory specified by path is a file.
case Win32Errors.ERROR_ALREADY_EXISTS:
if (File.ExistsCore(transaction, false, longPath, PathFormat.LongFullPath))
NativeError.ThrowException(lastError, longPath);
if (File.ExistsCore(transaction, false, folderLp, PathFormat.LongFullPath))
NativeError.ThrowException(Win32Errors.ERROR_PATH_NOT_FOUND, null, folderLp);
break;
case Win32Errors.ERROR_BAD_NET_NAME:
NativeError.ThrowException(Win32Errors.ERROR_BAD_NET_NAME, longPath);
break;
case Win32Errors.ERROR_DIRECTORY:
// MSDN: .NET 3.5+: NotSupportedException: path contains a colon character (:) that is not part of a drive label ("C:\").
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Resources.Unsupported_Path_Format, longPath));
case Win32Errors.ERROR_ACCESS_DENIED:
// Report the parent folder, the inaccessible folder.
var parent = GetParent(folderLp);
NativeError.ThrowException(lastError, null != parent ? parent.FullName : folderLp);
break;
default:
NativeError.ThrowException(lastError, true, folderLp);
break;
}
}
else if (compress)
Device.ToggleCompressionCore(transaction, true, folderLp, true, PathFormat.LongFullPath);
}
// We are not always interested in a new DirectoryInfo instance.
return returnNull ? null : new DirectoryInfo(transaction, longPath, PathFormat.LongFullPath);
}
}
private static Stack<string> ConstructFullPath(KernelTransaction transaction, string path)
{
var longPathPrefix = Path.IsUncPathCore(path, false, false) ? Path.LongPathUncPrefix : Path.LongPathPrefix;
path = Path.GetRegularPathCore(path, GetFullPathOptions.None, false);
var length = path.Length;
if (length >= 2 && Path.IsDVsc(path[length - 1], false))
--length;
var rootLength = Path.GetRootLength(path, false);
if (length == 2 && Path.IsDVsc(path[1], false))
throw new ArgumentException(Resources.Cannot_Create_Directory, "path");
// Check if directories are missing.
var list = new Stack<string>(100);
if (length > rootLength)
{
for (var index = length - 1; index >= rootLength; --index)
{
var path1 = path.Substring(0, index + 1);
var path2 = longPathPrefix + path1.TrimStart('\\');
if (!File.ExistsCore(transaction, true, path2, PathFormat.LongFullPath))
list.Push(path2);
while (index > rootLength && !Path.IsDVsc(path[index], false))
--index;
}
}
return list;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
namespace System.Net
{
internal static class SslStreamPal
{
private const string SecurityPackage = "Microsoft Unified Security Protocol Provider";
private const Interop.Secur32.ContextFlags RequiredFlags =
Interop.Secur32.ContextFlags.ReplayDetect |
Interop.Secur32.ContextFlags.SequenceDetect |
Interop.Secur32.ContextFlags.Confidentiality |
Interop.Secur32.ContextFlags.AllocateMemory;
private const Interop.Secur32.ContextFlags ServerRequiredFlags =
RequiredFlags | Interop.Secur32.ContextFlags.AcceptStream;
public static Exception GetException(SecurityStatusPal status)
{
int win32Code = (int)GetInteropFromSecurityStatusPal(status);
return new Win32Exception(win32Code);
}
public static void VerifyPackageInfo()
{
SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true);
}
public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool remoteCertRequired)
{
Interop.Secur32.ContextFlags unusedAttributes = default(Interop.Secur32.ContextFlags);
int errorCode = SSPIWrapper.AcceptSecurityContext(
GlobalSSPI.SSPISecureChannel,
ref credentialsHandle,
ref context,
ServerRequiredFlags | (remoteCertRequired ? Interop.Secur32.ContextFlags.MutualAuth : Interop.Secur32.ContextFlags.Zero),
Interop.Secur32.Endianness.Native,
inputBuffer,
outputBuffer,
ref unusedAttributes);
return GetSecurityStatusPalFromWin32Int(errorCode);
}
public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer)
{
Interop.Secur32.ContextFlags unusedAttributes = default(Interop.Secur32.ContextFlags);
int errorCode = SSPIWrapper.InitializeSecurityContext(
GlobalSSPI.SSPISecureChannel,
ref credentialsHandle,
ref context,
targetName,
RequiredFlags | Interop.Secur32.ContextFlags.InitManualCredValidation,
Interop.Secur32.Endianness.Native,
inputBuffer,
outputBuffer,
ref unusedAttributes);
return GetSecurityStatusPalFromWin32Int(errorCode);
}
public static SecurityStatusPal InitializeSecurityContext(SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer)
{
Interop.Secur32.ContextFlags unusedAttributes = default(Interop.Secur32.ContextFlags);
int errorCode = SSPIWrapper.InitializeSecurityContext(
GlobalSSPI.SSPISecureChannel,
credentialsHandle,
ref context,
targetName,
RequiredFlags | Interop.Secur32.ContextFlags.InitManualCredValidation,
Interop.Secur32.Endianness.Native,
inputBuffers,
outputBuffer,
ref unusedAttributes);
return GetSecurityStatusPalFromWin32Int(errorCode);
}
public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer)
{
int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer);
Interop.Secur32.SecureCredential.Flags flags;
Interop.Secur32.CredentialUse direction;
if (!isServer)
{
direction = Interop.Secur32.CredentialUse.Outbound;
flags = Interop.Secur32.SecureCredential.Flags.ValidateManual | Interop.Secur32.SecureCredential.Flags.NoDefaultCred;
// CoreFX: always opt-in SCH_USE_STRONG_CRYPTO except for SSL3.
if (((protocolFlags & (Interop.SChannel.SP_PROT_TLS1_0 | Interop.SChannel.SP_PROT_TLS1_1 | Interop.SChannel.SP_PROT_TLS1_2)) != 0)
&& (policy != EncryptionPolicy.AllowNoEncryption) && (policy != EncryptionPolicy.NoEncryption))
{
flags |= Interop.Secur32.SecureCredential.Flags.UseStrongCrypto;
}
}
else
{
direction = Interop.Secur32.CredentialUse.Inbound;
flags = Interop.Secur32.SecureCredential.Flags.Zero;
}
Interop.Secur32.SecureCredential secureCredential = CreateSecureCredential(
Interop.Secur32.SecureCredential.CurrentVersion,
certificate,
flags,
protocolFlags,
policy);
return AcquireCredentialsHandle(direction, secureCredential);
}
public static SecurityStatusPal EncryptMessage(SafeDeleteContext securityContext, byte[] writeBuffer, int size, int headerSize, int trailerSize, out int resultSize)
{
// Encryption using SCHANNEL requires 4 buffers: header, payload, trailer, empty.
SecurityBuffer[] securityBuffer = new SecurityBuffer[4];
securityBuffer[0] = new SecurityBuffer(writeBuffer, 0, headerSize, SecurityBufferType.Header);
securityBuffer[1] = new SecurityBuffer(writeBuffer, headerSize, size, SecurityBufferType.Data);
securityBuffer[2] = new SecurityBuffer(writeBuffer, headerSize + size, trailerSize, SecurityBufferType.Trailer);
securityBuffer[3] = new SecurityBuffer(null, SecurityBufferType.Empty);
int errorCode = SSPIWrapper.EncryptMessage(GlobalSSPI.SSPISecureChannel, securityContext, securityBuffer, 0);
if (errorCode != 0)
{
GlobalLog.Print("SslStreamPal.Windows: SecureChannel#" + Logging.HashString(securityContext) + "::Encrypt ERROR" + errorCode.ToString("x"));
resultSize = 0;
}
else
{
// The full buffer may not be used.
resultSize = securityBuffer[0].size + securityBuffer[1].size + securityBuffer[2].size;
}
return GetSecurityStatusPalFromWin32Int(errorCode);
}
public static SecurityStatusPal DecryptMessage(SafeDeleteContext securityContext, byte[] buffer, ref int offset, ref int count)
{
// Decryption using SCHANNEL requires four buffers.
SecurityBuffer[] decspc = new SecurityBuffer[4];
decspc[0] = new SecurityBuffer(buffer, offset, count, SecurityBufferType.Data);
decspc[1] = new SecurityBuffer(null, SecurityBufferType.Empty);
decspc[2] = new SecurityBuffer(null, SecurityBufferType.Empty);
decspc[3] = new SecurityBuffer(null, SecurityBufferType.Empty);
Interop.SecurityStatus errorCode = (Interop.SecurityStatus)SSPIWrapper.DecryptMessage(
GlobalSSPI.SSPISecureChannel,
securityContext,
decspc,
0);
count = 0;
for (int i = 0; i < decspc.Length; i++)
{
// Successfully decoded data and placed it at the following position in the buffer,
if ((errorCode == Interop.SecurityStatus.OK && decspc[i].type == SecurityBufferType.Data)
// or we failed to decode the data, here is the encoded data.
|| (errorCode != Interop.SecurityStatus.OK && decspc[i].type == SecurityBufferType.Extra))
{
offset = decspc[i].offset;
count = decspc[i].size;
break;
}
}
return GetSecurityStatusPalFromInterop(errorCode);
}
public unsafe static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute)
{
return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.Secur32.ContextAttribute)attribute);
}
public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes)
{
streamSizes = SSPIWrapper.QueryContextAttributes(
GlobalSSPI.SSPISecureChannel,
securityContext,
Interop.Secur32.ContextAttribute.StreamSizes) as StreamSizes;
}
public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo)
{
connectionInfo = SSPIWrapper.QueryContextAttributes(
GlobalSSPI.SSPISecureChannel,
securityContext,
Interop.Secur32.ContextAttribute.ConnectionInfo) as SslConnectionInfo;
}
private static int GetProtocolFlagsFromSslProtocols(SslProtocols protocols, bool isServer)
{
int protocolFlags = (int)protocols;
if (isServer)
{
protocolFlags &= Interop.SChannel.ServerProtocolMask;
}
else
{
protocolFlags &= Interop.SChannel.ClientProtocolMask;
}
return protocolFlags;
}
private static Interop.Secur32.SecureCredential CreateSecureCredential(
int version,
X509Certificate certificate,
Interop.Secur32.SecureCredential.Flags flags,
int protocols, EncryptionPolicy policy)
{
var credential = new Interop.Secur32.SecureCredential() {
rootStore = IntPtr.Zero,
phMappers = IntPtr.Zero,
palgSupportedAlgs = IntPtr.Zero,
certContextArray = IntPtr.Zero,
cCreds = 0,
cMappers = 0,
cSupportedAlgs = 0,
dwSessionLifespan = 0,
reserved = 0
};
if (policy == EncryptionPolicy.RequireEncryption)
{
// Prohibit null encryption cipher.
credential.dwMinimumCipherStrength = 0;
credential.dwMaximumCipherStrength = 0;
}
else if (policy == EncryptionPolicy.AllowNoEncryption)
{
// Allow null encryption cipher in addition to other ciphers.
credential.dwMinimumCipherStrength = -1;
credential.dwMaximumCipherStrength = 0;
}
else if (policy == EncryptionPolicy.NoEncryption)
{
// Suppress all encryption and require null encryption cipher only
credential.dwMinimumCipherStrength = -1;
credential.dwMaximumCipherStrength = -1;
}
else
{
throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), "policy");
}
credential.version = version;
credential.dwFlags = flags;
credential.grbitEnabledProtocols = protocols;
if (certificate != null)
{
credential.certContextArray = certificate.Handle;
credential.cCreds = 1;
}
return credential;
}
//
// Security: we temporarily reset thread token to open the handle under process account.
//
private static SafeFreeCredentials AcquireCredentialsHandle(Interop.Secur32.CredentialUse credUsage, Interop.Secur32.SecureCredential secureCredential)
{
// First try without impersonation, if it fails, then try the process account.
// I.E. We don't know which account the certificate context was created under.
try
{
//
// For app-compat we want to ensure the credential are accessed under >>process<< acount.
//
return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () => {
return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential);
});
}
catch
{
return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential);
}
}
private static SecurityStatusPal GetSecurityStatusPalFromWin32Int(int win32SecurityStatus)
{
return GetSecurityStatusPalFromInterop((Interop.SecurityStatus)win32SecurityStatus);
}
private static SecurityStatusPal GetSecurityStatusPalFromInterop(Interop.SecurityStatus win32SecurityStatus)
{
switch (win32SecurityStatus)
{
case Interop.SecurityStatus.OK:
return SecurityStatusPal.OK;
case Interop.SecurityStatus.ContinueNeeded:
return SecurityStatusPal.ContinueNeeded;
case Interop.SecurityStatus.CompleteNeeded:
return SecurityStatusPal.CompleteNeeded;
case Interop.SecurityStatus.CompAndContinue:
return SecurityStatusPal.CompAndContinue;
case Interop.SecurityStatus.ContextExpired:
return SecurityStatusPal.ContextExpired;
case Interop.SecurityStatus.CredentialsNeeded:
return SecurityStatusPal.CredentialsNeeded;
case Interop.SecurityStatus.Renegotiate:
return SecurityStatusPal.Renegotiate;
case Interop.SecurityStatus.OutOfMemory:
return SecurityStatusPal.OutOfMemory;
case Interop.SecurityStatus.InvalidHandle:
return SecurityStatusPal.InvalidHandle;
case Interop.SecurityStatus.Unsupported:
return SecurityStatusPal.Unsupported;
case Interop.SecurityStatus.TargetUnknown:
return SecurityStatusPal.TargetUnknown;
case Interop.SecurityStatus.InternalError:
return SecurityStatusPal.InternalError;
case Interop.SecurityStatus.PackageNotFound:
return SecurityStatusPal.PackageNotFound;
case Interop.SecurityStatus.NotOwner:
return SecurityStatusPal.NotOwner;
case Interop.SecurityStatus.CannotInstall:
return SecurityStatusPal.CannotInstall;
case Interop.SecurityStatus.InvalidToken:
return SecurityStatusPal.InvalidToken;
case Interop.SecurityStatus.CannotPack:
return SecurityStatusPal.CannotPack;
case Interop.SecurityStatus.QopNotSupported:
return SecurityStatusPal.QopNotSupported;
case Interop.SecurityStatus.NoImpersonation:
return SecurityStatusPal.NoImpersonation;
case Interop.SecurityStatus.LogonDenied:
return SecurityStatusPal.LogonDenied;
case Interop.SecurityStatus.UnknownCredentials:
return SecurityStatusPal.UnknownCredentials;
case Interop.SecurityStatus.NoCredentials:
return SecurityStatusPal.NoCredentials;
case Interop.SecurityStatus.MessageAltered:
return SecurityStatusPal.MessageAltered;
case Interop.SecurityStatus.OutOfSequence:
return SecurityStatusPal.OutOfSequence;
case Interop.SecurityStatus.NoAuthenticatingAuthority:
return SecurityStatusPal.NoAuthenticatingAuthority;
case Interop.SecurityStatus.IncompleteMessage:
return SecurityStatusPal.IncompleteMessage;
case Interop.SecurityStatus.IncompleteCredentials:
return SecurityStatusPal.IncompleteCredentials;
case Interop.SecurityStatus.BufferNotEnough:
return SecurityStatusPal.BufferNotEnough;
case Interop.SecurityStatus.WrongPrincipal:
return SecurityStatusPal.WrongPrincipal;
case Interop.SecurityStatus.TimeSkew:
return SecurityStatusPal.TimeSkew;
case Interop.SecurityStatus.UntrustedRoot:
return SecurityStatusPal.UntrustedRoot;
case Interop.SecurityStatus.IllegalMessage:
return SecurityStatusPal.IllegalMessage;
case Interop.SecurityStatus.CertUnknown:
return SecurityStatusPal.CertUnknown;
case Interop.SecurityStatus.CertExpired:
return SecurityStatusPal.CertExpired;
case Interop.SecurityStatus.AlgorithmMismatch:
return SecurityStatusPal.AlgorithmMismatch;
case Interop.SecurityStatus.SecurityQosFailed:
return SecurityStatusPal.SecurityQosFailed;
case Interop.SecurityStatus.SmartcardLogonRequired:
return SecurityStatusPal.SmartcardLogonRequired;
case Interop.SecurityStatus.UnsupportedPreauth:
return SecurityStatusPal.UnsupportedPreauth;
case Interop.SecurityStatus.BadBinding:
return SecurityStatusPal.BadBinding;
default:
Debug.Fail("Unknown Interop.SecurityStatus value: " + win32SecurityStatus);
throw new InternalException();
}
}
private static Interop.SecurityStatus GetInteropFromSecurityStatusPal(SecurityStatusPal status)
{
switch (status)
{
case SecurityStatusPal.NotSet:
Debug.Fail("SecurityStatus NotSet");
throw new InternalException();
case SecurityStatusPal.OK:
return Interop.SecurityStatus.OK;
case SecurityStatusPal.ContinueNeeded:
return Interop.SecurityStatus.ContinueNeeded;
case SecurityStatusPal.CompleteNeeded:
return Interop.SecurityStatus.CompleteNeeded;
case SecurityStatusPal.CompAndContinue:
return Interop.SecurityStatus.CompAndContinue;
case SecurityStatusPal.ContextExpired:
return Interop.SecurityStatus.ContextExpired;
case SecurityStatusPal.CredentialsNeeded:
return Interop.SecurityStatus.CredentialsNeeded;
case SecurityStatusPal.Renegotiate:
return Interop.SecurityStatus.Renegotiate;
case SecurityStatusPal.OutOfMemory:
return Interop.SecurityStatus.OutOfMemory;
case SecurityStatusPal.InvalidHandle:
return Interop.SecurityStatus.InvalidHandle;
case SecurityStatusPal.Unsupported:
return Interop.SecurityStatus.Unsupported;
case SecurityStatusPal.TargetUnknown:
return Interop.SecurityStatus.TargetUnknown;
case SecurityStatusPal.InternalError:
return Interop.SecurityStatus.InternalError;
case SecurityStatusPal.PackageNotFound:
return Interop.SecurityStatus.PackageNotFound;
case SecurityStatusPal.NotOwner:
return Interop.SecurityStatus.NotOwner;
case SecurityStatusPal.CannotInstall:
return Interop.SecurityStatus.CannotInstall;
case SecurityStatusPal.InvalidToken:
return Interop.SecurityStatus.InvalidToken;
case SecurityStatusPal.CannotPack:
return Interop.SecurityStatus.CannotPack;
case SecurityStatusPal.QopNotSupported:
return Interop.SecurityStatus.QopNotSupported;
case SecurityStatusPal.NoImpersonation:
return Interop.SecurityStatus.NoImpersonation;
case SecurityStatusPal.LogonDenied:
return Interop.SecurityStatus.LogonDenied;
case SecurityStatusPal.UnknownCredentials:
return Interop.SecurityStatus.UnknownCredentials;
case SecurityStatusPal.NoCredentials:
return Interop.SecurityStatus.NoCredentials;
case SecurityStatusPal.MessageAltered:
return Interop.SecurityStatus.MessageAltered;
case SecurityStatusPal.OutOfSequence:
return Interop.SecurityStatus.OutOfSequence;
case SecurityStatusPal.NoAuthenticatingAuthority:
return Interop.SecurityStatus.NoAuthenticatingAuthority;
case SecurityStatusPal.IncompleteMessage:
return Interop.SecurityStatus.IncompleteMessage;
case SecurityStatusPal.IncompleteCredentials:
return Interop.SecurityStatus.IncompleteCredentials;
case SecurityStatusPal.BufferNotEnough:
return Interop.SecurityStatus.BufferNotEnough;
case SecurityStatusPal.WrongPrincipal:
return Interop.SecurityStatus.WrongPrincipal;
case SecurityStatusPal.TimeSkew:
return Interop.SecurityStatus.TimeSkew;
case SecurityStatusPal.UntrustedRoot:
return Interop.SecurityStatus.UntrustedRoot;
case SecurityStatusPal.IllegalMessage:
return Interop.SecurityStatus.IllegalMessage;
case SecurityStatusPal.CertUnknown:
return Interop.SecurityStatus.CertUnknown;
case SecurityStatusPal.CertExpired:
return Interop.SecurityStatus.CertExpired;
case SecurityStatusPal.AlgorithmMismatch:
return Interop.SecurityStatus.AlgorithmMismatch;
case SecurityStatusPal.SecurityQosFailed:
return Interop.SecurityStatus.SecurityQosFailed;
case SecurityStatusPal.SmartcardLogonRequired:
return Interop.SecurityStatus.SmartcardLogonRequired;
case SecurityStatusPal.UnsupportedPreauth:
return Interop.SecurityStatus.UnsupportedPreauth;
case SecurityStatusPal.BadBinding:
return Interop.SecurityStatus.BadBinding;
default:
Debug.Fail("Unknown Interop.SecurityStatus value: " + status);
throw new InternalException();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using NUnit.Framework;
using NUnit.Framework.Constraints;
namespace Integrator.HelloWorld
{
/// <summary>
/// Provides a fluent interface for asserting the raising of exceptions.
/// </summary>
/// <typeparam name="TException">The type of exception to assert.</typeparam>
public static class Exception<TException>
where TException : Exception
{
/// <summary>
/// Asserts that the exception is thrown when the specified action is executed.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <returns></returns>
public static TException ShouldBeThrownBy(Action action)
{
return ShouldBeThrownBy(action, null);
}
/// <summary>
/// Asserts that the exception is thrown when the specified action is executed.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <param name="postCatchAction">The action to execute after the exception has been caught.</param>
/// <returns></returns>
public static TException ShouldBeThrownBy(Action action, Action<Exception> postCatchAction)
{
TException exception = null;
try
{
action();
}
catch (Exception e)
{
exception = e.ShouldBeOfType<TException>();
if(postCatchAction != null)
{
postCatchAction(e);
}
}
exception.ShouldNotBeNull("An exception was expected, but not thrown by the given action.");
return exception;
}
/// <summary>
/// Asserts that the exception was thrown when the specified action is executed by
/// scanning the exception chain.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <returns></returns>
public static TException ShouldExistInExceptionChainAfter(Action action)
{
TException exception = null;
try
{
action();
}
catch (Exception e)
{
exception = ScanExceptionChain(e);
}
return exception;
}
/// <summary>
/// Scans the specified exception chain and asserts the existence of the target exception.
/// </summary>
/// <param name="chainLink">Exception chain to scan.</param>
/// <returns></returns>
private static TException ScanExceptionChain(Exception chainLink)
{
TException exception;
if((exception = chainLink as TException) != null)
{
return exception;
}
if(chainLink.InnerException == null)
{
Assert.Fail("An exception was expected, but not thrown by the given action.");
}
return ScanExceptionChain(chainLink.InnerException);
}
}
public static class SpecificationExtensions
{
public static void ShouldHave<T>(this IEnumerable<T> values, Func<T, bool> func)
{
values.FirstOrDefault(func).ShouldNotBeNull();
}
public static void ShouldBeFalse(this bool condition)
{
Assert.IsFalse(condition);
}
public static void ShouldBeTrue(this bool condition)
{
Assert.IsTrue(condition);
}
public static void ShouldBeTrueBecause(this bool condition, string reason, params object[] args)
{
Assert.IsTrue(condition, reason, args);
}
public static object ShouldEqual(this object actual, object expected)
{
Assert.AreEqual(expected, actual);
return expected;
}
public static object ShouldEqual(this string actual, object expected)
{
Assert.AreEqual((expected != null) ? expected.ToString() : null, actual);
return expected;
}
public static void ShouldMatch(this string actual, string pattern)
{
#pragma warning disable 612,618
Assert.That(actual, Text.Matches(pattern));
#pragma warning restore 612,618
}
public static XmlElement AttributeShouldEqual(this XmlElement element, string attributeName, object expected)
{
Assert.IsNotNull(element, "The Element is null");
string actual = element.GetAttribute(attributeName);
Assert.AreEqual(expected, actual);
return element;
}
public static XmlElement AttributeShouldEqual(this XmlNode node, string attributeName, object expected)
{
var element = node as XmlElement;
Assert.IsNotNull(element, "The Element is null");
string actual = element.GetAttribute(attributeName);
Assert.AreEqual(expected, actual);
return element;
}
public static XmlElement ShouldHaveChild(this XmlElement element, string xpath)
{
var child = element.SelectSingleNode(xpath) as XmlElement;
Assert.IsNotNull(child, "Should have a child element matching " + xpath);
return child;
}
public static XmlElement DoesNotHaveAttribute(this XmlElement element, string attributeName)
{
Assert.IsNotNull(element, "The Element is null");
Assert.IsFalse(element.HasAttribute(attributeName),
"Element should not have an attribute named " + attributeName);
return element;
}
public static object ShouldNotEqual(this object actual, object expected)
{
Assert.AreNotEqual(expected, actual);
return expected;
}
public static void ShouldBeNull(this object anObject)
{
Assert.IsNull(anObject);
}
public static void ShouldNotBeNull(this object anObject)
{
Assert.IsNotNull(anObject);
}
public static void ShouldNotBeNull(this object anObject, string message)
{
Assert.IsNotNull(anObject, message);
}
public static object ShouldBeTheSameAs(this object actual, object expected)
{
Assert.AreSame(expected, actual);
return expected;
}
public static object ShouldNotBeTheSameAs(this object actual, object expected)
{
Assert.AreNotSame(expected, actual);
return expected;
}
public static T ShouldBeOfType<T>(this object actual)
{
actual.ShouldNotBeNull();
actual.ShouldBeOfType(typeof(T));
return (T)actual;
}
public static T As<T>(this object actual)
{
actual.ShouldNotBeNull();
actual.ShouldBeOfType(typeof(T));
return (T)actual;
}
public static object ShouldBeOfType(this object actual, Type expected)
{
#pragma warning disable 612,618
Assert.IsInstanceOfType(expected, actual);
#pragma warning restore 612,618
return actual;
}
public static void ShouldNotBeOfType(this object actual, Type expected)
{
#pragma warning disable 612,618
Assert.IsNotInstanceOfType(expected, actual);
#pragma warning restore 612,618
}
public static void ShouldContain(this IList actual, object expected)
{
Assert.Contains(expected, actual);
}
public static void ShouldContain<T>(this IEnumerable<T> actual, T expected)
{
if (actual.Count(t => t.Equals(expected)) == 0)
{
Assert.Fail("The item '{0}' was not found in the sequence.", expected);
}
}
public static void ShouldNotBeEmpty<T>(this IEnumerable<T> actual)
{
Assert.Greater(actual.Count(), 0, "The list should have at least one element");
}
public static void ShouldNotContain<T>(this IEnumerable<T> actual, T expected)
{
if (actual.Count(t => t.Equals(expected)) > 0)
{
Assert.Fail("The item was found in the sequence it should not be in.");
}
}
public static void ShouldHaveTheSameElementsAs(this IList actual, IList expected)
{
actual.ShouldNotBeNull();
expected.ShouldNotBeNull();
actual.Count.ShouldEqual(expected.Count);
for (int i = 0; i < actual.Count; i++)
{
actual[i].ShouldEqual(expected[i]);
}
}
public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, params T[] expected)
{
ShouldHaveTheSameElementsAs(actual, (IEnumerable<T>)expected);
}
public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, IEnumerable<T> expected)
{
IList actualList = (actual is IList) ? (IList)actual : actual.ToList();
IList expectedList = (expected is IList) ? (IList)expected : expected.ToList();
ShouldHaveTheSameElementsAs(actualList, expectedList);
}
public static void ShouldHaveTheSameElementKeysAs<ELEMENT, KEY>(this IEnumerable<ELEMENT> actual,
IEnumerable expected,
Func<ELEMENT, KEY> keySelector)
{
actual.ShouldNotBeNull();
expected.ShouldNotBeNull();
ELEMENT[] actualArray = actual.ToArray();
object[] expectedArray = expected.Cast<object>().ToArray();
actualArray.Length.ShouldEqual(expectedArray.Length);
for (int i = 0; i < actual.Count(); i++)
{
keySelector(actualArray[i]).ShouldEqual(expectedArray[i]);
}
}
public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2)
{
Assert.Greater(arg1, arg2);
return arg2;
}
public static IComparable ShouldBeLessThan(this IComparable arg1, IComparable arg2)
{
Assert.Less(arg1, arg2);
return arg2;
}
public static void ShouldBeEmpty(this ICollection collection)
{
Assert.IsEmpty(collection);
}
public static void ShouldBeEmpty(this string aString)
{
Assert.IsEmpty(aString);
}
public static void ShouldNotBeEmpty(this ICollection collection)
{
Assert.IsNotEmpty(collection);
}
public static void ShouldNotBeEmpty(this string aString)
{
Assert.IsNotEmpty(aString);
}
public static void ShouldContain(this string actual, string expected)
{
StringAssert.Contains(expected, actual);
}
public static void ShouldContain<T>(this IEnumerable<T> actual, Func<T, bool> expected)
{
actual.Count().ShouldBeGreaterThan(0);
T result = actual.FirstOrDefault(expected);
Assert.That(result, Is.Not.EqualTo(default(T)), "Expected item was not found in the actual sequence");
}
public static void ShouldNotContain(this string actual, string expected)
{
Assert.That(actual, new NotConstraint(new SubstringConstraint(expected)));
}
public static string ShouldBeEqualIgnoringCase(this string actual, string expected)
{
StringAssert.AreEqualIgnoringCase(expected, actual);
return expected;
}
public static void ShouldEndWith(this string actual, string expected)
{
StringAssert.EndsWith(expected, actual);
}
public static void ShouldStartWith(this string actual, string expected)
{
StringAssert.StartsWith(expected, actual);
}
public static void ShouldContainErrorMessage(this Exception exception, string expected)
{
StringAssert.Contains(expected, exception.Message);
}
public static Exception ShouldBeThrownBy(this Type exceptionType, Action action)
{
Exception exception = null;
try
{
action();
}
catch (Exception e)
{
Assert.AreEqual(exceptionType, e.GetType());
exception = e;
}
if (exception == null)
{
Assert.Fail(String.Format("Expected {0} to be thrown.", exceptionType.FullName));
}
return exception;
}
public static void ShouldEqualSqlDate(this DateTime actual, DateTime expected)
{
TimeSpan timeSpan = actual - expected;
Assert.Less(Math.Abs(timeSpan.TotalMilliseconds), 3);
}
public static IEnumerable<T> ShouldHaveCount<T>(this IEnumerable<T> actual, int expected)
{
actual.Count().ShouldEqual(expected);
return actual;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.OCSPResponderBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementOCSPResponderResponderDefinition))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementOCSPResponderSignInformation))]
public partial class ManagementOCSPResponder : iControlInterface {
public ManagementOCSPResponder() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void create(
ManagementOCSPResponderResponderDefinition [] responders
) {
this.Invoke("create", new object [] {
responders});
}
public System.IAsyncResult Begincreate(ManagementOCSPResponderResponderDefinition [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
responders}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_responders
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void delete_all_responders(
) {
this.Invoke("delete_all_responders", new object [0]);
}
public System.IAsyncResult Begindelete_all_responders(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_responders", new object[0], callback, asyncState);
}
public void Enddelete_all_responders(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_responder
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void delete_responder(
string [] responders
) {
this.Invoke("delete_responder", new object [] {
responders});
}
public System.IAsyncResult Begindelete_responder(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_responder", new object[] {
responders}, callback, asyncState);
}
public void Enddelete_responder(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_allow_additional_certificate_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_allow_additional_certificate_state(
string [] responders
) {
object [] results = this.Invoke("get_allow_additional_certificate_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_allow_additional_certificate_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_allow_additional_certificate_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_allow_additional_certificate_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ca_file
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_ca_file(
string [] responders
) {
object [] results = this.Invoke("get_ca_file", new object [] {
responders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_ca_file(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ca_file", new object[] {
responders}, callback, asyncState);
}
public string [] Endget_ca_file(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ca_file_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_ca_file_v2(
string [] responders
) {
object [] results = this.Invoke("get_ca_file_v2", new object [] {
responders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_ca_file_v2(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ca_file_v2", new object[] {
responders}, callback, asyncState);
}
public string [] Endget_ca_file_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ca_path
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_ca_path(
string [] responders
) {
object [] results = this.Invoke("get_ca_path", new object [] {
responders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_ca_path(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ca_path", new object[] {
responders}, callback, asyncState);
}
public string [] Endget_ca_path(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_certificate_check_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_certificate_check_state(
string [] responders
) {
object [] results = this.Invoke("get_certificate_check_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_certificate_check_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_certificate_check_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_certificate_check_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_certificate_id_digest_method
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementOCSPDigestMethod [] get_certificate_id_digest_method(
string [] responders
) {
object [] results = this.Invoke("get_certificate_id_digest_method", new object [] {
responders});
return ((ManagementOCSPDigestMethod [])(results[0]));
}
public System.IAsyncResult Beginget_certificate_id_digest_method(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_certificate_id_digest_method", new object[] {
responders}, callback, asyncState);
}
public ManagementOCSPDigestMethod [] Endget_certificate_id_digest_method(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementOCSPDigestMethod [])(results[0]));
}
//-----------------------------------------------------------------------
// get_certificate_verification_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_certificate_verification_state(
string [] responders
) {
object [] results = this.Invoke("get_certificate_verification_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_certificate_verification_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_certificate_verification_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_certificate_verification_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_chain_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_chain_state(
string [] responders
) {
object [] results = this.Invoke("get_chain_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_chain_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_chain_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_chain_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] responders
) {
object [] results = this.Invoke("get_description", new object [] {
responders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
responders}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_explicit_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_explicit_state(
string [] responders
) {
object [] results = this.Invoke("get_explicit_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_explicit_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_explicit_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_explicit_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ignore_aia_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_ignore_aia_state(
string [] responders
) {
object [] results = this.Invoke("get_ignore_aia_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_ignore_aia_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ignore_aia_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_ignore_aia_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_intern_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_intern_state(
string [] responders
) {
object [] results = this.Invoke("get_intern_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_intern_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_intern_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_intern_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_nonce_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_nonce_state(
string [] responders
) {
object [] results = this.Invoke("get_nonce_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_nonce_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_nonce_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_nonce_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_other_certificate_file
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_other_certificate_file(
string [] responders
) {
object [] results = this.Invoke("get_other_certificate_file", new object [] {
responders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_other_certificate_file(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_other_certificate_file", new object[] {
responders}, callback, asyncState);
}
public string [] Endget_other_certificate_file(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_other_certificate_file_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_other_certificate_file_v2(
string [] responders
) {
object [] results = this.Invoke("get_other_certificate_file_v2", new object [] {
responders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_other_certificate_file_v2(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_other_certificate_file_v2", new object[] {
responders}, callback, asyncState);
}
public string [] Endget_other_certificate_file_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_signature_verification_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_signature_verification_state(
string [] responders
) {
object [] results = this.Invoke("get_signature_verification_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_signature_verification_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_signature_verification_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_signature_verification_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_signing_information
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementOCSPResponderSignInformation [] get_signing_information(
string [] responders
) {
object [] results = this.Invoke("get_signing_information", new object [] {
responders});
return ((ManagementOCSPResponderSignInformation [])(results[0]));
}
public System.IAsyncResult Beginget_signing_information(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_signing_information", new object[] {
responders}, callback, asyncState);
}
public ManagementOCSPResponderSignInformation [] Endget_signing_information(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementOCSPResponderSignInformation [])(results[0]));
}
//-----------------------------------------------------------------------
// get_signing_information_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementOCSPResponderSignInformation [] get_signing_information_v2(
string [] responders
) {
object [] results = this.Invoke("get_signing_information_v2", new object [] {
responders});
return ((ManagementOCSPResponderSignInformation [])(results[0]));
}
public System.IAsyncResult Beginget_signing_information_v2(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_signing_information_v2", new object[] {
responders}, callback, asyncState);
}
public ManagementOCSPResponderSignInformation [] Endget_signing_information_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementOCSPResponderSignInformation [])(results[0]));
}
//-----------------------------------------------------------------------
// get_status_age
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_status_age(
string [] responders
) {
object [] results = this.Invoke("get_status_age", new object [] {
responders});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_status_age(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_status_age", new object[] {
responders}, callback, asyncState);
}
public long [] Endget_status_age(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trust_other_certificate_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_trust_other_certificate_state(
string [] responders
) {
object [] results = this.Invoke("get_trust_other_certificate_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_trust_other_certificate_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trust_other_certificate_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_trust_other_certificate_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_url
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_url(
string [] responders
) {
object [] results = this.Invoke("get_url", new object [] {
responders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_url(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_url", new object[] {
responders}, callback, asyncState);
}
public string [] Endget_url(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_va_file
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_va_file(
string [] responders
) {
object [] results = this.Invoke("get_va_file", new object [] {
responders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_va_file(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_va_file", new object[] {
responders}, callback, asyncState);
}
public string [] Endget_va_file(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_va_file_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_va_file_v2(
string [] responders
) {
object [] results = this.Invoke("get_va_file_v2", new object [] {
responders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_va_file_v2(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_va_file_v2", new object[] {
responders}, callback, asyncState);
}
public string [] Endget_va_file_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_validity_period
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_validity_period(
string [] responders
) {
object [] results = this.Invoke("get_validity_period", new object [] {
responders});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_validity_period(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_validity_period", new object[] {
responders}, callback, asyncState);
}
public long [] Endget_validity_period(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_verification_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_verification_state(
string [] responders
) {
object [] results = this.Invoke("get_verification_state", new object [] {
responders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_verification_state(string [] responders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_verification_state", new object[] {
responders}, callback, asyncState);
}
public CommonEnabledState [] Endget_verification_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// set_allow_additional_certificate_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_allow_additional_certificate_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_allow_additional_certificate_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_allow_additional_certificate_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_allow_additional_certificate_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_allow_additional_certificate_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ca_file
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_ca_file(
string [] responders,
string [] ca_files
) {
this.Invoke("set_ca_file", new object [] {
responders,
ca_files});
}
public System.IAsyncResult Beginset_ca_file(string [] responders,string [] ca_files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ca_file", new object[] {
responders,
ca_files}, callback, asyncState);
}
public void Endset_ca_file(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ca_file_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_ca_file_v2(
string [] responders,
string [] ca_files
) {
this.Invoke("set_ca_file_v2", new object [] {
responders,
ca_files});
}
public System.IAsyncResult Beginset_ca_file_v2(string [] responders,string [] ca_files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ca_file_v2", new object[] {
responders,
ca_files}, callback, asyncState);
}
public void Endset_ca_file_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ca_path
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_ca_path(
string [] responders,
string [] ca_paths
) {
this.Invoke("set_ca_path", new object [] {
responders,
ca_paths});
}
public System.IAsyncResult Beginset_ca_path(string [] responders,string [] ca_paths, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ca_path", new object[] {
responders,
ca_paths}, callback, asyncState);
}
public void Endset_ca_path(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_certificate_check_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_certificate_check_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_certificate_check_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_certificate_check_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_certificate_check_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_certificate_check_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_certificate_id_digest_method
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_certificate_id_digest_method(
string [] responders,
ManagementOCSPDigestMethod [] digest_methods
) {
this.Invoke("set_certificate_id_digest_method", new object [] {
responders,
digest_methods});
}
public System.IAsyncResult Beginset_certificate_id_digest_method(string [] responders,ManagementOCSPDigestMethod [] digest_methods, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_certificate_id_digest_method", new object[] {
responders,
digest_methods}, callback, asyncState);
}
public void Endset_certificate_id_digest_method(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_certificate_verification_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_certificate_verification_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_certificate_verification_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_certificate_verification_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_certificate_verification_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_certificate_verification_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_chain_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_chain_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_chain_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_chain_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_chain_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_chain_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_description(
string [] responders,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
responders,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] responders,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
responders,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_explicit_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_explicit_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_explicit_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_explicit_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_explicit_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_explicit_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ignore_aia_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_ignore_aia_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_ignore_aia_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_ignore_aia_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ignore_aia_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_ignore_aia_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_intern_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_intern_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_intern_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_intern_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_intern_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_intern_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_nonce_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_nonce_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_nonce_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_nonce_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_nonce_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_nonce_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_other_certificate_file
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_other_certificate_file(
string [] responders,
string [] other_files
) {
this.Invoke("set_other_certificate_file", new object [] {
responders,
other_files});
}
public System.IAsyncResult Beginset_other_certificate_file(string [] responders,string [] other_files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_other_certificate_file", new object[] {
responders,
other_files}, callback, asyncState);
}
public void Endset_other_certificate_file(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_other_certificate_file_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_other_certificate_file_v2(
string [] responders,
string [] other_files
) {
this.Invoke("set_other_certificate_file_v2", new object [] {
responders,
other_files});
}
public System.IAsyncResult Beginset_other_certificate_file_v2(string [] responders,string [] other_files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_other_certificate_file_v2", new object[] {
responders,
other_files}, callback, asyncState);
}
public void Endset_other_certificate_file_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_signature_verification_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_signature_verification_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_signature_verification_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_signature_verification_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_signature_verification_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_signature_verification_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_signing_information
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_signing_information(
string [] responders,
ManagementOCSPResponderSignInformation [] signers
) {
this.Invoke("set_signing_information", new object [] {
responders,
signers});
}
public System.IAsyncResult Beginset_signing_information(string [] responders,ManagementOCSPResponderSignInformation [] signers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_signing_information", new object[] {
responders,
signers}, callback, asyncState);
}
public void Endset_signing_information(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_signing_information_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_signing_information_v2(
string [] responders,
ManagementOCSPResponderSignInformation [] signers
) {
this.Invoke("set_signing_information_v2", new object [] {
responders,
signers});
}
public System.IAsyncResult Beginset_signing_information_v2(string [] responders,ManagementOCSPResponderSignInformation [] signers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_signing_information_v2", new object[] {
responders,
signers}, callback, asyncState);
}
public void Endset_signing_information_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_status_age
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_status_age(
string [] responders,
long [] ages
) {
this.Invoke("set_status_age", new object [] {
responders,
ages});
}
public System.IAsyncResult Beginset_status_age(string [] responders,long [] ages, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_status_age", new object[] {
responders,
ages}, callback, asyncState);
}
public void Endset_status_age(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trust_other_certificate_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_trust_other_certificate_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_trust_other_certificate_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_trust_other_certificate_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trust_other_certificate_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_trust_other_certificate_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_url
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_url(
string [] responders,
string [] urls
) {
this.Invoke("set_url", new object [] {
responders,
urls});
}
public System.IAsyncResult Beginset_url(string [] responders,string [] urls, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_url", new object[] {
responders,
urls}, callback, asyncState);
}
public void Endset_url(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_va_file
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_va_file(
string [] responders,
string [] va_files
) {
this.Invoke("set_va_file", new object [] {
responders,
va_files});
}
public System.IAsyncResult Beginset_va_file(string [] responders,string [] va_files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_va_file", new object[] {
responders,
va_files}, callback, asyncState);
}
public void Endset_va_file(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_va_file_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_va_file_v2(
string [] responders,
string [] va_files
) {
this.Invoke("set_va_file_v2", new object [] {
responders,
va_files});
}
public System.IAsyncResult Beginset_va_file_v2(string [] responders,string [] va_files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_va_file_v2", new object[] {
responders,
va_files}, callback, asyncState);
}
public void Endset_va_file_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_validity_period
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_validity_period(
string [] responders,
long [] ranges
) {
this.Invoke("set_validity_period", new object [] {
responders,
ranges});
}
public System.IAsyncResult Beginset_validity_period(string [] responders,long [] ranges, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_validity_period", new object[] {
responders,
ranges}, callback, asyncState);
}
public void Endset_validity_period(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_verification_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/OCSPResponder",
RequestNamespace="urn:iControl:Management/OCSPResponder", ResponseNamespace="urn:iControl:Management/OCSPResponder")]
public void set_verification_state(
string [] responders,
CommonEnabledState [] states
) {
this.Invoke("set_verification_state", new object [] {
responders,
states});
}
public System.IAsyncResult Beginset_verification_state(string [] responders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_verification_state", new object[] {
responders,
states}, callback, asyncState);
}
public void Endset_verification_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.OCSPResponder.ResponderDefinition", Namespace = "urn:iControl")]
public partial class ManagementOCSPResponderResponderDefinition
{
private string nameField;
public string name
{
get { return this.nameField; }
set { this.nameField = value; }
}
private string urlField;
public string url
{
get { return this.urlField; }
set { this.urlField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.OCSPResponder.SignInformation", Namespace = "urn:iControl")]
public partial class ManagementOCSPResponderSignInformation
{
private string signer_certificateField;
public string signer_certificate
{
get { return this.signer_certificateField; }
set { this.signer_certificateField = value; }
}
private string private_keyField;
public string private_key
{
get { return this.private_keyField; }
set { this.private_keyField = value; }
}
private string pass_phraseField;
public string pass_phrase
{
get { return this.pass_phraseField; }
set { this.pass_phraseField = value; }
}
private string other_certificateField;
public string other_certificate
{
get { return this.other_certificateField; }
set { this.other_certificateField = value; }
}
private ManagementOCSPDigestMethod digest_methodField;
public ManagementOCSPDigestMethod digest_method
{
get { return this.digest_methodField; }
set { this.digest_methodField = value; }
}
};
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
// NOTE:
// Currently the managed handler is opt-in on both Windows and Unix, due to still being a nascent implementation
// that's missing features, robustness, perf, etc. One opts into it currently by setting an environment variable,
// which makes it a bit difficult to test. There are two straightforward ways to test it:
// - This file contains test classes that derive from the other test classes in the project that create
// HttpClient{Handler} instances, and in the ctor sets the env var and in Dispose removes the env var.
// That has the effect of running all of those same tests again, but with the managed handler enabled.
// - By setting the env var prior to running tests, every test will implicitly use the managed handler,
// at which point the tests in this file are duplicative and can be commented out.
// For now parallelism is disabled because we use an env var to turn on the managed handler, and the env var
// impacts any tests running concurrently in the process. We can remove this restriction in the future once
// plans around the ManagedHandler are better understood.
[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true, MaxParallelThreads = 1)]
namespace System.Net.Http.Functional.Tests
{
public sealed class ManagedHandler_HttpClientTest : HttpClientTest, IDisposable
{
public ManagedHandler_HttpClientTest() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_DiagnosticsTest : DiagnosticsTest, IDisposable
{
public ManagedHandler_DiagnosticsTest() => ManagedHandlerTestHelpers.SetEnvVar();
public new void Dispose()
{
ManagedHandlerTestHelpers.RemoveEnvVar();
base.Dispose();
}
}
// TODO #21452: Tests on this class fail when the associated condition is enabled.
//public sealed class ManagedHandler_HttpClientEKUTest : HttpClientEKUTest, IDisposable
//{
// public ManagedHandler_HttpClientEKUTest() => ManagedHandlerTestHelpers.SetEnvVar();
// public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
//}
public sealed class ManagedHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_HttpClientHandler_ClientCertificates_Test : HttpClientHandler_ClientCertificates_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public new void Dispose()
{
ManagedHandlerTestHelpers.RemoveEnvVar();
base.Dispose();
}
}
public sealed class ManagedHandler_HttpClientHandler_DefaultProxyCredentials_Test : HttpClientHandler_DefaultProxyCredentials_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_DefaultProxyCredentials_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public new void Dispose()
{
ManagedHandlerTestHelpers.RemoveEnvVar();
base.Dispose();
}
}
public sealed class ManagedHandler_HttpClientHandler_MaxConnectionsPerServer_Test : HttpClientHandler_MaxConnectionsPerServer_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_MaxConnectionsPerServer_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_HttpClientHandler_ServerCertificates_Test : HttpClientHandler_ServerCertificates_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_ServerCertificates_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public new void Dispose()
{
ManagedHandlerTestHelpers.RemoveEnvVar();
base.Dispose();
}
}
public sealed class ManagedHandler_PostScenarioTest : PostScenarioTest, IDisposable
{
public ManagedHandler_PostScenarioTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_ResponseStreamTest : ResponseStreamTest, IDisposable
{
public ManagedHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_SslProtocols_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_SchSendAuxRecordHttpTest : SchSendAuxRecordHttpTest, IDisposable
{
public ManagedHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_HttpClientMiniStress : HttpClientMiniStress, IDisposable
{
public ManagedHandler_HttpClientMiniStress() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
// TODO #21452:
//public sealed class ManagedHandler_DefaultCredentialsTest : DefaultCredentialsTest, IDisposable
//{
// public ManagedHandler_DefaultCredentialsTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
// public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
//}
public sealed class ManagedHandler_HttpClientHandlerTest : HttpClientHandlerTest, IDisposable
{
public ManagedHandler_HttpClientHandlerTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public new void Dispose()
{
ManagedHandlerTestHelpers.RemoveEnvVar();
base.Dispose();
}
}
// TODO #21452: Socket's don't support canceling individual operations, so ReadStream on NetworkStream
// isn't cancelable once the operation has started. We either need to wrap the operation with one that's
// "cancelable", meaning that the underlying operation will still be running even though we've returned "canceled",
// or we need to just recognize that cancellation in such situations can be left up to the caller to do the
// same thing if it's really important.
//public sealed class ManagedHandler_CancellationTest : CancellationTest, IDisposable
//{
// public ManagedHandler_CancellationTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
// public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
//}
// TODO #21452: The managed handler doesn't currently track how much data was written for the response headers.
//public sealed class ManagedHandler_HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientHandler_MaxResponseHeadersLength_Test, IDisposable
//{
// public ManagedHandler_HttpClientHandler_MaxResponseHeadersLength_Test() => ManagedHandlerTestHelpers.SetEnvVar();
// public new void Dispose()
// {
// ManagedHandlerTestHelpers.RemoveEnvVar();
// base.Dispose();
// }
//}
public sealed class ManagedHandler_HttpClientHandler_ConnectionPooling_Test : IDisposable
{
public ManagedHandler_HttpClientHandler_ConnectionPooling_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
// TODO: Currently the subsequent tests sometimes fail/hang with WinHttpHandler / CurlHandler.
// In theory they should pass with any handler that does appropriate connection pooling.
// We should understand why they sometimes fail there and ideally move them to be
// used by all handlers this test project tests.
[Fact]
public async Task MultipleIterativeRequests_SameConnectionReused()
{
using (var client = new HttpClient())
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
var ep = (IPEndPoint)listener.LocalEndPoint;
var uri = new Uri($"http://{ep.Address}:{ep.Port}/");
string responseBody =
"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 0\r\n" +
"\r\n";
Task<string> firstRequest = client.GetStringAsync(uri);
using (Socket server = await listener.AcceptAsync())
using (var serverStream = new NetworkStream(server, ownsSocket: false))
using (var serverReader = new StreamReader(serverStream))
{
while (!string.IsNullOrWhiteSpace(await serverReader.ReadLineAsync()));
await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None);
await firstRequest;
Task<Socket> secondAccept = listener.AcceptAsync(); // shouldn't complete
Task<string> additionalRequest = client.GetStringAsync(uri);
while (!string.IsNullOrWhiteSpace(await serverReader.ReadLineAsync()));
await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None);
await additionalRequest;
Assert.False(secondAccept.IsCompleted, $"Second accept should never complete");
}
}
}
[OuterLoop("Incurs a delay")]
[Fact]
public async Task ServerDisconnectsAfterInitialRequest_SubsequentRequestUsesDifferentConnection()
{
using (var client = new HttpClient())
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(100);
var ep = (IPEndPoint)listener.LocalEndPoint;
var uri = new Uri($"http://{ep.Address}:{ep.Port}/");
string responseBody =
"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 0\r\n" +
"\r\n";
// Make multiple requests iteratively.
for (int i = 0; i < 2; i++)
{
Task<string> request = client.GetStringAsync(uri);
using (Socket server = await listener.AcceptAsync())
using (var serverStream = new NetworkStream(server, ownsSocket: false))
using (var serverReader = new StreamReader(serverStream))
{
while (!string.IsNullOrWhiteSpace(await serverReader.ReadLineAsync()));
await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None);
await request;
server.Shutdown(SocketShutdown.Both);
if (i == 0)
{
await Task.Delay(2000); // give client time to see the closing before next connect
}
}
}
}
}
[Fact]
public async Task ServerSendsConnectionClose_SubsequentRequestUsesDifferentConnection()
{
using (var client = new HttpClient())
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(100);
var ep = (IPEndPoint)listener.LocalEndPoint;
var uri = new Uri($"http://{ep.Address}:{ep.Port}/");
string responseBody =
"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 0\r\n" +
"Connection: close\r\n" +
"\r\n";
// Make multiple requests iteratively.
Task<string> request1 = client.GetStringAsync(uri);
using (Socket server1 = await listener.AcceptAsync())
using (var serverStream1 = new NetworkStream(server1, ownsSocket: false))
using (var serverReader1 = new StreamReader(serverStream1))
{
while (!string.IsNullOrWhiteSpace(await serverReader1.ReadLineAsync()));
await server1.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None);
await request1;
Task<string> request2 = client.GetStringAsync(uri);
using (Socket server2 = await listener.AcceptAsync())
using (var serverStream2 = new NetworkStream(server2, ownsSocket: false))
using (var serverReader2 = new StreamReader(serverStream2))
{
while (!string.IsNullOrWhiteSpace(await serverReader2.ReadLineAsync()));
await server2.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None);
await request2;
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using gView.Framework.Db.UI;
using gView.Framework.Db;
using gView.Framework.UI.Dialogs;
using gView.Framework.Geometry;
using gView.Framework.Data;
using gView.Framework.UI;
namespace gView.DataSources.EventTable.UI
{
public partial class FormEventTableConnection : Form, IConnectionStringDialog
{
public FormEventTableConnection()
{
InitializeComponent();
}
private void getConnectionString_Click(object sender, EventArgs e)
{
DbConnectionString dbConnStr = new DbConnectionString();
dbConnStr.FromString(txtConnectionString.Text);
FormConnectionString dlg = new FormConnectionString(dbConnStr);
dlg.UseProviderInConnectionString = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
dbConnStr = dlg.DbConnectionString;
txtConnectionString.Text = dbConnStr.ToString();
}
}
public DbConnectionString DbConnectionString
{
get
{
DbConnectionString dbConnStr = new DbConnectionString();
dbConnStr.FromString(txtConnectionString.Text);
return dbConnStr;
}
set
{
if (value != null)
txtConnectionString.Text = value.ToString();
}
}
public string TableName
{
get
{
return cmbTable.Text;
}
set { cmbTable.Text = value; }
}
public string IdField
{
get { return cmbID.Text; }
set { cmbID.Text = value; }
}
public string XField
{
get { return cmbX.Text; }
set { cmbX.Text = value; }
}
public string YField
{
get { return cmbY.Text; }
set { cmbY.Text = value; }
}
public ISpatialReference SpatialReference
{
get
{
if (String.IsNullOrEmpty(txtSR.Text)) return null;
SpatialReference sr = new SpatialReference();
sr.FromXmlString(txtSR.Text);
return sr;
}
set
{
if (value == null)
txtSR.Text = String.Empty;
else
txtSR.Text = value.ToXmlString();
}
}
private void btnGetSR_Click(object sender, EventArgs e)
{
FormSpatialReference dlg = new FormSpatialReference(this.SpatialReference);
if (dlg.ShowDialog() == DialogResult.OK)
{
this.SpatialReference = dlg.SpatialReference;
}
}
private void cmbID_DropDown(object sender, EventArgs e)
{
cmbID.Items.Clear();
Fields fields = FilterFields(FieldType.integer);
if (fields != null)
{
foreach (IField field in fields.ToEnumerable())
{
cmbID.Items.Add(field.name);
}
}
}
private void cmbX_DropDown(object sender, EventArgs e)
{
cmbX.Items.Clear();
Fields fields = FilterFields(FieldType.Double);
if (fields != null)
{
foreach (IField field in fields.ToEnumerable())
{
cmbX.Items.Add(field.name);
}
}
}
private void cmbY_DropDown(object sender, EventArgs e)
{
cmbY.Items.Clear();
Fields fields = FilterFields(FieldType.Double);
if (fields != null)
{
foreach (IField field in fields.ToEnumerable())
{
cmbY.Items.Add(field.name);
}
}
}
private void cmbTable_DropDown(object sender, EventArgs e)
{
cmbTable.Items.Clear();
string[] tabNames = TableNames();
if (tabNames != null)
{
foreach (string tabName in tabNames)
{
cmbTable.Items.Add(tabName);
}
}
}
#region Helper
public Fields FilterFields(FieldType fType)
{
try
{
DbConnectionString dbConnStr = this.DbConnectionString;
if (dbConnStr == null) return null;
CommonDbConnection conn = new CommonDbConnection();
conn.ConnectionString2 = dbConnStr.ConnectionString;
if (!conn.GetSchema(this.TableName))
{
MessageBox.Show(conn.errorMessage, "Error");
return null;
}
Fields fields = new Fields(conn.schemaTable);
Fields f = new Fields();
foreach (IField field in fields.ToEnumerable())
{
if (field.type == fType)
f.Add(field);
}
return f;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception");
return null;
}
}
public string[] TableNames()
{
try
{
DbConnectionString dbConnStr = this.DbConnectionString;
if (dbConnStr == null) return null;
CommonDbConnection conn = new CommonDbConnection();
conn.ConnectionString2 = dbConnStr.ConnectionString;
return conn.TableNames();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception");
return null;
}
}
#endregion
#region IConnectionStringDialog Member
public string ShowConnectionStringDialog(string initConnectionString)
{
EventTableConnection conn = new EventTableConnection();
try
{
conn.FromXmlString(initConnectionString);
}
catch { }
this.DbConnectionString = conn.DbConnectionString;
this.TableName = conn.TableName;
this.IdField = conn.IdFieldName;
this.XField = conn.XFieldName;
this.YField = conn.YFieldName;
this.SpatialReference = conn.SpatialReference;
if (this.ShowDialog() == DialogResult.OK)
{
conn = new EventTableConnection(
this.DbConnectionString,
this.TableName,
this.IdField,
this.XField,
this.YField,
this.SpatialReference);
return conn.ToXmlString();
}
return String.Empty;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Threading
{
//
// AsyncLocal<T> represents "ambient" data that is local to a given asynchronous control flow, such as an
// async method. For example, say you want to associate a culture with a given async flow:
//
// static AsyncLocal<Culture> s_currentCulture = new AsyncLocal<Culture>();
//
// static async Task SomeOperationAsync(Culture culture)
// {
// s_currentCulture.Value = culture;
//
// await FooAsync();
// }
//
// static async Task FooAsync()
// {
// PrintStringWithCulture(s_currentCulture.Value);
// }
//
// AsyncLocal<T> also provides optional notifications when the value associated with the current thread
// changes, either because it was explicitly changed by setting the Value property, or implicitly changed
// when the thread encountered an "await" or other context transition. For example, we might want our
// current culture to be communicated to the OS as well:
//
// static AsyncLocal<Culture> s_currentCulture = new AsyncLocal<Culture>(
// args =>
// {
// NativeMethods.SetThreadCulture(args.CurrentValue.LCID);
// });
//
public sealed class AsyncLocal<T> : IAsyncLocal
{
private readonly Action<AsyncLocalValueChangedArgs<T>> m_valueChangedHandler;
//
// Constructs an AsyncLocal<T> that does not receive change notifications.
//
public AsyncLocal()
{
}
//
// Constructs an AsyncLocal<T> with a delegate that is called whenever the current value changes
// on any thread.
//
public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler)
{
m_valueChangedHandler = valueChangedHandler;
}
public T Value
{
get
{
object obj = ExecutionContext.GetLocalValue(this);
return (obj == null) ? default : (T)obj;
}
set
{
ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null);
}
}
void IAsyncLocal.OnValueChanged(object previousValueObj, object currentValueObj, bool contextChanged)
{
Debug.Assert(m_valueChangedHandler != null);
T previousValue = previousValueObj == null ? default : (T)previousValueObj;
T currentValue = currentValueObj == null ? default : (T)currentValueObj;
m_valueChangedHandler(new AsyncLocalValueChangedArgs<T>(previousValue, currentValue, contextChanged));
}
}
//
// Interface to allow non-generic code in ExecutionContext to call into the generic AsyncLocal<T> type.
//
internal interface IAsyncLocal
{
void OnValueChanged(object previousValue, object currentValue, bool contextChanged);
}
public readonly struct AsyncLocalValueChangedArgs<T>
{
public T PreviousValue { get; }
public T CurrentValue { get; }
//
// If the value changed because we changed to a different ExecutionContext, this is true. If it changed
// because someone set the Value property, this is false.
//
public bool ThreadContextChanged { get; }
internal AsyncLocalValueChangedArgs(T previousValue, T currentValue, bool contextChanged)
{
PreviousValue = previousValue;
CurrentValue = currentValue;
ThreadContextChanged = contextChanged;
}
}
//
// Interface used to store an IAsyncLocal => object mapping in ExecutionContext.
// Implementations are specialized based on the number of elements in the immutable
// map in order to minimize memory consumption and look-up times.
//
internal interface IAsyncLocalValueMap
{
bool TryGetValue(IAsyncLocal key, out object value);
IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent);
}
//
// Utility functions for getting/creating instances of IAsyncLocalValueMap
//
internal static class AsyncLocalValueMap
{
public static IAsyncLocalValueMap Empty { get; } = new EmptyAsyncLocalValueMap();
public static bool IsEmpty(IAsyncLocalValueMap asyncLocalValueMap)
{
Debug.Assert(asyncLocalValueMap != null);
Debug.Assert(asyncLocalValueMap == Empty || asyncLocalValueMap.GetType() != typeof(EmptyAsyncLocalValueMap));
return asyncLocalValueMap == Empty;
}
public static IAsyncLocalValueMap Create(IAsyncLocal key, object value, bool treatNullValueAsNonexistent)
{
// If the value isn't null or a null value may not be treated as nonexistent, then create a new one-element map
// to store the key/value pair. Otherwise, use the empty map.
return value != null || !treatNullValueAsNonexistent ?
new OneElementAsyncLocalValueMap(key, value) :
Empty;
}
// Instance without any key/value pairs. Used as a singleton/
private sealed class EmptyAsyncLocalValueMap : IAsyncLocalValueMap
{
public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent)
{
// If the value isn't null or a null value may not be treated as nonexistent, then create a new one-element map
// to store the key/value pair. Otherwise, use the empty map.
return value != null || !treatNullValueAsNonexistent ?
new OneElementAsyncLocalValueMap(key, value) :
(IAsyncLocalValueMap)this;
}
public bool TryGetValue(IAsyncLocal key, out object value)
{
value = null;
return false;
}
}
// Instance with one key/value pair.
private sealed class OneElementAsyncLocalValueMap : IAsyncLocalValueMap
{
private readonly IAsyncLocal _key1;
private readonly object _value1;
public OneElementAsyncLocalValueMap(IAsyncLocal key, object value)
{
_key1 = key; _value1 = value;
}
public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent)
{
if (value != null || !treatNullValueAsNonexistent)
{
// If the key matches one already contained in this map, then create a new one-element map with the updated
// value, otherwise create a two-element map with the additional key/value.
return ReferenceEquals(key, _key1) ?
new OneElementAsyncLocalValueMap(key, value) :
(IAsyncLocalValueMap)new TwoElementAsyncLocalValueMap(_key1, _value1, key, value);
}
else
{
// If the key exists in this map, remove it by downgrading to an empty map. Otherwise, there's nothing to
// add or remove, so just return this map.
return ReferenceEquals(key, _key1) ?
Empty :
(IAsyncLocalValueMap)this;
}
}
public bool TryGetValue(IAsyncLocal key, out object value)
{
if (ReferenceEquals(key, _key1))
{
value = _value1;
return true;
}
else
{
value = null;
return false;
}
}
}
// Instance with two key/value pairs.
private sealed class TwoElementAsyncLocalValueMap : IAsyncLocalValueMap
{
private readonly IAsyncLocal _key1, _key2;
private readonly object _value1, _value2;
public TwoElementAsyncLocalValueMap(IAsyncLocal key1, object value1, IAsyncLocal key2, object value2)
{
_key1 = key1; _value1 = value1;
_key2 = key2; _value2 = value2;
}
public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent)
{
if (value != null || !treatNullValueAsNonexistent)
{
// If the key matches one already contained in this map, then create a new two-element map with the updated
// value, otherwise create a three-element map with the additional key/value.
return
ReferenceEquals(key, _key1) ? new TwoElementAsyncLocalValueMap(key, value, _key2, _value2) :
ReferenceEquals(key, _key2) ? new TwoElementAsyncLocalValueMap(_key1, _value1, key, value) :
(IAsyncLocalValueMap)new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value);
}
else
{
// If the key exists in this map, remove it by downgrading to a one-element map without the key. Otherwise,
// there's nothing to add or remove, so just return this map.
return
ReferenceEquals(key, _key1) ? new OneElementAsyncLocalValueMap(_key2, _value2) :
ReferenceEquals(key, _key2) ? new OneElementAsyncLocalValueMap(_key1, _value1) :
(IAsyncLocalValueMap)this;
}
}
public bool TryGetValue(IAsyncLocal key, out object value)
{
if (ReferenceEquals(key, _key1))
{
value = _value1;
return true;
}
else if (ReferenceEquals(key, _key2))
{
value = _value2;
return true;
}
else
{
value = null;
return false;
}
}
}
// Instance with three key/value pairs.
private sealed class ThreeElementAsyncLocalValueMap : IAsyncLocalValueMap
{
private readonly IAsyncLocal _key1, _key2, _key3;
private readonly object _value1, _value2, _value3;
public ThreeElementAsyncLocalValueMap(IAsyncLocal key1, object value1, IAsyncLocal key2, object value2, IAsyncLocal key3, object value3)
{
_key1 = key1; _value1 = value1;
_key2 = key2; _value2 = value2;
_key3 = key3; _value3 = value3;
}
public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent)
{
if (value != null || !treatNullValueAsNonexistent)
{
// If the key matches one already contained in this map, then create a new three-element map with the
// updated value.
if (ReferenceEquals(key, _key1)) return new ThreeElementAsyncLocalValueMap(key, value, _key2, _value2, _key3, _value3);
if (ReferenceEquals(key, _key2)) return new ThreeElementAsyncLocalValueMap(_key1, _value1, key, value, _key3, _value3);
if (ReferenceEquals(key, _key3)) return new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value);
// The key doesn't exist in this map, so upgrade to a multi map that contains
// the additional key/value pair.
var multi = new MultiElementAsyncLocalValueMap(4);
multi.UnsafeStore(0, _key1, _value1);
multi.UnsafeStore(1, _key2, _value2);
multi.UnsafeStore(2, _key3, _value3);
multi.UnsafeStore(3, key, value);
return multi;
}
else
{
// If the key exists in this map, remove it by downgrading to a two-element map without the key. Otherwise,
// there's nothing to add or remove, so just return this map.
return
ReferenceEquals(key, _key1) ? new TwoElementAsyncLocalValueMap(_key2, _value2, _key3, _value3) :
ReferenceEquals(key, _key2) ? new TwoElementAsyncLocalValueMap(_key1, _value1, _key3, _value3) :
ReferenceEquals(key, _key3) ? new TwoElementAsyncLocalValueMap(_key1, _value1, _key2, _value2) :
(IAsyncLocalValueMap)this;
}
}
public bool TryGetValue(IAsyncLocal key, out object value)
{
if (ReferenceEquals(key, _key1))
{
value = _value1;
return true;
}
else if (ReferenceEquals(key, _key2))
{
value = _value2;
return true;
}
else if (ReferenceEquals(key, _key3))
{
value = _value3;
return true;
}
else
{
value = null;
return false;
}
}
}
// Instance with up to 16 key/value pairs.
private sealed class MultiElementAsyncLocalValueMap : IAsyncLocalValueMap
{
internal const int MaxMultiElements = 16;
private readonly KeyValuePair<IAsyncLocal, object>[] _keyValues;
internal MultiElementAsyncLocalValueMap(int count)
{
Debug.Assert(count <= MaxMultiElements);
_keyValues = new KeyValuePair<IAsyncLocal, object>[count];
}
internal void UnsafeStore(int index, IAsyncLocal key, object value)
{
Debug.Assert(index < _keyValues.Length);
_keyValues[index] = new KeyValuePair<IAsyncLocal, object>(key, value);
}
public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent)
{
// Find the key in this map.
for (int i = 0; i < _keyValues.Length; i++)
{
if (ReferenceEquals(key, _keyValues[i].Key))
{
// The key is in the map.
if (value != null || !treatNullValueAsNonexistent)
{
// Create a new map of the same size that has all of the same pairs, with this new key/value pair
// overwriting the old.
var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length);
Array.Copy(_keyValues, 0, multi._keyValues, 0, _keyValues.Length);
multi._keyValues[i] = new KeyValuePair<IAsyncLocal, object>(key, value);
return multi;
}
else if (_keyValues.Length == 4)
{
// We only have four elements, one of which we're removing, so downgrade to a three-element map,
// without the matching element.
return
i == 0 ? new ThreeElementAsyncLocalValueMap(_keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value) :
i == 1 ? new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value) :
i == 2 ? new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[1].Key, _keyValues[1].Value, _keyValues[3].Key, _keyValues[3].Value) :
(IAsyncLocalValueMap)new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value);
}
else
{
// We have enough elements remaining to warrant a multi map. Create a new one and copy all of the
// elements from this one, except the one to be removed.
var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length - 1);
if (i != 0) Array.Copy(_keyValues, 0, multi._keyValues, 0, i);
if (i != _keyValues.Length - 1) Array.Copy(_keyValues, i + 1, multi._keyValues, i, _keyValues.Length - i - 1);
return multi;
}
}
}
// The key does not already exist in this map.
if (value == null && treatNullValueAsNonexistent)
{
// We can simply return this same map, as there's nothing to add or remove.
return this;
}
// We need to create a new map that has the additional key/value pair.
// If with the addition we can still fit in a multi map, create one.
if (_keyValues.Length < MaxMultiElements)
{
var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length + 1);
Array.Copy(_keyValues, 0, multi._keyValues, 0, _keyValues.Length);
multi._keyValues[_keyValues.Length] = new KeyValuePair<IAsyncLocal, object>(key, value);
return multi;
}
// Otherwise, upgrade to a many map.
var many = new ManyElementAsyncLocalValueMap(MaxMultiElements + 1);
foreach (KeyValuePair<IAsyncLocal, object> pair in _keyValues)
{
many[pair.Key] = pair.Value;
}
many[key] = value;
return many;
}
public bool TryGetValue(IAsyncLocal key, out object value)
{
foreach (KeyValuePair<IAsyncLocal, object> pair in _keyValues)
{
if (ReferenceEquals(key, pair.Key))
{
value = pair.Value;
return true;
}
}
value = null;
return false;
}
}
// Instance with any number of key/value pairs.
private sealed class ManyElementAsyncLocalValueMap : Dictionary<IAsyncLocal, object>, IAsyncLocalValueMap
{
public ManyElementAsyncLocalValueMap(int capacity) : base(capacity) { }
public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent)
{
int count = Count;
bool containsKey = ContainsKey(key);
// If the value being set exists, create a new many map, copy all of the elements from this one,
// and then store the new key/value pair into it. This is the most common case.
if (value != null || !treatNullValueAsNonexistent)
{
var map = new ManyElementAsyncLocalValueMap(count + (containsKey ? 0 : 1));
foreach (KeyValuePair<IAsyncLocal, object> pair in this)
{
map[pair.Key] = pair.Value;
}
map[key] = value;
return map;
}
// Otherwise, the value is null and a null value may be treated as nonexistent. We can downgrade to a smaller
// map rather than storing null.
// If the key is contained in this map, we're going to create a new map that's one pair smaller.
if (containsKey)
{
// If the new count would be within range of a multi map instead of a many map,
// downgrade to the multi map, which uses less memory and is faster to access.
// Otherwise, just create a new many map that's missing this key.
if (count == MultiElementAsyncLocalValueMap.MaxMultiElements + 1)
{
var multi = new MultiElementAsyncLocalValueMap(MultiElementAsyncLocalValueMap.MaxMultiElements);
int index = 0;
foreach (KeyValuePair<IAsyncLocal, object> pair in this)
{
if (!ReferenceEquals(key, pair.Key))
{
multi.UnsafeStore(index++, pair.Key, pair.Value);
}
}
Debug.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements);
return multi;
}
else
{
var map = new ManyElementAsyncLocalValueMap(count - 1);
foreach (KeyValuePair<IAsyncLocal, object> pair in this)
{
if (!ReferenceEquals(key, pair.Key))
{
map[pair.Key] = pair.Value;
}
}
Debug.Assert(map.Count == count - 1);
return map;
}
}
// We were storing null and a null value may be treated as nonexistent, but the key wasn't in the map, so
// there's nothing to change. Just return this instance.
return this;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
internal sealed unsafe class SocketAsyncEngine
{
//
// Encapsulates a particular SocketAsyncContext object's access to a SocketAsyncEngine.
//
public struct Token
{
private readonly SocketAsyncEngine _engine;
private readonly IntPtr _handle;
public Token(SocketAsyncContext context)
{
AllocateToken(context, out _engine, out _handle);
}
public bool WasAllocated
{
get { return _engine != null; }
}
public void Free()
{
if (WasAllocated)
{
_engine.FreeHandle(_handle);
}
}
public bool TryRegister(SafeCloseSocket socket, Interop.Sys.SocketEvents current, Interop.Sys.SocketEvents events, out Interop.Error error)
{
Debug.Assert(WasAllocated, "Expected WasAllocated to be true");
return _engine.TryRegister(socket, current, events, _handle, out error);
}
}
private const int EventBufferCount = 64;
private static readonly object s_lock = new object();
//
// The current engine. We replace this with a new engine when we run out of "handle" values for the current
// engine.
// Must be accessed under s_lock.
//
private static SocketAsyncEngine s_currentEngine;
private readonly IntPtr _port;
private readonly Interop.Sys.SocketEvent* _buffer;
//
// The read and write ends of a native pipe, used to signal that this instance's event loop should stop
// processing events.
//
private readonly int _shutdownReadPipe;
private readonly int _shutdownWritePipe;
//
// Each SocketAsyncContext is associated with a particular "handle" value, used to identify that
// SocketAsyncContext when events are raised. These handle values are never reused, because we do not have
// a way to ensure that we will never see an event for a socket/handle that has been freed. Instead, we
// allocate monotonically increasing handle values up to some limit; when we would exceed that limit,
// we allocate a new SocketAsyncEngine (and thus a new event port) and start the handle values over at zero.
// Thus we can uniquely identify a given SocketAsyncContext by the *pair* {SocketAsyncEngine, handle},
// and avoid any issues with misidentifying the target of an event we read from the port.
//
#if DEBUG
//
// In debug builds, force rollover to new SocketAsyncEngine instances so that code doesn't go untested, since
// it's very unlikely that the "real" limits will ever be reached in test code.
//
private static readonly IntPtr MaxHandles = (IntPtr)(EventBufferCount * 2);
#else
//
// In release builds, we use *very* high limits. No 64-bit process running on release builds should ever
// reach the handle limit for a single event port, and even 32-bit processes should see this only very rarely.
//
private static readonly IntPtr MaxHandles = IntPtr.Size == 4 ? (IntPtr)int.MaxValue : (IntPtr)long.MaxValue;
#endif
//
// Sentinel handle value to identify events from the "shutdown pipe," used to signal an event loop to stop
// processing events.
//
private static readonly IntPtr ShutdownHandle = (IntPtr)(-1);
//
// The next handle value to be allocated for this event port.
// Must be accessed under s_lock.
//
private IntPtr _nextHandle;
//
// Count of handles that have been allocated for this event port, but not yet freed.
// Must be accessed under s_lock.
//
private IntPtr _outstandingHandles;
//
// Maps handle values to SocketAsyncContext instances.
// Must be accessed under s_lock.
//
private readonly Dictionary<IntPtr, SocketAsyncContext> _handleToContextMap = new Dictionary<IntPtr, SocketAsyncContext>();
//
// True if we've reached the handle value limit for this event port, and thus must allocate a new event port
// on the next handle allocation.
//
private bool IsFull { get { return _nextHandle == MaxHandles; } }
//
// Allocates a new {SocketAsyncEngine, handle} pair.
//
private static void AllocateToken(SocketAsyncContext context, out SocketAsyncEngine engine, out IntPtr handle)
{
lock (s_lock)
{
if (s_currentEngine == null)
{
s_currentEngine = new SocketAsyncEngine();
}
engine = s_currentEngine;
handle = s_currentEngine.AllocateHandle(context);
}
}
private IntPtr AllocateHandle(SocketAsyncContext context)
{
Debug.Assert(Monitor.IsEntered(s_lock), "Expected s_lock to be held");
Debug.Assert(!IsFull, "Expected !IsFull");
IntPtr handle = _nextHandle;
_handleToContextMap.Add(handle, context);
_nextHandle = IntPtr.Add(_nextHandle, 1);
_outstandingHandles = IntPtr.Add(_outstandingHandles, 1);
if (IsFull)
{
// We'll need to create a new event port for the next handle.
s_currentEngine = null;
}
Debug.Assert(handle != ShutdownHandle, $"Expected handle != ShutdownHandle: {handle}");
return handle;
}
private void FreeHandle(IntPtr handle)
{
Debug.Assert(handle != ShutdownHandle, $"Expected handle != ShutdownHandle: {handle}");
bool shutdownNeeded = false;
lock (s_lock)
{
if (_handleToContextMap.Remove(handle))
{
_outstandingHandles = IntPtr.Subtract(_outstandingHandles, 1);
Debug.Assert(_outstandingHandles.ToInt64() >= 0, $"Unexpected _outstandingHandles: {_outstandingHandles}");
//
// If we've allocated all possible handles for this instance, and freed them all, then
// we don't need the event loop any more, and can reclaim resources.
//
if (IsFull && _outstandingHandles == IntPtr.Zero)
{
shutdownNeeded = true;
}
}
}
//
// Signal shutdown outside of the lock to reduce contention.
//
if (shutdownNeeded)
{
RequestEventLoopShutdown();
}
}
private SocketAsyncContext GetContextFromHandle(IntPtr handle)
{
Debug.Assert(handle != ShutdownHandle, $"Expected handle != ShutdownHandle: {handle}");
Debug.Assert(handle.ToInt64() < MaxHandles.ToInt64(), $"Unexpected values: handle={handle}, MaxHandles={MaxHandles}");
lock (s_lock)
{
SocketAsyncContext context;
_handleToContextMap.TryGetValue(handle, out context);
return context;
}
}
private SocketAsyncEngine()
{
_port = (IntPtr)(-1);
_shutdownReadPipe = -1;
_shutdownWritePipe = -1;
try
{
//
// Create the event port and buffer
//
if (Interop.Sys.CreateSocketEventPort(out _port) != Interop.Error.SUCCESS)
{
throw new InternalException();
}
if (Interop.Sys.CreateSocketEventBuffer(EventBufferCount, out _buffer) != Interop.Error.SUCCESS)
{
throw new InternalException();
}
//
// Create the pipe for signaling shutdown, and register for "read" events for the pipe. Now writing
// to the pipe will send an event to the event loop.
//
int* pipeFds = stackalloc int[2];
if (Interop.Sys.Pipe(pipeFds, Interop.Sys.PipeFlags.O_CLOEXEC) != 0)
{
throw new InternalException();
}
_shutdownReadPipe = pipeFds[Interop.Sys.ReadEndOfPipe];
_shutdownWritePipe = pipeFds[Interop.Sys.WriteEndOfPipe];
if (Interop.Sys.TryChangeSocketEventRegistration(_port, (IntPtr)_shutdownReadPipe, Interop.Sys.SocketEvents.None, Interop.Sys.SocketEvents.Read, ShutdownHandle) != Interop.Error.SUCCESS)
{
throw new InternalException();
}
//
// Start the event loop on its own thread.
//
Task.Factory.StartNew(
EventLoop,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
catch
{
FreeNativeResources();
throw;
}
}
private void EventLoop()
{
try
{
bool shutdown = false;
while (!shutdown)
{
int numEvents = EventBufferCount;
Interop.Error err = Interop.Sys.WaitForSocketEvents(_port, _buffer, &numEvents);
if (err != Interop.Error.SUCCESS)
{
throw new InternalException();
}
// The native shim is responsible for ensuring this condition.
Debug.Assert(numEvents > 0, $"Unexpected numEvents: {numEvents}");
for (int i = 0; i < numEvents; i++)
{
IntPtr handle = _buffer[i].Data;
if (handle == ShutdownHandle)
{
shutdown = true;
}
else
{
SocketAsyncContext context = GetContextFromHandle(handle);
if (context != null)
{
context.HandleEvents(_buffer[i].Events);
}
}
}
}
FreeNativeResources();
}
catch (Exception e)
{
Environment.FailFast("Exception thrown from SocketAsyncEngine event loop: " + e.ToString(), e);
}
}
private void RequestEventLoopShutdown()
{
//
// Write to the pipe, which will wake up the event loop and cause it to exit.
//
byte b = 1;
int bytesWritten = Interop.Sys.Write(_shutdownWritePipe, &b, 1);
if (bytesWritten != 1)
{
throw new InternalException();
}
}
private void FreeNativeResources()
{
if (_shutdownReadPipe != -1)
{
Interop.Sys.Close((IntPtr)_shutdownReadPipe);
}
if (_shutdownWritePipe != -1)
{
Interop.Sys.Close((IntPtr)_shutdownWritePipe);
}
if (_buffer != null)
{
Interop.Sys.FreeSocketEventBuffer(_buffer);
}
if (_port != (IntPtr)(-1))
{
Interop.Sys.CloseSocketEventPort(_port);
}
}
private bool TryRegister(SafeCloseSocket socket, Interop.Sys.SocketEvents current, Interop.Sys.SocketEvents events, IntPtr handle, out Interop.Error error)
{
if (current == events)
{
error = Interop.Error.SUCCESS;
return true;
}
error = Interop.Sys.TryChangeSocketEventRegistration(_port, socket, current, events, handle);
return error == Interop.Error.SUCCESS;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using System.IO.Ports;
//using System.Diagnostics;
namespace T5CANLib.CAN
{
public enum ReceiveState : int
{
Idle,
RxFrame,
}
/// <summary>
/// CAN232Device is an implementation of ICANDevice for the Lawicel CAN232 device
/// (www.can232.com).
///
/// All incomming messages are published to registered ICANListeners.
/// </summary>
public class CAN232Device : ICANDevice, IDisposable
{
// ReceiveState m_rxstate;
SerialPort m_port = new SerialPort();
//static uint m_deviceHandle = 0;
Thread m_readThread;
Object m_synchObject = new Object();
bool m_endThread = false;
private bool m_DoLogging = false;
private string m_startuppath = @"C:\Program files\Dilemma\CarPCControl";
private int m_baudrate = 57600;
private string m_portnumber = "COM1";
//private bool m_frameAvailable = false;
override public void setPortNumber(string portnumber)
{
Portnumber = portnumber;
}
public override float GetADCValue(uint channel)
{
return 0F;
}
// not supported by lawicel
public override float GetThermoValue()
{
return 0F;
}
public string Portnumber
{
get { return m_portnumber; }
set
{
m_portnumber = value;
if (m_port.IsOpen)
{
m_port.Close();
m_port.PortName = m_portnumber.ToString();
m_port.Open();
}
else
{
m_port.PortName = m_portnumber.ToString();
}
}
}
public int Baudrate
{
get { return m_baudrate; }
set
{
m_baudrate = value;
if (m_port.IsOpen)
{
m_port.Close();
m_port.BaudRate = m_baudrate;
m_port.Open();
}
else
{
m_port.BaudRate = m_baudrate;
}
}
}
public string Startuppath
{
get { return m_startuppath; }
set { m_startuppath = value; }
}
public bool DoLogging
{
get { return m_DoLogging; }
set { m_DoLogging = value; }
}
/// <summary>
/// Constructor for CAN232Device.
/// </summary>
public CAN232Device()
{
m_port.ErrorReceived += new SerialErrorReceivedEventHandler(m_port_ErrorReceived);
m_port.PinChanged += new SerialPinChangedEventHandler(m_port_PinChanged);
m_port.DataReceived += new SerialDataReceivedEventHandler(m_port_DataReceived);
m_port.WriteTimeout = 100;
m_port.ReadTimeout = 100;
m_port.NewLine = "\r";
//m_port.ReceivedBytesThreshold = 1;
/* m_readThread = new Thread(readMessages);
try
{
m_readThread.Priority = ThreadPriority.Normal; // realtime enough
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}*/
}
void m_port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
/*if (e.EventType == SerialData.Chars)
{
int bytesavailable = m_port.BytesToRead;
for (int i = 0; i < bytesavailable; i++)
{
byte rxbyte = (byte)m_port.ReadByte();
switch (m_rxstate)
{
}
}
//m_frameAvailable = true;
}*/
}
void m_port_PinChanged(object sender, SerialPinChangedEventArgs e)
{
}
void m_port_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
}
/// <summary>
/// Destructor for CAN232Device.
/// </summary>
~CAN232Device()
{
lock (m_synchObject)
{
m_endThread = true;
}
close();
}
public enum FlushFlags : byte
{
FLUSH_WAIT = 0,
FLUSH_DONTWAIT = 1,
FLUSH_EMPTY_INQUEUE = 2
}
public override void Delete()
{
}
public void Dispose()
{
}
override public int GetNumberOfAdapters()
{
return 1;
}
override public void EnableLogging(string path2log)
{
m_DoLogging = true;
m_startuppath = path2log;
}
override public void DisableLogging()
{
m_DoLogging = false;
}
override public void clearReceiveBuffer()
{
if (m_port.IsOpen)
{
m_port.DiscardInBuffer();
}
}
override public void clearTransmitBuffer()
{
if (m_port.IsOpen)
{
m_port.DiscardOutBuffer();
}
}
// int thrdcnt = 0;
/// <summary>
/// readMessages is the "run" method of this class. It reads all incomming messages
/// and publishes them to registered ICANListeners.
/// </summary>
public void readMessages()
{
//int readResult = 0;
LAWICEL.CANMsg r_canMsg = new LAWICEL.CANMsg();
CANMessage canMessage = new CANMessage();
while (true)
{
lock (m_synchObject)
{
if (m_endThread)
{
m_endThread = false;
return;
}
}
if (m_port.IsOpen)
{
// read the status?
string line = string.Empty;
m_port.Write("\r");
m_port.Write("A\r"); // poll for all pending CAN messages
//Console.WriteLine("Polled for frames");
Thread.Sleep(0);
bool endofFrames = false;
while(!endofFrames)
{
try
{
line = m_port.ReadLine();
if (line.Length > 0)
{
if (line[0] == '\x07' || line[0] == '\r' || line[0] == 'A')
{
//Console.WriteLine("End of messages");
endofFrames = true;
}
else
{
//t00C8C6003E0000000000
//Console.WriteLine("line: " + line + " len: " + line.Length.ToString());
if (line.Length == 21)
{
// three bytes identifier
r_canMsg.id = (uint)Convert.ToInt32(line.Substring(1, 3), 16);
r_canMsg.len = (byte)Convert.ToInt32(line.Substring(4, 1), 16);
ulong data = 0;
// add all the bytes
data |= (ulong)(byte)Convert.ToInt32(line.Substring(5, 2), 16) ;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(7, 2), 16) << 1 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(9, 2), 16) << 2 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(11, 2), 16) << 3 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(13, 2), 16) << 4 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(15, 2), 16) << 5 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(17, 2), 16) << 6 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(19, 2), 16) << 7 * 8;
r_canMsg.data = data;
canMessage.setID(r_canMsg.id);
canMessage.setLength(r_canMsg.len);
canMessage.setTimeStamp(r_canMsg.timestamp);
canMessage.setFlags(r_canMsg.flags);
canMessage.setData(r_canMsg.data);
if (m_DoLogging)
{
DumpCanMsg(r_canMsg, false);
}
lock (m_listeners)
{
foreach (ICANListener listener in m_listeners)
{
listener.handleMessage(canMessage);
}
}
}
}
}
}
catch (Exception E)
{
//Console.WriteLine("Failed to read frames from CANbus: " + E.Message);
}
Thread.Sleep(0);
}
}
Thread.Sleep(1);
}
}
private string GetCharString(int value)
{
char c = Convert.ToChar(value);
string charstr = c.ToString();
if (c == 0x0d) charstr = "<CR>";
else if (c == 0x0a) charstr = "<LF>";
else if (c == 0x00) charstr = "<NULL>";
else if (c == 0x01) charstr = "<SOH>";
else if (c == 0x02) charstr = "<STX>";
else if (c == 0x03) charstr = "<ETX>";
else if (c == 0x04) charstr = "<EOT>";
else if (c == 0x05) charstr = "<ENQ>";
else if (c == 0x06) charstr = "<ACK>";
else if (c == 0x07) charstr = "<BEL>";
else if (c == 0x08) charstr = "<BS>";
else if (c == 0x09) charstr = "<TAB>";
else if (c == 0x0B) charstr = "<VT>";
else if (c == 0x0C) charstr = "<FF>";
else if (c == 0x0E) charstr = "<SO>";
else if (c == 0x0F) charstr = "<SI>";
else if (c == 0x10) charstr = "<DLE>";
else if (c == 0x11) charstr = "<DC1>";
else if (c == 0x12) charstr = "<DC2>";
else if (c == 0x13) charstr = "<DC3>";
else if (c == 0x14) charstr = "<DC4>";
else if (c == 0x15) charstr = "<NACK>";
else if (c == 0x16) charstr = "<SYN>";
else if (c == 0x17) charstr = "<ETB>";
else if (c == 0x18) charstr = "<CAN>";
else if (c == 0x19) charstr = "<EM>";
else if (c == 0x1A) charstr = "<SUB>";
else if (c == 0x1B) charstr = "<ESC>";
else if (c == 0x1C) charstr = "<FS>";
else if (c == 0x1D) charstr = "<GS>";
else if (c == 0x1E) charstr = "<RS>";
else if (c == 0x1F) charstr = "<US>";
else if (c == 0x7F) charstr = "<DEL>";
return charstr;
}
private void DumpCanMsg(LAWICEL.CANMsg r_canMsg, bool IsTransmit)
{
DateTime dt = DateTime.Now;
try
{
using (StreamWriter sw = new StreamWriter(Path.Combine(m_startuppath, dt.Year.ToString("D4") + dt.Month.ToString("D2") + dt.Day.ToString("D2") + "-CanTrace.log"), true))
{
if (IsTransmit)
{
// get the byte transmitted
int transmitvalue = (int)(r_canMsg.data & 0x000000000000FF00);
transmitvalue /= 256;
sw.WriteLine(dt.ToString("dd/MM/yyyy HH:mm:ss") + " TX: id=" + r_canMsg.id.ToString("D2") + " len= " + r_canMsg.len.ToString("X8") + " data=" + r_canMsg.data.ToString("X16") + " " + r_canMsg.flags.ToString("X2") + " character = " + GetCharString(transmitvalue) + "\t ts: " + r_canMsg.timestamp.ToString("X16") + " flags: " + r_canMsg.flags.ToString("X2"));
}
else
{
// get the byte received
int receivevalue = (int)(r_canMsg.data & 0x0000000000FF0000);
receivevalue /= (256 * 256);
sw.WriteLine(dt.ToString("dd/MM/yyyy HH:mm:ss") + " RX: id=" + r_canMsg.id.ToString("D2") + " len= " + r_canMsg.len.ToString("X8") + " data=" + r_canMsg.data.ToString("X16") + " " + r_canMsg.flags.ToString("X2") + " character = " + GetCharString(receivevalue) + "\t ts: " + r_canMsg.timestamp.ToString("X16") + " flags: " + r_canMsg.flags.ToString("X2"));
}
}
}
catch (Exception E)
{
Console.WriteLine("Failed to write to logfile: " + E.Message);
}
}
/// <summary>
/// The open method tries to connect to both busses to see if one of them is connected and
/// active. The first strategy is to listen for any CAN message. If this fails there is a
/// check to see if the application is started after an interrupted flash session. This is
/// done by sending a message to set address and length (only for P-bus).
/// </summary>
/// <returns>OpenResult.OK is returned on success. Otherwise OpenResult.OpenError is
/// returned.</returns>
override public OpenResult open()
{
Console.WriteLine("Opening port: " + m_portnumber + " in CAN232");
if (m_port.IsOpen)
{
Console.WriteLine("Port was open, closing first");
m_port.Write("\r");
m_port.Write("C\r");
Thread.Sleep(100);
m_port.Close();
}
m_port.BaudRate = m_baudrate;
m_port.PortName = m_portnumber.ToString();
m_port.Handshake = Handshake.None;
Console.WriteLine("Opening comport");
try
{
m_port.Open();
if (m_port.IsOpen)
{
try
{
Console.WriteLine("Setting CAN bitrate");
m_port.Write("\r");
Thread.Sleep(1);
m_port.Write("s4037\r"); // set CAN baudrate to 615 kb/s 0x40:0x37
// now open the CAN channel
Thread.Sleep(100);
if ((byte)m_port.ReadByte() == 0x07) // error
{
Console.WriteLine("Failed to set CAN bitrate to 615 Kb/s");
}
Console.WriteLine("Opening CAN channel");
m_port.Write("\r");
Thread.Sleep(1);
m_port.Write("O\r");
Thread.Sleep(100);
if ((byte)m_port.ReadByte() == 0x07) // error
{
Console.WriteLine("Failed to open CAN channel");
return OpenResult.OpenError;
}
//need to check is channel opened!!!
Console.WriteLine("Creating new reader thread");
m_readThread = new Thread(readMessages);
try
{
m_readThread.Priority = ThreadPriority.Normal; // realtime enough
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
if (m_readThread.ThreadState == ThreadState.Unstarted)
m_readThread.Start();
return OpenResult.OK;
}
catch (Exception E)
{
Console.WriteLine("Failed to set canbaudrate: " + E.Message);
}
try
{
m_port.Close();
}
catch (Exception cE)
{
Console.WriteLine("Failed to close comport: " + cE.Message);
}
return OpenResult.OpenError;
}
}
catch (Exception oE)
{
Console.WriteLine("Failed to open comport: " + oE.Message);
}
return OpenResult.OpenError;
}
/// <summary>
/// The close method closes the CAN232 device.
/// </summary>
/// <returns>CloseResult.OK on success, otherwise CloseResult.CloseError.</returns>
override public CloseResult close()
{
Console.WriteLine("Close called in CAN232Device");
if (m_readThread != null)
{
if (m_readThread.ThreadState != ThreadState.Stopped && m_readThread.ThreadState != ThreadState.StopRequested)
{
lock (m_synchObject)
{
m_endThread = true;
}
// m_readThread.Abort();
}
}
Console.WriteLine("Thread ended");
if (m_port.IsOpen)
{
Console.WriteLine("Thread Closing port (1)");
m_port.Write("\r");
m_port.Write("C\r");
Thread.Sleep(100);
Console.WriteLine("Thread Closing port (2)");
m_port.Close();
Console.WriteLine("Thread Closing port (3)");
return CloseResult.OK;
}
return CloseResult.CloseError;
}
/// <summary>
/// isOpen checks if the device is open.
/// </summary>
/// <returns>true if the device is open, otherwise false.</returns>
override public bool isOpen()
{
return m_port.IsOpen;
}
/// <summary>
/// sendMessage send a CANMessage.
/// </summary>
/// <param name="a_message">A CANMessage.</param>
/// <returns>true on success, othewise false.</returns>
override public bool sendMessage(CANMessage a_message)
{
LAWICEL.CANMsg msg = new LAWICEL.CANMsg();
msg.id = a_message.getID();
msg.len = a_message.getLength();
msg.flags = a_message.getFlags();
msg.data = a_message.getData();
if (m_DoLogging)
{
DumpCanMsg(msg, true);
}
if (m_port.IsOpen)
{
m_port.Write("\r");
string txstring = "t";
txstring += msg.id.ToString("X3");
txstring += "8"; // always 8 bytes to transmit
for (int t = 0; t < 8; t++)
{
byte b = (byte)(((msg.data >> t * 8) & 0x0000000000000000FF));
txstring += b.ToString("X2");
}
txstring += "\r";
m_port.Write(txstring);
// Console.WriteLine("Send: " + txstring);
return true;
}
return false;
/*
int writeResult;
writeResult = LAWICEL.canusb_Write(m_deviceHandle, ref msg);
if (writeResult == LAWICEL.ERROR_CANUSB_OK)
return true;
else
return false;
*/
}
/// <summary>
/// waitForMessage waits for a specific CAN message give by a CAN id.
/// </summary>
/// <param name="a_canID">The CAN id to listen for</param>
/// <param name="timeout">Listen timeout</param>
/// <param name="r_canMsg">The CAN message with a_canID that we where listening for.</param>
/// <returns>The CAN id for the message we where listening for, otherwise 0.</returns>
private uint waitForMessage(uint a_canID, uint timeout, out LAWICEL.CANMsg r_canMsg)
{
CANMessage canMessage = new CANMessage();
string line = string.Empty;
int readResult = 0;
int nrOfWait = 0;
while (nrOfWait < timeout)
{
m_port.Write("\r");
m_port.Write("P\r");
bool endofFrames = false;
while (!endofFrames)
{
Console.WriteLine("reading line");
line = m_port.ReadLine();
Console.WriteLine("line: " + line + " len: " + line.Length.ToString());
if (line[0] == '\x07' || line[0] == '\r' || line[0] == 'A')
{
endofFrames = true;
}
else
{
if (line.Length == 14)
{
// three bytes identifier
r_canMsg = new LAWICEL.CANMsg();
r_canMsg.id = (uint)Convert.ToInt32(line.Substring(1, 3), 16);
r_canMsg.len = (byte)Convert.ToInt32(line.Substring(4, 1), 16);
ulong data = 0;
// add all the bytes
data |= (ulong)(byte)Convert.ToInt32(line.Substring(5, 2), 16) << 7 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(7, 2), 16) << 6 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(9, 2), 16) << 5 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(11, 2), 16) << 4 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(13, 2), 16) << 3 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(15, 2), 16) << 2 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(17, 2), 16) << 1 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(19, 2), 16);
r_canMsg.data = data;
canMessage.setID(r_canMsg.id);
canMessage.setLength(r_canMsg.len);
//canMessage.setTimeStamp(0);
canMessage.setFlags(0);
canMessage.setData(r_canMsg.data);
if (m_DoLogging)
{
DumpCanMsg(r_canMsg, false);
}
if (r_canMsg.id != a_canID)
continue;
return (uint)r_canMsg.id;
}
}
}
Thread.Sleep(1);
nrOfWait++;
}
r_canMsg = new LAWICEL.CANMsg();
return 0;
}
/// <summary>
/// waitAnyMessage waits for any message to be received.
/// </summary>
/// <param name="timeout">Listen timeout</param>
/// <param name="r_canMsg">The CAN message that was first received</param>
/// <returns>The CAN id for the message received, otherwise 0.</returns>
private uint waitAnyMessage(uint timeout, out LAWICEL.CANMsg r_canMsg)
{
CANMessage canMessage = new CANMessage();
string line = string.Empty;
int readResult = 0;
int nrOfWait = 0;
while (nrOfWait < timeout)
{
m_port.Write("\r");
m_port.Write("P\r");
bool endofFrames = false;
while (!endofFrames)
{
Console.WriteLine("reading line");
line = m_port.ReadLine();
Console.WriteLine("line: " + line + " len: " + line.Length.ToString());
if (line[0] == '\x07' || line[0] == '\r' || line[0] == 'A')
{
endofFrames = true;
}
else
{
if (line.Length == 14)
{
// three bytes identifier
r_canMsg = new LAWICEL.CANMsg();
r_canMsg.id = (uint)Convert.ToInt32(line.Substring(1, 3), 16);
r_canMsg.len = (byte)Convert.ToInt32(line.Substring(4, 1), 16);
ulong data = 0;
// add all the bytes
data |= (ulong)(byte)Convert.ToInt32(line.Substring(5, 2), 16) << 7 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(7, 2), 16) << 6 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(9, 2), 16) << 5 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(11, 2), 16) << 4 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(13, 2), 16) << 3 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(15, 2), 16) << 2 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(17, 2), 16) << 1 * 8;
data |= (ulong)(byte)Convert.ToInt32(line.Substring(19, 2), 16);
r_canMsg.data = data;
canMessage.setID(r_canMsg.id);
canMessage.setLength(r_canMsg.len);
//canMessage.setTimeStamp(r_canMsg.timestamp);
canMessage.setFlags(0);
canMessage.setData(r_canMsg.data);
if (m_DoLogging)
{
DumpCanMsg(r_canMsg, false);
}
return (uint)r_canMsg.id;
}
}
}
Thread.Sleep(1);
nrOfWait++;
}
r_canMsg = new LAWICEL.CANMsg();
return 0;
}
}
}
| |
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using k8s.Authentication;
using k8s.Exceptions;
using k8s.KubeConfigModels;
using System.Net;
namespace k8s
{
public partial class KubernetesClientConfiguration
{
/// <summary>
/// kubeconfig Default Location
/// </summary>
public static readonly string KubeConfigDefaultLocation =
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), @".kube\config")
: Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".kube/config");
/// <summary>
/// Gets CurrentContext
/// </summary>
public string CurrentContext { get; private set; }
// For testing
internal static string KubeConfigEnvironmentVariable { get; set; } = "KUBECONFIG";
/// <summary>
/// Initializes a new instance of the <see cref="KubernetesClientConfiguration" /> from default locations
/// If the KUBECONFIG environment variable is set, then that will be used.
/// Next, it looks for a config file at <see cref="KubeConfigDefaultLocation"/>.
/// Then, it checks whether it is executing inside a cluster and will use <see cref="InClusterConfig()" />.
/// Finally, if nothing else exists, it creates a default config with localhost:8080 as host.
/// </summary>
/// <remarks>
/// If multiple kubeconfig files are specified in the KUBECONFIG environment variable,
/// merges the files, where first occurrence wins. See https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#merging-kubeconfig-files.
/// </remarks>
/// <returns>Instance of the<see cref="KubernetesClientConfiguration"/> class</returns>
public static KubernetesClientConfiguration BuildDefaultConfig()
{
var kubeconfig = Environment.GetEnvironmentVariable(KubeConfigEnvironmentVariable);
if (kubeconfig != null)
{
var configList = kubeconfig.Split(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ';' : ':')
.Select((s) => new FileInfo(s.Trim('"')));
var k8sConfig = LoadKubeConfig(configList.ToArray());
return BuildConfigFromConfigObject(k8sConfig);
}
if (File.Exists(KubeConfigDefaultLocation))
{
return BuildConfigFromConfigFile(KubeConfigDefaultLocation);
}
if (IsInCluster())
{
return InClusterConfig();
}
var config = new KubernetesClientConfiguration();
config.Host = "http://localhost:8080";
return config;
}
/// <summary>
/// Initializes a new instance of the <see cref="KubernetesClientConfiguration" /> from config file
/// </summary>
/// <param name="kubeconfigPath">Explicit file path to kubeconfig. Set to null to use the default file path</param>
/// <param name="currentContext">override the context in config file, set null if do not want to override</param>
/// <param name="masterUrl">kube api server endpoint</param>
/// <param name="useRelativePaths">When <see langword="true"/>, the paths in the kubeconfig file will be considered to be relative to the directory in which the kubeconfig
/// file is located. When <see langword="false"/>, the paths will be considered to be relative to the current working directory.</param>
/// <returns>Instance of the<see cref="KubernetesClientConfiguration"/> class</returns>
public static KubernetesClientConfiguration BuildConfigFromConfigFile(
string kubeconfigPath = null,
string currentContext = null, string masterUrl = null, bool useRelativePaths = true)
{
return BuildConfigFromConfigFile(new FileInfo(kubeconfigPath ?? KubeConfigDefaultLocation), currentContext,
masterUrl, useRelativePaths);
}
/// <summary>
/// Initializes a new instance of the <see cref="KubernetesClientConfiguration" /> from config file
/// </summary>
/// <param name="kubeconfig">Fileinfo of the kubeconfig, cannot be null</param>
/// <param name="currentContext">override the context in config file, set null if do not want to override</param>
/// <param name="masterUrl">override the kube api server endpoint, set null if do not want to override</param>
/// <param name="useRelativePaths">When <see langword="true"/>, the paths in the kubeconfig file will be considered to be relative to the directory in which the kubeconfig
/// file is located. When <see langword="false"/>, the paths will be considered to be relative to the current working directory.</param>
/// <returns>Instance of the<see cref="KubernetesClientConfiguration"/> class</returns>
public static KubernetesClientConfiguration BuildConfigFromConfigFile(
FileInfo kubeconfig,
string currentContext = null, string masterUrl = null, bool useRelativePaths = true)
{
return BuildConfigFromConfigFileAsync(kubeconfig, currentContext, masterUrl, useRelativePaths).GetAwaiter()
.GetResult();
}
/// <summary>
/// Initializes a new instance of the <see cref="KubernetesClientConfiguration" /> from config file
/// </summary>
/// <param name="kubeconfig">Fileinfo of the kubeconfig, cannot be null</param>
/// <param name="currentContext">override the context in config file, set null if do not want to override</param>
/// <param name="masterUrl">override the kube api server endpoint, set null if do not want to override</param>
/// <param name="useRelativePaths">When <see langword="true"/>, the paths in the kubeconfig file will be considered to be relative to the directory in which the kubeconfig
/// file is located. When <see langword="false"/>, the paths will be considered to be relative to the current working directory.</param>
/// <returns>Instance of the<see cref="KubernetesClientConfiguration"/> class</returns>
public static async Task<KubernetesClientConfiguration> BuildConfigFromConfigFileAsync(
FileInfo kubeconfig,
string currentContext = null, string masterUrl = null, bool useRelativePaths = true)
{
if (kubeconfig == null)
{
throw new NullReferenceException(nameof(kubeconfig));
}
var k8SConfig = await LoadKubeConfigAsync(kubeconfig, useRelativePaths).ConfigureAwait(false);
var k8SConfiguration = GetKubernetesClientConfiguration(currentContext, masterUrl, k8SConfig);
return k8SConfiguration;
}
/// <summary>
/// Initializes a new instance of the <see cref="KubernetesClientConfiguration" /> from config file
/// </summary>
/// <param name="kubeconfig">Stream of the kubeconfig, cannot be null</param>
/// <param name="currentContext">Override the current context in config, set null if do not want to override</param>
/// <param name="masterUrl">Override the Kubernetes API server endpoint, set null if do not want to override</param>
/// <returns>Instance of the<see cref="KubernetesClientConfiguration"/> class</returns>
public static KubernetesClientConfiguration BuildConfigFromConfigFile(
Stream kubeconfig,
string currentContext = null, string masterUrl = null)
{
return BuildConfigFromConfigFileAsync(kubeconfig, currentContext, masterUrl).GetAwaiter().GetResult();
}
/// <summary>
/// Initializes a new instance of the <see cref="KubernetesClientConfiguration" /> from config file
/// </summary>
/// <param name="kubeconfig">Stream of the kubeconfig, cannot be null</param>
/// <param name="currentContext">Override the current context in config, set null if do not want to override</param>
/// <param name="masterUrl">Override the Kubernetes API server endpoint, set null if do not want to override</param>
/// <returns>Instance of the<see cref="KubernetesClientConfiguration"/> class</returns>
public static async Task<KubernetesClientConfiguration> BuildConfigFromConfigFileAsync(
Stream kubeconfig,
string currentContext = null, string masterUrl = null)
{
if (kubeconfig == null)
{
throw new NullReferenceException(nameof(kubeconfig));
}
if (!kubeconfig.CanSeek)
{
throw new Exception("Stream don't support seeking!");
}
kubeconfig.Position = 0;
var k8SConfig = await Yaml.LoadFromStreamAsync<K8SConfiguration>(kubeconfig).ConfigureAwait(false);
var k8SConfiguration = GetKubernetesClientConfiguration(currentContext, masterUrl, k8SConfig);
return k8SConfiguration;
}
/// <summary>
/// Initializes a new instance of <see cref="KubernetesClientConfiguration"/> from pre-loaded config object.
/// </summary>
/// <param name="k8SConfig">A <see cref="K8SConfiguration"/>, for example loaded from <see cref="LoadKubeConfigAsync(string, bool)" /></param>
/// <param name="currentContext">Override the current context in config, set null if do not want to override</param>
/// <param name="masterUrl">Override the Kubernetes API server endpoint, set null if do not want to override</param>
/// <returns>Instance of the<see cref="KubernetesClientConfiguration"/> class</returns>
public static KubernetesClientConfiguration BuildConfigFromConfigObject(
K8SConfiguration k8SConfig,
string currentContext = null, string masterUrl = null)
=> GetKubernetesClientConfiguration(currentContext, masterUrl, k8SConfig);
private static KubernetesClientConfiguration GetKubernetesClientConfiguration(
string currentContext,
string masterUrl, K8SConfiguration k8SConfig)
{
if (k8SConfig == null)
{
throw new ArgumentNullException(nameof(k8SConfig));
}
var k8SConfiguration = new KubernetesClientConfiguration();
currentContext = currentContext ?? k8SConfig.CurrentContext;
// only init context if context is set
if (currentContext != null)
{
k8SConfiguration.InitializeContext(k8SConfig, currentContext);
}
if (!string.IsNullOrWhiteSpace(masterUrl))
{
k8SConfiguration.Host = masterUrl;
}
if (string.IsNullOrWhiteSpace(k8SConfiguration.Host))
{
throw new KubeConfigException("Cannot infer server host url either from context or masterUrl");
}
return k8SConfiguration;
}
/// <summary>
/// Validates and Initializes Client Configuration
/// </summary>
/// <param name="k8SConfig">Kubernetes Configuration</param>
/// <param name="currentContext">Current Context</param>
private void InitializeContext(K8SConfiguration k8SConfig, string currentContext)
{
// current context
var activeContext =
k8SConfig.Contexts.FirstOrDefault(
c => c.Name.Equals(currentContext, StringComparison.OrdinalIgnoreCase));
if (activeContext == null)
{
throw new KubeConfigException($"CurrentContext: {currentContext} not found in contexts in kubeconfig");
}
if (string.IsNullOrEmpty(activeContext.ContextDetails?.Cluster))
{
// This serves as validation for any of the properties of ContextDetails being set.
// Other locations in code assume that ContextDetails is non-null.
throw new KubeConfigException($"Cluster not set for context `{currentContext}` in kubeconfig");
}
CurrentContext = activeContext.Name;
// cluster
SetClusterDetails(k8SConfig, activeContext);
// user
SetUserDetails(k8SConfig, activeContext);
// namespace
Namespace = activeContext.ContextDetails?.Namespace;
}
private void SetClusterDetails(K8SConfiguration k8SConfig, Context activeContext)
{
var clusterDetails =
k8SConfig.Clusters.FirstOrDefault(c => c.Name.Equals(
activeContext.ContextDetails.Cluster,
StringComparison.OrdinalIgnoreCase));
if (clusterDetails?.ClusterEndpoint == null)
{
throw new KubeConfigException($"Cluster not found for context `{activeContext}` in kubeconfig");
}
if (string.IsNullOrWhiteSpace(clusterDetails.ClusterEndpoint.Server))
{
throw new KubeConfigException($"Server not found for current-context `{activeContext}` in kubeconfig");
}
Host = clusterDetails.ClusterEndpoint.Server;
SkipTlsVerify = clusterDetails.ClusterEndpoint.SkipTlsVerify;
if (!Uri.TryCreate(Host, UriKind.Absolute, out var uri))
{
throw new KubeConfigException($"Bad server host URL `{Host}` (cannot be parsed)");
}
if (IPAddress.TryParse(uri.Host, out var ipAddress))
{
if (IPAddress.Equals(IPAddress.Any, ipAddress))
{
var builder = new UriBuilder(Host);
builder.Host = $"{IPAddress.Loopback}";
Host = builder.ToString();
}
else if (IPAddress.Equals(IPAddress.IPv6Any, ipAddress))
{
var builder = new UriBuilder(Host);
builder.Host = $"{IPAddress.IPv6Loopback}";
Host = builder.ToString();
}
}
if (uri.Scheme == "https")
{
if (!string.IsNullOrEmpty(clusterDetails.ClusterEndpoint.CertificateAuthorityData))
{
var data = clusterDetails.ClusterEndpoint.CertificateAuthorityData;
SslCaCerts = new X509Certificate2Collection(new X509Certificate2(Convert.FromBase64String(data)));
}
else if (!string.IsNullOrEmpty(clusterDetails.ClusterEndpoint.CertificateAuthority))
{
SslCaCerts = new X509Certificate2Collection(new X509Certificate2(GetFullPath(
k8SConfig,
clusterDetails.ClusterEndpoint.CertificateAuthority)));
}
}
}
private void SetUserDetails(K8SConfiguration k8SConfig, Context activeContext)
{
if (string.IsNullOrWhiteSpace(activeContext.ContextDetails.User))
{
return;
}
var userDetails = k8SConfig.Users.FirstOrDefault(c => c.Name.Equals(
activeContext.ContextDetails.User,
StringComparison.OrdinalIgnoreCase));
if (userDetails == null)
{
throw new KubeConfigException($"User not found for context {activeContext.Name} in kubeconfig");
}
if (userDetails.UserCredentials == null)
{
throw new KubeConfigException($"User credentials not found for user: {userDetails.Name} in kubeconfig");
}
var userCredentialsFound = false;
// Basic and bearer tokens are mutually exclusive
if (!string.IsNullOrWhiteSpace(userDetails.UserCredentials.Token))
{
AccessToken = userDetails.UserCredentials.Token;
userCredentialsFound = true;
}
else if (!string.IsNullOrWhiteSpace(userDetails.UserCredentials.UserName) &&
!string.IsNullOrWhiteSpace(userDetails.UserCredentials.Password))
{
Username = userDetails.UserCredentials.UserName;
Password = userDetails.UserCredentials.Password;
userCredentialsFound = true;
}
// Token and cert based auth can co-exist
if (!string.IsNullOrWhiteSpace(userDetails.UserCredentials.ClientCertificateData) &&
!string.IsNullOrWhiteSpace(userDetails.UserCredentials.ClientKeyData))
{
ClientCertificateData = userDetails.UserCredentials.ClientCertificateData;
ClientCertificateKeyData = userDetails.UserCredentials.ClientKeyData;
userCredentialsFound = true;
}
if (!string.IsNullOrWhiteSpace(userDetails.UserCredentials.ClientCertificate) &&
!string.IsNullOrWhiteSpace(userDetails.UserCredentials.ClientKey))
{
ClientCertificateFilePath = GetFullPath(k8SConfig, userDetails.UserCredentials.ClientCertificate);
ClientKeyFilePath = GetFullPath(k8SConfig, userDetails.UserCredentials.ClientKey);
userCredentialsFound = true;
}
if (userDetails.UserCredentials.AuthProvider != null)
{
if (userDetails.UserCredentials.AuthProvider.Config != null
&& (userDetails.UserCredentials.AuthProvider.Config.ContainsKey("access-token")
|| userDetails.UserCredentials.AuthProvider.Config.ContainsKey("id-token")))
{
switch (userDetails.UserCredentials.AuthProvider.Name)
{
case "azure":
{
var config = userDetails.UserCredentials.AuthProvider.Config;
if (config.ContainsKey("expires-on"))
{
var expiresOn = int.Parse(config["expires-on"]);
DateTimeOffset expires;
expires = DateTimeOffset.FromUnixTimeSeconds(expiresOn);
if (DateTimeOffset.Compare(
expires,
DateTimeOffset.Now)
<= 0)
{
var tenantId = config["tenant-id"];
var clientId = config["client-id"];
var apiServerId = config["apiserver-id"];
var refresh = config["refresh-token"];
var newToken = RenewAzureToken(
tenantId,
clientId,
apiServerId,
refresh);
config["access-token"] = newToken;
}
}
AccessToken = config["access-token"];
userCredentialsFound = true;
break;
}
case "gcp":
{
// config
var config = userDetails.UserCredentials.AuthProvider.Config;
TokenProvider = new GcpTokenProvider(config["cmd-path"]);
userCredentialsFound = true;
break;
}
case "oidc":
{
var config = userDetails.UserCredentials.AuthProvider.Config;
AccessToken = config["id-token"];
if (config.ContainsKey("client-id")
&& config.ContainsKey("idp-issuer-url")
&& config.ContainsKey("id-token")
&& config.ContainsKey("refresh-token"))
{
string clientId = config["client-id"];
string clientSecret = config.ContainsKey("client-secret") ? config["client-secret"] : null;
string idpIssuerUrl = config["idp-issuer-url"];
string idToken = config["id-token"];
string refreshToken = config["refresh-token"];
TokenProvider = new OidcTokenProvider(clientId, clientSecret, idpIssuerUrl, idToken, refreshToken);
userCredentialsFound = true;
}
break;
}
}
}
}
if (userDetails.UserCredentials.ExternalExecution != null)
{
if (string.IsNullOrWhiteSpace(userDetails.UserCredentials.ExternalExecution.Command))
{
throw new KubeConfigException(
"External command execution to receive user credentials must include a command to execute");
}
if (string.IsNullOrWhiteSpace(userDetails.UserCredentials.ExternalExecution.ApiVersion))
{
throw new KubeConfigException("External command execution missing ApiVersion key");
}
var response = ExecuteExternalCommand(userDetails.UserCredentials.ExternalExecution);
AccessToken = response.Status.Token;
// When reading ClientCertificateData from a config file it will be base64 encoded, and code later in the system (see CertUtils.GeneratePfx)
// expects ClientCertificateData and ClientCertificateKeyData to be base64 encoded because of this. However the string returned by external
// auth providers is the raw certificate and key PEM text, so we need to take that and base64 encoded it here so it can be decoded later.
ClientCertificateData = response.Status.ClientCertificateData == null ? null : Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(response.Status.ClientCertificateData));
ClientCertificateKeyData = response.Status.ClientKeyData == null ? null : Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(response.Status.ClientKeyData));
userCredentialsFound = true;
// TODO: support client certificates here too.
if (AccessToken != null)
{
TokenProvider = new ExecTokenProvider(userDetails.UserCredentials.ExternalExecution);
}
}
if (!userCredentialsFound)
{
throw new KubeConfigException(
$"User: {userDetails.Name} does not have appropriate auth credentials in kubeconfig");
}
}
public static string RenewAzureToken(string tenantId, string clientId, string apiServerId, string refresh)
{
throw new KubeConfigException("Refresh not supported.");
}
public static Process CreateRunnableExternalProcess(ExternalExecution config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
var execInfo = new Dictionary<string, dynamic>
{
{ "apiVersion", config.ApiVersion },
{ "kind", "ExecCredentials" },
{ "spec", new Dictionary<string, bool> { { "interactive", Environment.UserInteractive } } },
};
var process = new Process();
process.StartInfo.EnvironmentVariables.Add("KUBERNETES_EXEC_INFO", JsonSerializer.Serialize(execInfo));
if (config.EnvironmentVariables != null)
{
foreach (var configEnvironmentVariable in config.EnvironmentVariables)
{
if (configEnvironmentVariable.ContainsKey("name") && configEnvironmentVariable.ContainsKey("value"))
{
var name = configEnvironmentVariable["name"];
process.StartInfo.EnvironmentVariables[name] = configEnvironmentVariable["value"];
}
else
{
var badVariable = string.Join(",", configEnvironmentVariable.Select(x => $"{x.Key}={x.Value}"));
throw new KubeConfigException($"Invalid environment variable defined: {badVariable}");
}
}
}
process.StartInfo.FileName = config.Command;
if (config.Arguments != null)
{
process.StartInfo.Arguments = string.Join(" ", config.Arguments);
}
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
return process;
}
/// <summary>
/// Implementation of the proposal for out-of-tree client
/// authentication providers as described here --
/// https://github.com/kubernetes/community/blob/master/contributors/design-proposals/auth/kubectl-exec-plugins.md
/// Took inspiration from python exec_provider.py --
/// https://github.com/kubernetes-client/python-base/blob/master/config/exec_provider.py
/// </summary>
/// <param name="config">The external command execution configuration</param>
/// <returns>
/// The token, client certificate data, and the client key data received from the external command execution
/// </returns>
public static ExecCredentialResponse ExecuteExternalCommand(ExternalExecution config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
var process = CreateRunnableExternalProcess(config);
try
{
process.Start();
}
catch (Exception ex)
{
throw new KubeConfigException($"external exec failed due to: {ex.Message}");
}
var stdout = process.StandardOutput.ReadToEnd();
var stderr = process.StandardError.ReadToEnd();
if (string.IsNullOrWhiteSpace(stderr) == false)
{
throw new KubeConfigException($"external exec failed due to: {stderr}");
}
// Wait for a maximum of 5 seconds, if a response takes longer probably something went wrong...
process.WaitForExit(5);
try
{
var responseObject = KubernetesJson.Deserialize<ExecCredentialResponse>(stdout);
if (responseObject == null || responseObject.ApiVersion != config.ApiVersion)
{
throw new KubeConfigException(
$"external exec failed because api version {responseObject.ApiVersion} does not match {config.ApiVersion}");
}
if (responseObject.Status.IsValid())
{
return responseObject;
}
else
{
throw new KubeConfigException($"external exec failed missing token or clientCertificateData field in plugin output");
}
}
catch (JsonException ex)
{
throw new KubeConfigException($"external exec failed due to failed deserialization process: {ex}");
}
catch (Exception ex)
{
throw new KubeConfigException($"external exec failed due to uncaught exception: {ex}");
}
}
/// <summary>
/// Loads entire Kube Config from default or explicit file path
/// </summary>
/// <param name="kubeconfigPath">Explicit file path to kubeconfig. Set to null to use the default file path</param>
/// <param name="useRelativePaths">When <see langword="true"/>, the paths in the kubeconfig file will be considered to be relative to the directory in which the kubeconfig
/// file is located. When <see langword="false"/>, the paths will be considered to be relative to the current working directory.</param>
/// <returns>Instance of the <see cref="K8SConfiguration"/> class</returns>
public static async Task<K8SConfiguration> LoadKubeConfigAsync(
string kubeconfigPath = null,
bool useRelativePaths = true)
{
var fileInfo = new FileInfo(kubeconfigPath ?? KubeConfigDefaultLocation);
return await LoadKubeConfigAsync(fileInfo, useRelativePaths).ConfigureAwait(false);
}
/// <summary>
/// Loads entire Kube Config from default or explicit file path
/// </summary>
/// <param name="kubeconfigPath">Explicit file path to kubeconfig. Set to null to use the default file path</param>
/// <param name="useRelativePaths">When <see langword="true"/>, the paths in the kubeconfig file will be considered to be relative to the directory in which the kubeconfig
/// file is located. When <see langword="false"/>, the paths will be considered to be relative to the current working directory.</param>
/// <returns>Instance of the <see cref="K8SConfiguration"/> class</returns>
public static K8SConfiguration LoadKubeConfig(string kubeconfigPath = null, bool useRelativePaths = true)
{
return LoadKubeConfigAsync(kubeconfigPath, useRelativePaths).GetAwaiter().GetResult();
}
/// <summary>
/// Loads Kube Config
/// </summary>
/// <param name="kubeconfig">Kube config file contents</param>
/// <param name="useRelativePaths">When <see langword="true"/>, the paths in the kubeconfig file will be considered to be relative to the directory in which the kubeconfig
/// file is located. When <see langword="false"/>, the paths will be considered to be relative to the current working directory.</param>
/// <returns>Instance of the <see cref="K8SConfiguration"/> class</returns>
public static async Task<K8SConfiguration> LoadKubeConfigAsync(
FileInfo kubeconfig,
bool useRelativePaths = true)
{
if (kubeconfig == null)
{
throw new ArgumentNullException(nameof(kubeconfig));
}
if (!kubeconfig.Exists)
{
throw new KubeConfigException($"kubeconfig file not found at {kubeconfig.FullName}");
}
using (var stream = kubeconfig.OpenRead())
{
var config = await Yaml.LoadFromStreamAsync<K8SConfiguration>(stream).ConfigureAwait(false);
if (useRelativePaths)
{
config.FileName = kubeconfig.FullName;
}
return config;
}
}
/// <summary>
/// Loads Kube Config
/// </summary>
/// <param name="kubeconfig">Kube config file contents</param>
/// <param name="useRelativePaths">When <see langword="true"/>, the paths in the kubeconfig file will be considered to be relative to the directory in which the kubeconfig
/// file is located. When <see langword="false"/>, the paths will be considered to be relative to the current working directory.</param>
/// <returns>Instance of the <see cref="K8SConfiguration"/> class</returns>
public static K8SConfiguration LoadKubeConfig(FileInfo kubeconfig, bool useRelativePaths = true)
{
return LoadKubeConfigAsync(kubeconfig, useRelativePaths).GetAwaiter().GetResult();
}
/// <summary>
/// Loads Kube Config
/// </summary>
/// <param name="kubeconfigStream">Kube config file contents stream</param>
/// <returns>Instance of the <see cref="K8SConfiguration"/> class</returns>
public static async Task<K8SConfiguration> LoadKubeConfigAsync(Stream kubeconfigStream)
{
return await Yaml.LoadFromStreamAsync<K8SConfiguration>(kubeconfigStream).ConfigureAwait(false);
}
/// <summary>
/// Loads Kube Config
/// </summary>
/// <param name="kubeconfigStream">Kube config file contents stream</param>
/// <returns>Instance of the <see cref="K8SConfiguration"/> class</returns>
public static K8SConfiguration LoadKubeConfig(Stream kubeconfigStream)
{
return LoadKubeConfigAsync(kubeconfigStream).GetAwaiter().GetResult();
}
/// <summary>
/// Loads Kube Config
/// </summary>
/// <param name="kubeConfigs">List of kube config file contents</param>
/// <param name="useRelativePaths">When <see langword="true"/>, the paths in the kubeconfig file will be considered to be relative to the directory in which the kubeconfig
/// file is located. When <see langword="false"/>, the paths will be considered to be relative to the current working directory.</param>
/// <returns>Instance of the <see cref="K8SConfiguration"/> class</returns>
/// <remarks>
/// The kube config files will be merges into a single <see cref="K8SConfiguration"/>, where first occurrence wins.
/// See https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#merging-kubeconfig-files.
/// </remarks>
internal static K8SConfiguration LoadKubeConfig(FileInfo[] kubeConfigs, bool useRelativePaths = true)
{
return LoadKubeConfigAsync(kubeConfigs, useRelativePaths).GetAwaiter().GetResult();
}
/// <summary>
/// Loads Kube Config
/// </summary>
/// <param name="kubeConfigs">List of kube config file contents</param>
/// <param name="useRelativePaths">When <see langword="true"/>, the paths in the kubeconfig file will be considered to be relative to the directory in which the kubeconfig
/// file is located. When <see langword="false"/>, the paths will be considered to be relative to the current working directory.</param>
/// <returns>Instance of the <see cref="K8SConfiguration"/> class</returns>
/// <remarks>
/// The kube config files will be merges into a single <see cref="K8SConfiguration"/>, where first occurrence wins.
/// See https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#merging-kubeconfig-files.
/// </remarks>
internal static async Task<K8SConfiguration> LoadKubeConfigAsync(
FileInfo[] kubeConfigs,
bool useRelativePaths = true)
{
var basek8SConfig = await LoadKubeConfigAsync(kubeConfigs[0], useRelativePaths).ConfigureAwait(false);
for (var i = 1; i < kubeConfigs.Length; i++)
{
var mergek8SConfig = await LoadKubeConfigAsync(kubeConfigs[i], useRelativePaths).ConfigureAwait(false);
MergeKubeConfig(basek8SConfig, mergek8SConfig);
}
return basek8SConfig;
}
/// <summary>
/// Tries to get the full path to a file referenced from the Kubernetes configuration.
/// </summary>
/// <param name="configuration">
/// The Kubernetes configuration.
/// </param>
/// <param name="path">
/// The path to resolve.
/// </param>
/// <returns>
/// When possible a fully qualified path to the file.
/// </returns>
/// <remarks>
/// For example, if the configuration file is at "C:\Users\me\kube.config" and path is "ca.crt",
/// this will return "C:\Users\me\ca.crt". Similarly, if path is "D:\ca.cart", this will return
/// "D:\ca.crt".
/// </remarks>
private static string GetFullPath(K8SConfiguration configuration, string path)
{
// If we don't have a file name,
if (string.IsNullOrWhiteSpace(configuration.FileName) || Path.IsPathRooted(path))
{
return path;
}
else
{
return Path.Combine(Path.GetDirectoryName(configuration.FileName), path);
}
}
/// <summary>
/// Merges kube config files together, preferring configuration present in the base config over the merge config.
/// </summary>
/// <param name="basek8SConfig">The <see cref="K8SConfiguration"/> to merge into</param>
/// <param name="mergek8SConfig">The <see cref="K8SConfiguration"/> to merge from</param>
private static void MergeKubeConfig(K8SConfiguration basek8SConfig, K8SConfiguration mergek8SConfig)
{
// For scalar values, prefer local values
basek8SConfig.CurrentContext = basek8SConfig.CurrentContext ?? mergek8SConfig.CurrentContext;
basek8SConfig.FileName = basek8SConfig.FileName ?? mergek8SConfig.FileName;
// Kinds must match in kube config, otherwise throw.
if (basek8SConfig.Kind != mergek8SConfig.Kind)
{
throw new KubeConfigException(
$"kubeconfig \"kind\" are different between {basek8SConfig.FileName} and {mergek8SConfig.FileName}");
}
if (mergek8SConfig.Preferences != null)
{
foreach (var preference in mergek8SConfig.Preferences)
{
if (basek8SConfig.Preferences?.ContainsKey(preference.Key) == false)
{
basek8SConfig.Preferences[preference.Key] = preference.Value;
}
}
}
// Note, Clusters, Contexts, and Extensions are map-like in config despite being represented as a list here:
// https://github.com/kubernetes/client-go/blob/ede92e0fe62deed512d9ceb8bf4186db9f3776ff/tools/clientcmd/api/types.go#L238
basek8SConfig.Extensions = MergeLists(basek8SConfig.Extensions, mergek8SConfig.Extensions, (s) => s.Name);
basek8SConfig.Clusters = MergeLists(basek8SConfig.Clusters, mergek8SConfig.Clusters, (s) => s.Name);
basek8SConfig.Users = MergeLists(basek8SConfig.Users, mergek8SConfig.Users, (s) => s.Name);
basek8SConfig.Contexts = MergeLists(basek8SConfig.Contexts, mergek8SConfig.Contexts, (s) => s.Name);
}
private static IEnumerable<T> MergeLists<T>(IEnumerable<T> baseList, IEnumerable<T> mergeList,
Func<T, string> getNameFunc)
{
if (mergeList != null && mergeList.Any())
{
var mapping = new Dictionary<string, T>();
foreach (var item in baseList)
{
mapping[getNameFunc(item)] = item;
}
foreach (var item in mergeList)
{
var name = getNameFunc(item);
if (!mapping.ContainsKey(name))
{
mapping[name] = item;
}
}
return mapping.Values;
}
return baseList;
}
}
}
| |
using ICSharpCode.SharpZipLib.Core;
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// Basic implementation of <see cref="IEntryFactory"></see>
/// </summary>
public class ZipEntryFactory : IEntryFactory
{
#region Enumerations
/// <summary>
/// Defines the possible values to be used for the <see cref="ZipEntry.DateTime"/>.
/// </summary>
public enum TimeSetting
{
/// <summary>
/// Use the recorded LastWriteTime value for the file.
/// </summary>
LastWriteTime,
/// <summary>
/// Use the recorded LastWriteTimeUtc value for the file
/// </summary>
LastWriteTimeUtc,
/// <summary>
/// Use the recorded CreateTime value for the file.
/// </summary>
CreateTime,
/// <summary>
/// Use the recorded CreateTimeUtc value for the file.
/// </summary>
CreateTimeUtc,
/// <summary>
/// Use the recorded LastAccessTime value for the file.
/// </summary>
LastAccessTime,
/// <summary>
/// Use the recorded LastAccessTimeUtc value for the file.
/// </summary>
LastAccessTimeUtc,
/// <summary>
/// Use a fixed value.
/// </summary>
/// <remarks>The actual <see cref="DateTime"/> value used can be
/// specified via the <see cref="ZipEntryFactory(DateTime)"/> constructor or
/// using the <see cref="ZipEntryFactory(TimeSetting)"/> with the setting set
/// to <see cref="TimeSetting.Fixed"/> which will use the <see cref="DateTime"/> when this class was constructed.
/// The <see cref="FixedDateTime"/> property can also be used to set this value.</remarks>
Fixed,
}
#endregion Enumerations
#region Constructors
/// <summary>
/// Initialise a new instance of the <see cref="ZipEntryFactory"/> class.
/// </summary>
/// <remarks>A default <see cref="INameTransform"/>, and the LastWriteTime for files is used.</remarks>
public ZipEntryFactory()
{
nameTransform_ = new ZipNameTransform();
isUnicodeText_ = ZipStrings.UseUnicode;
}
/// <summary>
/// Initialise a new instance of <see cref="ZipEntryFactory"/> using the specified <see cref="TimeSetting"/>
/// </summary>
/// <param name="timeSetting">The <see cref="TimeSetting">time setting</see> to use when creating <see cref="ZipEntry">Zip entries</see>.</param>
public ZipEntryFactory(TimeSetting timeSetting) : this()
{
timeSetting_ = timeSetting;
}
/// <summary>
/// Initialise a new instance of <see cref="ZipEntryFactory"/> using the specified <see cref="DateTime"/>
/// </summary>
/// <param name="time">The time to set all <see cref="ZipEntry.DateTime"/> values to.</param>
public ZipEntryFactory(DateTime time) : this()
{
timeSetting_ = TimeSetting.Fixed;
FixedDateTime = time;
}
#endregion Constructors
#region Properties
/// <summary>
/// Get / set the <see cref="INameTransform"/> to be used when creating new <see cref="ZipEntry"/> values.
/// </summary>
/// <remarks>
/// Setting this property to null will cause a default <see cref="ZipNameTransform">name transform</see> to be used.
/// </remarks>
public INameTransform NameTransform
{
get { return nameTransform_; }
set
{
if (value == null)
{
nameTransform_ = new ZipNameTransform();
}
else
{
nameTransform_ = value;
}
}
}
/// <summary>
/// Get / set the <see cref="TimeSetting"/> in use.
/// </summary>
public TimeSetting Setting
{
get { return timeSetting_; }
set { timeSetting_ = value; }
}
/// <summary>
/// Get / set the <see cref="DateTime"/> value to use when <see cref="Setting"/> is set to <see cref="TimeSetting.Fixed"/>
/// </summary>
public DateTime FixedDateTime
{
get { return fixedDateTime_; }
set
{
if (value.Year < 1970)
{
throw new ArgumentException("Value is too old to be valid", nameof(value));
}
fixedDateTime_ = value;
}
}
/// <summary>
/// A bitmask defining the attributes to be retrieved from the actual file.
/// </summary>
/// <remarks>The default is to get all possible attributes from the actual file.</remarks>
public int GetAttributes
{
get { return getAttributes_; }
set { getAttributes_ = value; }
}
/// <summary>
/// A bitmask defining which attributes are to be set on.
/// </summary>
/// <remarks>By default no attributes are set on.</remarks>
public int SetAttributes
{
get { return setAttributes_; }
set { setAttributes_ = value; }
}
/// <summary>
/// Get set a value indicating wether unidoce text should be set on.
/// </summary>
public bool IsUnicodeText
{
get { return isUnicodeText_; }
set { isUnicodeText_ = value; }
}
#endregion Properties
#region IEntryFactory Members
/// <summary>
/// Make a new <see cref="ZipEntry"/> for a file.
/// </summary>
/// <param name="fileName">The name of the file to create a new entry for.</param>
/// <returns>Returns a new <see cref="ZipEntry"/> based on the <paramref name="fileName"/>.</returns>
public ZipEntry MakeFileEntry(string fileName)
{
return MakeFileEntry(fileName, null, true);
}
/// <summary>
/// Make a new <see cref="ZipEntry"/> for a file.
/// </summary>
/// <param name="fileName">The name of the file to create a new entry for.</param>
/// <param name="useFileSystem">If true entry detail is retrieved from the file system if the file exists.</param>
/// <returns>Returns a new <see cref="ZipEntry"/> based on the <paramref name="fileName"/>.</returns>
public ZipEntry MakeFileEntry(string fileName, bool useFileSystem)
{
return MakeFileEntry(fileName, null, useFileSystem);
}
/// <summary>
/// Make a new <see cref="ZipEntry"/> from a name.
/// </summary>
/// <param name="fileName">The name of the file to create a new entry for.</param>
/// <param name="entryName">An alternative name to be used for the new entry. Null if not applicable.</param>
/// <param name="useFileSystem">If true entry detail is retrieved from the file system if the file exists.</param>
/// <returns>Returns a new <see cref="ZipEntry"/> based on the <paramref name="fileName"/>.</returns>
public ZipEntry MakeFileEntry(string fileName, string entryName, bool useFileSystem)
{
var result = new ZipEntry(nameTransform_.TransformFile(!string.IsNullOrEmpty(entryName) ? entryName : fileName));
result.IsUnicodeText = isUnicodeText_;
int externalAttributes = 0;
bool useAttributes = (setAttributes_ != 0);
FileInfo fi = null;
if (useFileSystem)
{
fi = new FileInfo(fileName);
}
if ((fi != null) && fi.Exists)
{
switch (timeSetting_)
{
case TimeSetting.CreateTime:
result.DateTime = fi.CreationTime;
break;
case TimeSetting.CreateTimeUtc:
result.DateTime = fi.CreationTimeUtc;
break;
case TimeSetting.LastAccessTime:
result.DateTime = fi.LastAccessTime;
break;
case TimeSetting.LastAccessTimeUtc:
result.DateTime = fi.LastAccessTimeUtc;
break;
case TimeSetting.LastWriteTime:
result.DateTime = fi.LastWriteTime;
break;
case TimeSetting.LastWriteTimeUtc:
result.DateTime = fi.LastWriteTimeUtc;
break;
case TimeSetting.Fixed:
result.DateTime = fixedDateTime_;
break;
default:
throw new ZipException("Unhandled time setting in MakeFileEntry");
}
result.Size = fi.Length;
useAttributes = true;
externalAttributes = ((int)fi.Attributes & getAttributes_);
}
else
{
if (timeSetting_ == TimeSetting.Fixed)
{
result.DateTime = fixedDateTime_;
}
}
if (useAttributes)
{
externalAttributes |= setAttributes_;
result.ExternalFileAttributes = externalAttributes;
}
return result;
}
/// <summary>
/// Make a new <see cref="ZipEntry"></see> for a directory.
/// </summary>
/// <param name="directoryName">The raw untransformed name for the new directory</param>
/// <returns>Returns a new <see cref="ZipEntry"></see> representing a directory.</returns>
public ZipEntry MakeDirectoryEntry(string directoryName)
{
return MakeDirectoryEntry(directoryName, true);
}
/// <summary>
/// Make a new <see cref="ZipEntry"></see> for a directory.
/// </summary>
/// <param name="directoryName">The raw untransformed name for the new directory</param>
/// <param name="useFileSystem">If true entry detail is retrieved from the file system if the file exists.</param>
/// <returns>Returns a new <see cref="ZipEntry"></see> representing a directory.</returns>
public ZipEntry MakeDirectoryEntry(string directoryName, bool useFileSystem)
{
var result = new ZipEntry(nameTransform_.TransformDirectory(directoryName));
result.IsUnicodeText = isUnicodeText_;
result.Size = 0;
int externalAttributes = 0;
DirectoryInfo di = null;
if (useFileSystem)
{
di = new DirectoryInfo(directoryName);
}
if ((di != null) && di.Exists)
{
switch (timeSetting_)
{
case TimeSetting.CreateTime:
result.DateTime = di.CreationTime;
break;
case TimeSetting.CreateTimeUtc:
result.DateTime = di.CreationTimeUtc;
break;
case TimeSetting.LastAccessTime:
result.DateTime = di.LastAccessTime;
break;
case TimeSetting.LastAccessTimeUtc:
result.DateTime = di.LastAccessTimeUtc;
break;
case TimeSetting.LastWriteTime:
result.DateTime = di.LastWriteTime;
break;
case TimeSetting.LastWriteTimeUtc:
result.DateTime = di.LastWriteTimeUtc;
break;
case TimeSetting.Fixed:
result.DateTime = fixedDateTime_;
break;
default:
throw new ZipException("Unhandled time setting in MakeDirectoryEntry");
}
externalAttributes = ((int)di.Attributes & getAttributes_);
}
else
{
if (timeSetting_ == TimeSetting.Fixed)
{
result.DateTime = fixedDateTime_;
}
}
// Always set directory attribute on.
externalAttributes |= (setAttributes_ | 16);
result.ExternalFileAttributes = externalAttributes;
return result;
}
#endregion IEntryFactory Members
#region Instance Fields
private INameTransform nameTransform_;
private DateTime fixedDateTime_ = DateTime.Now;
private TimeSetting timeSetting_;
private bool isUnicodeText_;
private int getAttributes_ = -1;
private int setAttributes_;
#endregion Instance Fields
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
namespace AT_Utils.UI
{
public class DialogFactory : MonoBehaviour
{
private static readonly HashSet<object> contexts = new HashSet<object>();
private static DialogFactory Instance { get; set; }
protected virtual RectTransform dialogParent => GetComponentInParent<Canvas>()?.transform as RectTransform;
public GameObject
prefab;
protected virtual void Awake()
{
if(Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
if(prefab != null)
prefab.SetActive(false);
contexts.Clear();
}
protected virtual void setupDialog(SimpleDialog dialog) { }
private static SimpleDialog newInstance()
{
if(Instance == null || Instance.prefab == null)
return null;
var obj = Instantiate(Instance.prefab, Instance.dialogParent);
if(obj == null)
return null;
var dialog = obj.GetComponent<SimpleDialog>();
Instance.setupDialog(dialog);
return dialog;
}
public static bool ContextIsActive(object context) => contexts.Contains(context);
public static SimpleDialog Create(
string message,
string title,
UnityAction onConfirm,
UnityAction onCancel = null,
UnityAction onClose = null,
UnityAction onDestroy = null,
string confirmText = "Yes",
string cancelText = "No",
bool destroyOnClose = true,
object context = null
)
{
if(context != null && contexts.Contains(context))
return null;
var dialog = newInstance();
if(dialog == null)
return null;
dialog.confirmText.text = confirmText ?? "Yes";
if(string.IsNullOrEmpty(cancelText))
dialog.cancelText.gameObject.SetActive(false);
else
dialog.cancelText.text = cancelText;
dialog.title.text = title;
dialog.message.text = message;
dialog.DestroyOnClose = destroyOnClose;
if(context != null)
{
contexts.Add(context);
dialog.onDestroy.AddListener(() => contexts.Remove(context));
}
dialog.onConfirm.AddListener(onConfirm);
if(onCancel != null)
dialog.onCancel.AddListener(onCancel);
if(onClose != null)
dialog.onClose.AddListener(onClose);
if(onDestroy != null)
dialog.onDestroy.AddListener(onDestroy);
return dialog;
}
public static SimpleDialog Show(
string message,
string title,
UnityAction onConfirm,
UnityAction onCancel = null,
UnityAction onClose = null,
UnityAction onDestroy = null,
string confirmText = "Yes",
string cancelText = "No",
bool destroyOnClose = true,
object context = null
)
{
var dialog = Create(message,
title,
onConfirm,
onCancel,
onClose,
onDestroy,
confirmText,
cancelText,
destroyOnClose,
context);
if(dialog == null)
return null;
dialog.Show();
return dialog;
}
public static SimpleDialog Info(
string message,
string title,
object context = null
) =>
Show(message,
title,
null,
null,
null,
null,
"Close",
null,
context: context);
public static SimpleDialog Warning(
string message,
string title = null,
object context = null
) =>
Show(message,
title ?? "Warning",
null,
null,
null,
null,
"Close",
null,
context: context);
public static SimpleDialog Danger(
string message,
UnityAction onConfirm,
UnityAction onCancel = null,
UnityAction onClose = null,
UnityAction onDestroy = null,
string title = null,
object context = null
)
{
var dialog = Create(message,
title ?? "Warning",
onConfirm,
onCancel,
onClose,
onDestroy,
"Yes",
"Cancel",
context: context);
if(dialog == null)
return null;
dialog.confirmButtonColorizer.SetColor(Colors.Danger);
dialog.cancelButtonColorizer.SetColor(Colors.Good);
dialog.Show();
return dialog;
}
}
public class SimpleDialog : ScreenBoundRect
{
public UnityEvent onConfirm = new UnityEvent();
public UnityEvent onCancel = new UnityEvent();
public UnityEvent onClose = new UnityEvent();
public UnityEvent onDestroy = new UnityEvent();
public Button
confirmButton,
cancelButton;
public Colorizer
confirmButtonColorizer,
cancelButtonColorizer;
public Text
title,
message,
confirmText,
cancelText;
public bool DestroyOnClose = true;
protected override void Awake()
{
base.Awake();
confirmButton.onClick.AddListener(handleConfirm);
cancelButton.onClick.AddListener(handleCancel);
}
private void OnDestroy()
{
if(gameObject.activeInHierarchy)
sendEvent(onClose, nameof(onClose));
sendEvent(onDestroy, nameof(onDestroy));
onConfirm.RemoveAllListeners();
onCancel.RemoveAllListeners();
onClose.RemoveAllListeners();
onDestroy.RemoveAllListeners();
confirmButton.onClick.RemoveAllListeners();
cancelButton.onClick.RemoveAllListeners();
}
private void sendEvent(UnityEvent @event, string eventName)
{
try
{
@event.Invoke();
}
catch(Exception e)
{
Debug.LogError($"[AT_Utils: SimpleDialog] exception in {eventName}: {e}", this);
}
}
private void close()
{
sendEvent(onClose, nameof(onClose));
gameObject.SetActive(false);
if(DestroyOnClose)
Destroy(gameObject);
}
private void handleConfirm()
{
sendEvent(onConfirm, nameof(onConfirm));
close();
}
private void handleCancel()
{
sendEvent(onCancel, nameof(onCancel));
close();
}
public void Show(string newMessage, string newTitle = null)
{
if(!string.IsNullOrEmpty(newMessage))
message.text = newMessage;
if(!string.IsNullOrEmpty(newTitle))
title.text = newTitle;
Show();
}
public void Show() => gameObject.SetActive(true);
public void Close() => gameObject.SetActive(false);
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NodaTime.Calendars;
using NUnit.Framework;
namespace NodaTime.Test.Calendars
{
[TestFixture]
public class IslamicCalendarSystemTest
{
private static readonly CalendarSystem SampleCalendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base16, IslamicEpoch.Civil);
[Test]
public void SampleDate1()
{
// Note: field checks removed from the tests.
LocalDateTime ldt = new LocalDateTime(1945, 11, 12, 0, 0, 0, 0, CalendarSystem.Iso);
ldt = ldt.WithCalendar(SampleCalendar);
Assert.AreEqual(Era.AnnoHegirae, ldt.Era);
Assert.AreEqual(1364, ldt.YearOfEra);
Assert.AreEqual(1364, ldt.Year);
Assert.AreEqual(12, ldt.Month);
Assert.AreEqual(6, ldt.Day);
Assert.AreEqual(IsoDayOfWeek.Monday, ldt.IsoDayOfWeek);
Assert.AreEqual(6 * 30 + 5 * 29 + 6, ldt.DayOfYear);
Assert.AreEqual(0, ldt.Hour);
Assert.AreEqual(0, ldt.Minute);
Assert.AreEqual(0, ldt.Second);
Assert.AreEqual(0, ldt.TickOfSecond);
}
[Test]
public void SampleDate2()
{
LocalDateTime ldt = new LocalDateTime(2005, 11, 26, 0, 0, 0, 0, CalendarSystem.Iso);
ldt = ldt.WithCalendar(SampleCalendar);
Assert.AreEqual(Era.AnnoHegirae, ldt.Era);
Assert.AreEqual(1426, ldt.YearOfEra);
Assert.AreEqual(1426, ldt.Year);
Assert.AreEqual(10, ldt.Month);
Assert.AreEqual(24, ldt.Day);
Assert.AreEqual(IsoDayOfWeek.Saturday, ldt.IsoDayOfWeek);
Assert.AreEqual(5 * 30 + 4 * 29 + 24, ldt.DayOfYear);
Assert.AreEqual(0, ldt.Hour);
Assert.AreEqual(0, ldt.Minute);
Assert.AreEqual(0, ldt.Second);
Assert.AreEqual(0, ldt.TickOfSecond);
}
[Test]
public void SampleDate3()
{
LocalDateTime ldt = new LocalDateTime(1426, 12, 24, 0, 0, 0, 0, SampleCalendar);
Assert.AreEqual(Era.AnnoHegirae, ldt.Era);
Assert.AreEqual(1426, ldt.Year);
Assert.AreEqual(12, ldt.Month);
Assert.AreEqual(24, ldt.Day);
Assert.AreEqual(IsoDayOfWeek.Tuesday, ldt.IsoDayOfWeek);
Assert.AreEqual(6 * 30 + 5 * 29 + 24, ldt.DayOfYear);
Assert.AreEqual(0, ldt.Hour);
Assert.AreEqual(0, ldt.Minute);
Assert.AreEqual(0, ldt.Second);
Assert.AreEqual(0, ldt.TickOfSecond);
}
[Test]
public void InternalConsistency()
{
var calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil);
// Check construction and then deconstruction for every day of every year in one 30-year cycle.
for (int year = 1; year <= 30; year++)
{
for (int month = 1; month <= 12; month++)
{
int monthLength = calendar.GetDaysInMonth(year, month);
for (int day = 1; day < monthLength; day++)
{
LocalDate date = new LocalDate(year, month, day, calendar);
Assert.AreEqual(year, date.Year, "Year of {0}-{1}-{2}", year, month, day);
Assert.AreEqual(month, date.Month, "Month of {0}-{1}-{2}", year, month, day);
Assert.AreEqual(day, date.Day, "Day of {0}-{1}-{2}", year, month, day);
}
}
}
}
[Test]
public void Base15LeapYear()
{
CalendarSystem calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil);
Assert.AreEqual(false, calendar.IsLeapYear(1));
Assert.AreEqual(true, calendar.IsLeapYear(2));
Assert.AreEqual(false, calendar.IsLeapYear(3));
Assert.AreEqual(false, calendar.IsLeapYear(4));
Assert.AreEqual(true, calendar.IsLeapYear(5));
Assert.AreEqual(false, calendar.IsLeapYear(6));
Assert.AreEqual(true, calendar.IsLeapYear(7));
Assert.AreEqual(false, calendar.IsLeapYear(8));
Assert.AreEqual(false, calendar.IsLeapYear(9));
Assert.AreEqual(true, calendar.IsLeapYear(10));
Assert.AreEqual(false, calendar.IsLeapYear(11));
Assert.AreEqual(false, calendar.IsLeapYear(12));
Assert.AreEqual(true, calendar.IsLeapYear(13));
Assert.AreEqual(false, calendar.IsLeapYear(14));
Assert.AreEqual(true, calendar.IsLeapYear(15));
Assert.AreEqual(false, calendar.IsLeapYear(16));
Assert.AreEqual(false, calendar.IsLeapYear(17));
Assert.AreEqual(true, calendar.IsLeapYear(18));
Assert.AreEqual(false, calendar.IsLeapYear(19));
Assert.AreEqual(false, calendar.IsLeapYear(20));
Assert.AreEqual(true, calendar.IsLeapYear(21));
Assert.AreEqual(false, calendar.IsLeapYear(22));
Assert.AreEqual(false, calendar.IsLeapYear(23));
Assert.AreEqual(true, calendar.IsLeapYear(24));
Assert.AreEqual(false, calendar.IsLeapYear(25));
Assert.AreEqual(true, calendar.IsLeapYear(26));
Assert.AreEqual(false, calendar.IsLeapYear(27));
Assert.AreEqual(false, calendar.IsLeapYear(28));
Assert.AreEqual(true, calendar.IsLeapYear(29));
Assert.AreEqual(false, calendar.IsLeapYear(30));
}
[Test]
public void Base16LeapYear()
{
CalendarSystem calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base16, IslamicEpoch.Civil);
Assert.AreEqual(false, calendar.IsLeapYear(1));
Assert.AreEqual(true, calendar.IsLeapYear(2));
Assert.AreEqual(false, calendar.IsLeapYear(3));
Assert.AreEqual(false, calendar.IsLeapYear(4));
Assert.AreEqual(true, calendar.IsLeapYear(5));
Assert.AreEqual(false, calendar.IsLeapYear(6));
Assert.AreEqual(true, calendar.IsLeapYear(7));
Assert.AreEqual(false, calendar.IsLeapYear(8));
Assert.AreEqual(false, calendar.IsLeapYear(9));
Assert.AreEqual(true, calendar.IsLeapYear(10));
Assert.AreEqual(false, calendar.IsLeapYear(11));
Assert.AreEqual(false, calendar.IsLeapYear(12));
Assert.AreEqual(true, calendar.IsLeapYear(13));
Assert.AreEqual(false, calendar.IsLeapYear(14));
Assert.AreEqual(false, calendar.IsLeapYear(15));
Assert.AreEqual(true, calendar.IsLeapYear(16));
Assert.AreEqual(false, calendar.IsLeapYear(17));
Assert.AreEqual(true, calendar.IsLeapYear(18));
Assert.AreEqual(false, calendar.IsLeapYear(19));
Assert.AreEqual(false, calendar.IsLeapYear(20));
Assert.AreEqual(true, calendar.IsLeapYear(21));
Assert.AreEqual(false, calendar.IsLeapYear(22));
Assert.AreEqual(false, calendar.IsLeapYear(23));
Assert.AreEqual(true, calendar.IsLeapYear(24));
Assert.AreEqual(false, calendar.IsLeapYear(25));
Assert.AreEqual(true, calendar.IsLeapYear(26));
Assert.AreEqual(false, calendar.IsLeapYear(27));
Assert.AreEqual(false, calendar.IsLeapYear(28));
Assert.AreEqual(true, calendar.IsLeapYear(29));
Assert.AreEqual(false, calendar.IsLeapYear(30));
}
[Test]
public void IndianBasedLeapYear()
{
CalendarSystem calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Indian, IslamicEpoch.Civil);
Assert.AreEqual(false, calendar.IsLeapYear(1));
Assert.AreEqual(true, calendar.IsLeapYear(2));
Assert.AreEqual(false, calendar.IsLeapYear(3));
Assert.AreEqual(false, calendar.IsLeapYear(4));
Assert.AreEqual(true, calendar.IsLeapYear(5));
Assert.AreEqual(false, calendar.IsLeapYear(6));
Assert.AreEqual(false, calendar.IsLeapYear(7));
Assert.AreEqual(true, calendar.IsLeapYear(8));
Assert.AreEqual(false, calendar.IsLeapYear(9));
Assert.AreEqual(true, calendar.IsLeapYear(10));
Assert.AreEqual(false, calendar.IsLeapYear(11));
Assert.AreEqual(false, calendar.IsLeapYear(12));
Assert.AreEqual(true, calendar.IsLeapYear(13));
Assert.AreEqual(false, calendar.IsLeapYear(14));
Assert.AreEqual(false, calendar.IsLeapYear(15));
Assert.AreEqual(true, calendar.IsLeapYear(16));
Assert.AreEqual(false, calendar.IsLeapYear(17));
Assert.AreEqual(false, calendar.IsLeapYear(18));
Assert.AreEqual(true, calendar.IsLeapYear(19));
Assert.AreEqual(false, calendar.IsLeapYear(20));
Assert.AreEqual(true, calendar.IsLeapYear(21));
Assert.AreEqual(false, calendar.IsLeapYear(22));
Assert.AreEqual(false, calendar.IsLeapYear(23));
Assert.AreEqual(true, calendar.IsLeapYear(24));
Assert.AreEqual(false, calendar.IsLeapYear(25));
Assert.AreEqual(false, calendar.IsLeapYear(26));
Assert.AreEqual(true, calendar.IsLeapYear(27));
Assert.AreEqual(false, calendar.IsLeapYear(28));
Assert.AreEqual(true, calendar.IsLeapYear(29));
Assert.AreEqual(false, calendar.IsLeapYear(30));
}
[Test]
public void HabashAlHasibBasedLeapYear()
{
CalendarSystem calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.HabashAlHasib, IslamicEpoch.Civil);
Assert.AreEqual(false, calendar.IsLeapYear(1));
Assert.AreEqual(true, calendar.IsLeapYear(2));
Assert.AreEqual(false, calendar.IsLeapYear(3));
Assert.AreEqual(false, calendar.IsLeapYear(4));
Assert.AreEqual(true, calendar.IsLeapYear(5));
Assert.AreEqual(false, calendar.IsLeapYear(6));
Assert.AreEqual(false, calendar.IsLeapYear(7));
Assert.AreEqual(true, calendar.IsLeapYear(8));
Assert.AreEqual(false, calendar.IsLeapYear(9));
Assert.AreEqual(false, calendar.IsLeapYear(10));
Assert.AreEqual(true, calendar.IsLeapYear(11));
Assert.AreEqual(false, calendar.IsLeapYear(12));
Assert.AreEqual(true, calendar.IsLeapYear(13));
Assert.AreEqual(false, calendar.IsLeapYear(14));
Assert.AreEqual(false, calendar.IsLeapYear(15));
Assert.AreEqual(true, calendar.IsLeapYear(16));
Assert.AreEqual(false, calendar.IsLeapYear(17));
Assert.AreEqual(false, calendar.IsLeapYear(18));
Assert.AreEqual(true, calendar.IsLeapYear(19));
Assert.AreEqual(false, calendar.IsLeapYear(20));
Assert.AreEqual(true, calendar.IsLeapYear(21));
Assert.AreEqual(false, calendar.IsLeapYear(22));
Assert.AreEqual(false, calendar.IsLeapYear(23));
Assert.AreEqual(true, calendar.IsLeapYear(24));
Assert.AreEqual(false, calendar.IsLeapYear(25));
Assert.AreEqual(false, calendar.IsLeapYear(26));
Assert.AreEqual(true, calendar.IsLeapYear(27));
Assert.AreEqual(false, calendar.IsLeapYear(28));
Assert.AreEqual(false, calendar.IsLeapYear(29));
Assert.AreEqual(true, calendar.IsLeapYear(30));
}
[Test]
public void ThursdayEpoch()
{
CalendarSystem thursdayEpochCalendar = CalendarSystem.IslamicBcl;
CalendarSystem julianCalendar = CalendarSystem.Julian;
LocalDate thursdayEpoch = new LocalDate(1, 1, 1, thursdayEpochCalendar);
LocalDate thursdayEpochJulian = new LocalDate(622, 7, 15, julianCalendar);
Assert.AreEqual(thursdayEpochJulian, thursdayEpoch.WithCalendar(julianCalendar));
}
[Test]
public void FridayEpoch()
{
CalendarSystem fridayEpochCalendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base16, IslamicEpoch.Civil);
CalendarSystem julianCalendar = CalendarSystem.Julian;
LocalDate fridayEpoch = new LocalDate(1, 1, 1, fridayEpochCalendar);
LocalDate fridayEpochJulian = new LocalDate(622, 7, 16, julianCalendar);
Assert.AreEqual(fridayEpochJulian, fridayEpoch.WithCalendar(julianCalendar));
}
[Test]
public void BclUsesAstronomicalEpoch()
{
Calendar hijri = new HijriCalendar();
DateTime bclDirect = new DateTime(1, 1, 1, 0, 0, 0, 0, hijri, DateTimeKind.Unspecified);
CalendarSystem julianCalendar = CalendarSystem.Julian;
LocalDate julianIslamicEpoch = new LocalDate(622, 7, 15, julianCalendar);
LocalDate isoIslamicEpoch = julianIslamicEpoch.WithCalendar(CalendarSystem.Iso);
DateTime bclFromNoda = isoIslamicEpoch.AtMidnight().ToDateTimeUnspecified();
Assert.AreEqual(bclDirect, bclFromNoda);
}
[Test]
public void SampleDateBclCompatibility()
{
Calendar hijri = new HijriCalendar();
DateTime bclDirect = new DateTime(1302, 10, 15, 0, 0, 0, 0, hijri, DateTimeKind.Unspecified);
CalendarSystem islamicCalendar = CalendarSystem.IslamicBcl;
LocalDate iso = new LocalDate(1302, 10, 15, islamicCalendar);
DateTime bclFromNoda = iso.AtMidnight().ToDateTimeUnspecified();
Assert.AreEqual(bclDirect, bclFromNoda);
}
/// <summary>
/// This tests every day for 9000 (ISO) years, to check that it always matches the year, month and day.
/// </summary>
[Test, Timeout(180000)] // Can take a long time under NCrunch.
public void BclThroughHistory()
{
var bcl = new HijriCalendar();
var noda = CalendarSystem.IslamicBcl;
BclEquivalenceHelper.AssertEquivalent(bcl, noda, noda.MinYear, noda.MaxYear);
}
[Test]
public void GetDaysInMonth()
{
// Just check that we've got the long/short the right way round...
CalendarSystem calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.HabashAlHasib, IslamicEpoch.Civil);
Assert.AreEqual(30, calendar.GetDaysInMonth(7, 1));
Assert.AreEqual(29, calendar.GetDaysInMonth(7, 2));
Assert.AreEqual(30, calendar.GetDaysInMonth(7, 3));
Assert.AreEqual(29, calendar.GetDaysInMonth(7, 4));
Assert.AreEqual(30, calendar.GetDaysInMonth(7, 5));
Assert.AreEqual(29, calendar.GetDaysInMonth(7, 6));
Assert.AreEqual(30, calendar.GetDaysInMonth(7, 7));
Assert.AreEqual(29, calendar.GetDaysInMonth(7, 8));
Assert.AreEqual(30, calendar.GetDaysInMonth(7, 9));
Assert.AreEqual(29, calendar.GetDaysInMonth(7, 10));
Assert.AreEqual(30, calendar.GetDaysInMonth(7, 11));
// As noted before, 7 isn't a leap year in this calendar
Assert.AreEqual(29, calendar.GetDaysInMonth(7, 12));
// As noted before, 8 is a leap year in this calendar
Assert.AreEqual(30, calendar.GetDaysInMonth(8, 12));
}
[Test]
public void GetInstance_Caching()
{
var queue = new Queue<CalendarSystem>();
var set = new HashSet<CalendarSystem>();
var ids = new HashSet<string>();
foreach (IslamicLeapYearPattern leapYearPattern in Enum.GetValues(typeof(IslamicLeapYearPattern)))
{
foreach (IslamicEpoch epoch in Enum.GetValues(typeof(IslamicEpoch)))
{
var calendar = CalendarSystem.GetIslamicCalendar(leapYearPattern, epoch);
queue.Enqueue(calendar);
Assert.IsTrue(set.Add(calendar)); // Check we haven't already seen it...
Assert.IsTrue(ids.Add(calendar.Id));
}
}
// Now check we get the same references again...
foreach (IslamicLeapYearPattern leapYearPattern in Enum.GetValues(typeof(IslamicLeapYearPattern)))
{
foreach (IslamicEpoch epoch in Enum.GetValues(typeof(IslamicEpoch)))
{
var oldCalendar = queue.Dequeue();
var newCalendar = CalendarSystem.GetIslamicCalendar(leapYearPattern, epoch);
Assert.AreSame(oldCalendar, newCalendar);
}
}
}
[Test]
public void GetInstance_ArgumentValidation()
{
var epochs = Enum.GetValues(typeof(IslamicEpoch)).Cast<IslamicEpoch>();
var leapYearPatterns = Enum.GetValues(typeof(IslamicLeapYearPattern)).Cast<IslamicLeapYearPattern>();
Assert.Throws<ArgumentOutOfRangeException>(() => CalendarSystem.GetIslamicCalendar(leapYearPatterns.Min() - 1, epochs.Min()));
Assert.Throws<ArgumentOutOfRangeException>(() => CalendarSystem.GetIslamicCalendar(leapYearPatterns.Min(), epochs.Min() - 1));
Assert.Throws<ArgumentOutOfRangeException>(() => CalendarSystem.GetIslamicCalendar(leapYearPatterns.Max() + 1, epochs.Min()));
Assert.Throws<ArgumentOutOfRangeException>(() => CalendarSystem.GetIslamicCalendar(leapYearPatterns.Min(), epochs.Max() + 1));
}
[Test]
public void PlusYears_Simple()
{
var calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil);
LocalDateTime start = new LocalDateTime(5, 8, 20, 2, 0, calendar);
LocalDateTime expectedEnd = new LocalDateTime(10, 8, 20, 2, 0, calendar);
Assert.AreEqual(expectedEnd, start.PlusYears(5));
}
[Test]
public void PlusYears_TruncatesAtLeapYear()
{
var calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil);
Assert.IsTrue(calendar.IsLeapYear(2));
Assert.IsFalse(calendar.IsLeapYear(3));
LocalDateTime start = new LocalDateTime(2, 12, 30, 2, 0, calendar);
LocalDateTime expectedEnd = new LocalDateTime(3, 12, 29, 2, 0, calendar);
Assert.AreEqual(expectedEnd, start.PlusYears(1));
}
[Test]
public void PlusYears_DoesNotTruncateFromOneLeapYearToAnother()
{
var calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil);
Assert.IsTrue(calendar.IsLeapYear(2));
Assert.IsTrue(calendar.IsLeapYear(5));
LocalDateTime start = new LocalDateTime(2, 12, 30, 2, 0, calendar);
LocalDateTime expectedEnd = new LocalDateTime(5, 12, 30, 2, 0, calendar);
Assert.AreEqual(expectedEnd, start.PlusYears(3));
}
[Test]
public void PlusMonths_Simple()
{
var calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil);
Assert.IsTrue(calendar.IsLeapYear(2));
LocalDateTime start = new LocalDateTime(2, 12, 30, 2, 0, calendar);
LocalDateTime expectedEnd = new LocalDateTime(3, 11, 30, 2, 0, calendar);
Assert.AreEqual(11, expectedEnd.Month);
Assert.AreEqual(30, expectedEnd.Day);
Assert.AreEqual(expectedEnd, start.PlusMonths(11));
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the ConAgendaAuditorium class.
/// </summary>
[Serializable]
public partial class ConAgendaAuditoriumCollection : ActiveList<ConAgendaAuditorium, ConAgendaAuditoriumCollection>
{
public ConAgendaAuditoriumCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ConAgendaAuditoriumCollection</returns>
public ConAgendaAuditoriumCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ConAgendaAuditorium o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the CON_AgendaAuditoria table.
/// </summary>
[Serializable]
public partial class ConAgendaAuditorium : ActiveRecord<ConAgendaAuditorium>, IActiveRecord
{
#region .ctors and Default Settings
public ConAgendaAuditorium()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ConAgendaAuditorium(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public ConAgendaAuditorium(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public ConAgendaAuditorium(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CON_AgendaAuditoria", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdAuditoria = new TableSchema.TableColumn(schema);
colvarIdAuditoria.ColumnName = "idAuditoria";
colvarIdAuditoria.DataType = DbType.Int32;
colvarIdAuditoria.MaxLength = 0;
colvarIdAuditoria.AutoIncrement = true;
colvarIdAuditoria.IsNullable = false;
colvarIdAuditoria.IsPrimaryKey = true;
colvarIdAuditoria.IsForeignKey = false;
colvarIdAuditoria.IsReadOnly = false;
colvarIdAuditoria.DefaultSetting = @"";
colvarIdAuditoria.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdAuditoria);
TableSchema.TableColumn colvarIdAgenda = new TableSchema.TableColumn(schema);
colvarIdAgenda.ColumnName = "idAgenda";
colvarIdAgenda.DataType = DbType.Int32;
colvarIdAgenda.MaxLength = 0;
colvarIdAgenda.AutoIncrement = false;
colvarIdAgenda.IsNullable = false;
colvarIdAgenda.IsPrimaryKey = false;
colvarIdAgenda.IsForeignKey = false;
colvarIdAgenda.IsReadOnly = false;
colvarIdAgenda.DefaultSetting = @"";
colvarIdAgenda.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdAgenda);
TableSchema.TableColumn colvarIdAgendaEstado = new TableSchema.TableColumn(schema);
colvarIdAgendaEstado.ColumnName = "idAgendaEstado";
colvarIdAgendaEstado.DataType = DbType.Int32;
colvarIdAgendaEstado.MaxLength = 0;
colvarIdAgendaEstado.AutoIncrement = false;
colvarIdAgendaEstado.IsNullable = false;
colvarIdAgendaEstado.IsPrimaryKey = false;
colvarIdAgendaEstado.IsForeignKey = true;
colvarIdAgendaEstado.IsReadOnly = false;
colvarIdAgendaEstado.DefaultSetting = @"";
colvarIdAgendaEstado.ForeignKeyTableName = "CON_AgendaEstado";
schema.Columns.Add(colvarIdAgendaEstado);
TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema);
colvarIdEfector.ColumnName = "idEfector";
colvarIdEfector.DataType = DbType.Int32;
colvarIdEfector.MaxLength = 0;
colvarIdEfector.AutoIncrement = false;
colvarIdEfector.IsNullable = false;
colvarIdEfector.IsPrimaryKey = false;
colvarIdEfector.IsForeignKey = false;
colvarIdEfector.IsReadOnly = false;
colvarIdEfector.DefaultSetting = @"";
colvarIdEfector.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEfector);
TableSchema.TableColumn colvarIdServicio = new TableSchema.TableColumn(schema);
colvarIdServicio.ColumnName = "idServicio";
colvarIdServicio.DataType = DbType.Int32;
colvarIdServicio.MaxLength = 0;
colvarIdServicio.AutoIncrement = false;
colvarIdServicio.IsNullable = false;
colvarIdServicio.IsPrimaryKey = false;
colvarIdServicio.IsForeignKey = false;
colvarIdServicio.IsReadOnly = false;
colvarIdServicio.DefaultSetting = @"((0))";
colvarIdServicio.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdServicio);
TableSchema.TableColumn colvarIdProfesional = new TableSchema.TableColumn(schema);
colvarIdProfesional.ColumnName = "idProfesional";
colvarIdProfesional.DataType = DbType.Int32;
colvarIdProfesional.MaxLength = 0;
colvarIdProfesional.AutoIncrement = false;
colvarIdProfesional.IsNullable = false;
colvarIdProfesional.IsPrimaryKey = false;
colvarIdProfesional.IsForeignKey = false;
colvarIdProfesional.IsReadOnly = false;
colvarIdProfesional.DefaultSetting = @"((0))";
colvarIdProfesional.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdProfesional);
TableSchema.TableColumn colvarIdEspecialidad = new TableSchema.TableColumn(schema);
colvarIdEspecialidad.ColumnName = "idEspecialidad";
colvarIdEspecialidad.DataType = DbType.Int32;
colvarIdEspecialidad.MaxLength = 0;
colvarIdEspecialidad.AutoIncrement = false;
colvarIdEspecialidad.IsNullable = false;
colvarIdEspecialidad.IsPrimaryKey = false;
colvarIdEspecialidad.IsForeignKey = false;
colvarIdEspecialidad.IsReadOnly = false;
colvarIdEspecialidad.DefaultSetting = @"((0))";
colvarIdEspecialidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEspecialidad);
TableSchema.TableColumn colvarIdConsultorio = new TableSchema.TableColumn(schema);
colvarIdConsultorio.ColumnName = "idConsultorio";
colvarIdConsultorio.DataType = DbType.Int32;
colvarIdConsultorio.MaxLength = 0;
colvarIdConsultorio.AutoIncrement = false;
colvarIdConsultorio.IsNullable = false;
colvarIdConsultorio.IsPrimaryKey = false;
colvarIdConsultorio.IsForeignKey = false;
colvarIdConsultorio.IsReadOnly = false;
colvarIdConsultorio.DefaultSetting = @"((0))";
colvarIdConsultorio.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdConsultorio);
TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema);
colvarIdUsuario.ColumnName = "idUsuario";
colvarIdUsuario.DataType = DbType.Int32;
colvarIdUsuario.MaxLength = 0;
colvarIdUsuario.AutoIncrement = false;
colvarIdUsuario.IsNullable = false;
colvarIdUsuario.IsPrimaryKey = false;
colvarIdUsuario.IsForeignKey = false;
colvarIdUsuario.IsReadOnly = false;
colvarIdUsuario.DefaultSetting = @"";
colvarIdUsuario.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdUsuario);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = false;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"((0))";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarHoraInicio = new TableSchema.TableColumn(schema);
colvarHoraInicio.ColumnName = "horaInicio";
colvarHoraInicio.DataType = DbType.AnsiStringFixedLength;
colvarHoraInicio.MaxLength = 5;
colvarHoraInicio.AutoIncrement = false;
colvarHoraInicio.IsNullable = false;
colvarHoraInicio.IsPrimaryKey = false;
colvarHoraInicio.IsForeignKey = false;
colvarHoraInicio.IsReadOnly = false;
colvarHoraInicio.DefaultSetting = @"(((1)/(1))/(1900))";
colvarHoraInicio.ForeignKeyTableName = "";
schema.Columns.Add(colvarHoraInicio);
TableSchema.TableColumn colvarHoraFin = new TableSchema.TableColumn(schema);
colvarHoraFin.ColumnName = "horaFin";
colvarHoraFin.DataType = DbType.AnsiStringFixedLength;
colvarHoraFin.MaxLength = 5;
colvarHoraFin.AutoIncrement = false;
colvarHoraFin.IsNullable = false;
colvarHoraFin.IsPrimaryKey = false;
colvarHoraFin.IsForeignKey = false;
colvarHoraFin.IsReadOnly = false;
colvarHoraFin.DefaultSetting = @"(((1)/(1))/(1900))";
colvarHoraFin.ForeignKeyTableName = "";
schema.Columns.Add(colvarHoraFin);
TableSchema.TableColumn colvarDuracion = new TableSchema.TableColumn(schema);
colvarDuracion.ColumnName = "duracion";
colvarDuracion.DataType = DbType.Int32;
colvarDuracion.MaxLength = 0;
colvarDuracion.AutoIncrement = false;
colvarDuracion.IsNullable = false;
colvarDuracion.IsPrimaryKey = false;
colvarDuracion.IsForeignKey = false;
colvarDuracion.IsReadOnly = false;
colvarDuracion.DefaultSetting = @"((0))";
colvarDuracion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDuracion);
TableSchema.TableColumn colvarReservados = new TableSchema.TableColumn(schema);
colvarReservados.ColumnName = "reservados";
colvarReservados.DataType = DbType.Int32;
colvarReservados.MaxLength = 0;
colvarReservados.AutoIncrement = false;
colvarReservados.IsNullable = false;
colvarReservados.IsPrimaryKey = false;
colvarReservados.IsForeignKey = false;
colvarReservados.IsReadOnly = false;
colvarReservados.DefaultSetting = @"((0))";
colvarReservados.ForeignKeyTableName = "";
schema.Columns.Add(colvarReservados);
TableSchema.TableColumn colvarMaxSobreturnos = new TableSchema.TableColumn(schema);
colvarMaxSobreturnos.ColumnName = "maxSobreturnos";
colvarMaxSobreturnos.DataType = DbType.Int32;
colvarMaxSobreturnos.MaxLength = 0;
colvarMaxSobreturnos.AutoIncrement = false;
colvarMaxSobreturnos.IsNullable = false;
colvarMaxSobreturnos.IsPrimaryKey = false;
colvarMaxSobreturnos.IsForeignKey = false;
colvarMaxSobreturnos.IsReadOnly = false;
colvarMaxSobreturnos.DefaultSetting = @"";
colvarMaxSobreturnos.ForeignKeyTableName = "";
schema.Columns.Add(colvarMaxSobreturnos);
TableSchema.TableColumn colvarCitarPorBloques = new TableSchema.TableColumn(schema);
colvarCitarPorBloques.ColumnName = "citarPorBloques";
colvarCitarPorBloques.DataType = DbType.Int32;
colvarCitarPorBloques.MaxLength = 0;
colvarCitarPorBloques.AutoIncrement = false;
colvarCitarPorBloques.IsNullable = false;
colvarCitarPorBloques.IsPrimaryKey = false;
colvarCitarPorBloques.IsForeignKey = false;
colvarCitarPorBloques.IsReadOnly = false;
colvarCitarPorBloques.DefaultSetting = @"((0))";
colvarCitarPorBloques.ForeignKeyTableName = "";
schema.Columns.Add(colvarCitarPorBloques);
TableSchema.TableColumn colvarFechaModificacion = new TableSchema.TableColumn(schema);
colvarFechaModificacion.ColumnName = "fechaModificacion";
colvarFechaModificacion.DataType = DbType.DateTime;
colvarFechaModificacion.MaxLength = 0;
colvarFechaModificacion.AutoIncrement = false;
colvarFechaModificacion.IsNullable = false;
colvarFechaModificacion.IsPrimaryKey = false;
colvarFechaModificacion.IsForeignKey = false;
colvarFechaModificacion.IsReadOnly = false;
colvarFechaModificacion.DefaultSetting = @"";
colvarFechaModificacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaModificacion);
TableSchema.TableColumn colvarHoraModificacion = new TableSchema.TableColumn(schema);
colvarHoraModificacion.ColumnName = "horaModificacion";
colvarHoraModificacion.DataType = DbType.AnsiStringFixedLength;
colvarHoraModificacion.MaxLength = 5;
colvarHoraModificacion.AutoIncrement = false;
colvarHoraModificacion.IsNullable = true;
colvarHoraModificacion.IsPrimaryKey = false;
colvarHoraModificacion.IsForeignKey = false;
colvarHoraModificacion.IsReadOnly = false;
colvarHoraModificacion.DefaultSetting = @"";
colvarHoraModificacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarHoraModificacion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_AgendaAuditoria",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdAuditoria")]
[Bindable(true)]
public int IdAuditoria
{
get { return GetColumnValue<int>(Columns.IdAuditoria); }
set { SetColumnValue(Columns.IdAuditoria, value); }
}
[XmlAttribute("IdAgenda")]
[Bindable(true)]
public int IdAgenda
{
get { return GetColumnValue<int>(Columns.IdAgenda); }
set { SetColumnValue(Columns.IdAgenda, value); }
}
[XmlAttribute("IdAgendaEstado")]
[Bindable(true)]
public int IdAgendaEstado
{
get { return GetColumnValue<int>(Columns.IdAgendaEstado); }
set { SetColumnValue(Columns.IdAgendaEstado, value); }
}
[XmlAttribute("IdEfector")]
[Bindable(true)]
public int IdEfector
{
get { return GetColumnValue<int>(Columns.IdEfector); }
set { SetColumnValue(Columns.IdEfector, value); }
}
[XmlAttribute("IdServicio")]
[Bindable(true)]
public int IdServicio
{
get { return GetColumnValue<int>(Columns.IdServicio); }
set { SetColumnValue(Columns.IdServicio, value); }
}
[XmlAttribute("IdProfesional")]
[Bindable(true)]
public int IdProfesional
{
get { return GetColumnValue<int>(Columns.IdProfesional); }
set { SetColumnValue(Columns.IdProfesional, value); }
}
[XmlAttribute("IdEspecialidad")]
[Bindable(true)]
public int IdEspecialidad
{
get { return GetColumnValue<int>(Columns.IdEspecialidad); }
set { SetColumnValue(Columns.IdEspecialidad, value); }
}
[XmlAttribute("IdConsultorio")]
[Bindable(true)]
public int IdConsultorio
{
get { return GetColumnValue<int>(Columns.IdConsultorio); }
set { SetColumnValue(Columns.IdConsultorio, value); }
}
[XmlAttribute("IdUsuario")]
[Bindable(true)]
public int IdUsuario
{
get { return GetColumnValue<int>(Columns.IdUsuario); }
set { SetColumnValue(Columns.IdUsuario, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime Fecha
{
get { return GetColumnValue<DateTime>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("HoraInicio")]
[Bindable(true)]
public string HoraInicio
{
get { return GetColumnValue<string>(Columns.HoraInicio); }
set { SetColumnValue(Columns.HoraInicio, value); }
}
[XmlAttribute("HoraFin")]
[Bindable(true)]
public string HoraFin
{
get { return GetColumnValue<string>(Columns.HoraFin); }
set { SetColumnValue(Columns.HoraFin, value); }
}
[XmlAttribute("Duracion")]
[Bindable(true)]
public int Duracion
{
get { return GetColumnValue<int>(Columns.Duracion); }
set { SetColumnValue(Columns.Duracion, value); }
}
[XmlAttribute("Reservados")]
[Bindable(true)]
public int Reservados
{
get { return GetColumnValue<int>(Columns.Reservados); }
set { SetColumnValue(Columns.Reservados, value); }
}
[XmlAttribute("MaxSobreturnos")]
[Bindable(true)]
public int MaxSobreturnos
{
get { return GetColumnValue<int>(Columns.MaxSobreturnos); }
set { SetColumnValue(Columns.MaxSobreturnos, value); }
}
[XmlAttribute("CitarPorBloques")]
[Bindable(true)]
public int CitarPorBloques
{
get { return GetColumnValue<int>(Columns.CitarPorBloques); }
set { SetColumnValue(Columns.CitarPorBloques, value); }
}
[XmlAttribute("FechaModificacion")]
[Bindable(true)]
public DateTime FechaModificacion
{
get { return GetColumnValue<DateTime>(Columns.FechaModificacion); }
set { SetColumnValue(Columns.FechaModificacion, value); }
}
[XmlAttribute("HoraModificacion")]
[Bindable(true)]
public string HoraModificacion
{
get { return GetColumnValue<string>(Columns.HoraModificacion); }
set { SetColumnValue(Columns.HoraModificacion, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a ConAgendaEstado ActiveRecord object related to this ConAgendaAuditorium
///
/// </summary>
public DalSic.ConAgendaEstado ConAgendaEstado
{
get { return DalSic.ConAgendaEstado.FetchByID(this.IdAgendaEstado); }
set { SetColumnValue("idAgendaEstado", value.IdAgendaEstado); }
}
/// <summary>
/// Returns a ConAgendaEstado ActiveRecord object related to this ConAgendaAuditorium
///
/// </summary>
public DalSic.ConAgendaEstado ConAgendaEstadoToIdAgendaEstado
{
get { return DalSic.ConAgendaEstado.FetchByID(this.IdAgendaEstado); }
set { SetColumnValue("idAgendaEstado", value.IdAgendaEstado); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdAgenda,int varIdAgendaEstado,int varIdEfector,int varIdServicio,int varIdProfesional,int varIdEspecialidad,int varIdConsultorio,int varIdUsuario,DateTime varFecha,string varHoraInicio,string varHoraFin,int varDuracion,int varReservados,int varMaxSobreturnos,int varCitarPorBloques,DateTime varFechaModificacion,string varHoraModificacion)
{
ConAgendaAuditorium item = new ConAgendaAuditorium();
item.IdAgenda = varIdAgenda;
item.IdAgendaEstado = varIdAgendaEstado;
item.IdEfector = varIdEfector;
item.IdServicio = varIdServicio;
item.IdProfesional = varIdProfesional;
item.IdEspecialidad = varIdEspecialidad;
item.IdConsultorio = varIdConsultorio;
item.IdUsuario = varIdUsuario;
item.Fecha = varFecha;
item.HoraInicio = varHoraInicio;
item.HoraFin = varHoraFin;
item.Duracion = varDuracion;
item.Reservados = varReservados;
item.MaxSobreturnos = varMaxSobreturnos;
item.CitarPorBloques = varCitarPorBloques;
item.FechaModificacion = varFechaModificacion;
item.HoraModificacion = varHoraModificacion;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdAuditoria,int varIdAgenda,int varIdAgendaEstado,int varIdEfector,int varIdServicio,int varIdProfesional,int varIdEspecialidad,int varIdConsultorio,int varIdUsuario,DateTime varFecha,string varHoraInicio,string varHoraFin,int varDuracion,int varReservados,int varMaxSobreturnos,int varCitarPorBloques,DateTime varFechaModificacion,string varHoraModificacion)
{
ConAgendaAuditorium item = new ConAgendaAuditorium();
item.IdAuditoria = varIdAuditoria;
item.IdAgenda = varIdAgenda;
item.IdAgendaEstado = varIdAgendaEstado;
item.IdEfector = varIdEfector;
item.IdServicio = varIdServicio;
item.IdProfesional = varIdProfesional;
item.IdEspecialidad = varIdEspecialidad;
item.IdConsultorio = varIdConsultorio;
item.IdUsuario = varIdUsuario;
item.Fecha = varFecha;
item.HoraInicio = varHoraInicio;
item.HoraFin = varHoraFin;
item.Duracion = varDuracion;
item.Reservados = varReservados;
item.MaxSobreturnos = varMaxSobreturnos;
item.CitarPorBloques = varCitarPorBloques;
item.FechaModificacion = varFechaModificacion;
item.HoraModificacion = varHoraModificacion;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdAuditoriaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdAgendaColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdAgendaEstadoColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdEfectorColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn IdServicioColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn IdProfesionalColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn IdEspecialidadColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn IdConsultorioColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn IdUsuarioColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn HoraInicioColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn HoraFinColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn DuracionColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn ReservadosColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn MaxSobreturnosColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn CitarPorBloquesColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn FechaModificacionColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn HoraModificacionColumn
{
get { return Schema.Columns[17]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdAuditoria = @"idAuditoria";
public static string IdAgenda = @"idAgenda";
public static string IdAgendaEstado = @"idAgendaEstado";
public static string IdEfector = @"idEfector";
public static string IdServicio = @"idServicio";
public static string IdProfesional = @"idProfesional";
public static string IdEspecialidad = @"idEspecialidad";
public static string IdConsultorio = @"idConsultorio";
public static string IdUsuario = @"idUsuario";
public static string Fecha = @"fecha";
public static string HoraInicio = @"horaInicio";
public static string HoraFin = @"horaFin";
public static string Duracion = @"duracion";
public static string Reservados = @"reservados";
public static string MaxSobreturnos = @"maxSobreturnos";
public static string CitarPorBloques = @"citarPorBloques";
public static string FechaModificacion = @"fechaModificacion";
public static string HoraModificacion = @"horaModificacion";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// <copyright file="MainWindowForm.cs" company="Public Domain">
// Released into the public domain
// </copyright>
// This file is part of the C# Packet Capture Analyser application. It is
// free and unencumbered software released into the public domain as detailed
// in the UNLICENSE file in the top level directory of this distribution
namespace PacketCaptureAnalyzer
{
using System.Linq; // Required to be able to use Any method
/// <summary>
/// This class provides the main window form
/// </summary>
public partial class MainWindowForm : System.Windows.Forms.Form
{
/// <summary>
/// The path of the selected packet capture
/// </summary>
private string theSelectedPacketCapturePath;
/// <summary>
/// The type of the selected packet capture
/// </summary>
private MainWindowFormConstants.PacketCaptureType theSelectedPacketCaptureType;
/// <summary>
/// The class provides the latency analysis processing
/// </summary>
private Analysis.LatencyAnalysis.Processing theLatencyAnalysisProcessing = null;
/// <summary>
/// The class provides the burst analysis processing
/// </summary>
private Analysis.BurstAnalysis.Processing theBurstAnalysisProcessing = null;
/// <summary>
/// The class provides the time analysis processing
/// </summary>
private Analysis.TimeAnalysis.Processing theTimeAnalysisProcessing = null;
/// <summary>
/// Initializes a new instance of the MainWindowForm class
/// </summary>
public MainWindowForm()
{
this.InitializeComponent();
// Clear the selected packet capture on window form creation
this.ClearSelectedPacketCapture(this);
}
//// Packet capture type
/// <summary>
/// Checks if the indicated packet capture has an expected type
/// </summary>
/// <param name="thePath">The path of the packet capture</param>
/// <returns>>Boolean flag that indicates whether the indicated packet capture has an expected type</returns>
private static bool IsExpectedPacketCaptureType(string thePath)
{
bool theResult = true;
string theFileExtension = System.IO.Path.GetExtension(thePath);
// Check if this is an expected type for a packet capture
// Determine the type of the packet capture from the file extension
// Does the file extension match one of the expected values for a packet capture?
if (MainWindowFormConstants.ExpectedPCAPNextGenerationPacketCaptureFileExtensions.Any(theFileExtension.Equals) ||
MainWindowFormConstants.ExpectedPCAPPacketCaptureFileExtensions.Any(theFileExtension.Equals) ||
MainWindowFormConstants.ExpectedNASnifferDOSPacketCaptureFileExtensions.Any(theFileExtension.Equals))
{
// This file is a supported type for a packet capture
// Any changes to this set of supported types should also be reflected to the Selected Packet Capture For Analysis dialog!
}
else
{
// This file is an unsupported type for a packet capture
theResult = false;
}
return theResult;
}
//// Button and checkbox click actions
/// <summary>
/// Processes the button click event for the "Select Packet Capture" button
/// </summary>
/// <param name="sender">The sender for the button click event</param>
/// <param name="e">The arguments for the button click event</param>
private void SelectPacketCaptureButton_Click(object sender, System.EventArgs e)
{
// Open the packet capture selection dialog box
System.Windows.Forms.DialogResult theSelectedPacketCaptureDialogResult =
this.theSelectPacketCaptureForAnalysisDialog.ShowDialog();
if (theSelectedPacketCaptureDialogResult == System.Windows.Forms.DialogResult.OK)
{
// Update the window to reflect the selected packet capture
this.ReflectSelectedPacketCapture(this.theSelectPacketCaptureForAnalysisDialog.FileName, sender);
}
}
/// <summary>
/// Processes the button click event for the "Clear Selected Packet Capture" button
/// </summary>
/// <param name="sender">The sender for the button click event</param>
/// <param name="e">The arguments for the button click event</param>
private void ClearSelectedPacketCaptureButton_Click(object sender, System.EventArgs e)
{
// Clear the selected packet capture on user request
this.ClearSelectedPacketCapture(sender);
}
/// <summary>
/// Processes the button click event for the "Open Selected Packet Capture" button
/// </summary>
/// <param name="sender">The sender for the button click event</param>
/// <param name="e">The arguments for the button click event</param>
private void OpenSelectedPackageCaptureButton_Click(object sender, System.EventArgs e)
{
if (System.IO.File.Exists(this.theSelectedPacketCapturePath))
{
try
{
System.Diagnostics.Process.Start(this.theSelectedPacketCapturePath);
}
catch (System.ComponentModel.Win32Exception f)
{
System.Diagnostics.Debug.WriteLine(
"The exception " +
f.GetType().Name +
" with the following message: " +
f.Message +
" was raised as there is no application registered that can open the " +
System.IO.Path.GetFileName(this.theSelectedPacketCapturePath) +
" packet capture!!!");
}
}
}
/// <summary>
/// Processes the check changed event for the "Enable" check box in the "Debug Information" group box
/// </summary>
/// <param name="sender">The sender for the check changed event</param>
/// <param name="e">The arguments for the check changed event</param>
private void EnableDebugInformationCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
// Guard against infinite recursion
if ((sender as System.Windows.Forms.Control).ContainsFocus)
{
if (this.theEnableDebugInformationCheckBox.Checked)
{
this.EnablePacketCaptureAnalysisCheckBoxes(sender);
}
else
{
this.DisablePacketCaptureAnalysisCheckBoxes(sender);
}
}
}
/// <summary>
/// Processes the check changed event for the "Perform" check box in the "Latency Analysis" group box
/// </summary>
/// <param name="sender">The sender for the check changed event</param>
/// <param name="e">The arguments for the check changed event</param>
private void PerformLatencyAnalysisCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
// Guard against infinite recursion
if ((sender as System.Windows.Forms.Control).ContainsFocus)
{
if (this.thePerformLatencyAnalysisCheckBox.Checked)
{
this.theOutputLatencyAnalysisHistogramCheckBox.Checked = false;
this.theOutputLatencyAnalysisHistogramCheckBox.Enabled = true;
this.theOutputAdditionalLatencyAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalLatencyAnalysisInformationCheckBox.Enabled = true;
}
else
{
this.theOutputLatencyAnalysisHistogramCheckBox.Checked = false;
this.theOutputLatencyAnalysisHistogramCheckBox.Enabled = false;
this.theOutputAdditionalLatencyAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalLatencyAnalysisInformationCheckBox.Enabled = false;
}
}
}
/// <summary>
/// Processes the check changed event for the "Perform" check box in the "Burst Analysis" group box
/// </summary>
/// <param name="sender">The sender for the check changed event</param>
/// <param name="e">The arguments for the check changed event</param>
private void PerformBurstAnalysisCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
// Guard against infinite recursion
if ((sender as System.Windows.Forms.Control).ContainsFocus)
{
if (this.thePerformBurstAnalysisCheckBox.Checked)
{
this.theOutputBurstAnalysisHistogramCheckBox.Checked = false;
this.theOutputBurstAnalysisHistogramCheckBox.Enabled = true;
this.theOutputAdditionalBurstAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalBurstAnalysisInformationCheckBox.Enabled = true;
}
else
{
this.theOutputBurstAnalysisHistogramCheckBox.Checked = false;
this.theOutputBurstAnalysisHistogramCheckBox.Enabled = false;
this.theOutputAdditionalBurstAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalBurstAnalysisInformationCheckBox.Enabled = false;
}
}
}
/// <summary>
/// Processes the check changed event for the "Perform" check box in the "Time Analysis" group box
/// </summary>
/// <param name="sender">The sender for the check changed event</param>
/// <param name="e">The arguments for the check changed event</param>
private void PerformTimeAnalysisCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
// Guard against infinite recursion
if ((sender as System.Windows.Forms.Control).ContainsFocus)
{
if (this.thePerformTimeAnalysisCheckBox.Checked)
{
this.theOutputTimeAnalysisTimestampHistogramCheckBox.Checked = false;
this.theOutputTimeAnalysisTimestampHistogramCheckBox.Enabled = true;
this.theOutputTimeAnalysisTimeHistogramCheckBox.Checked = false;
this.theOutputTimeAnalysisTimeHistogramCheckBox.Enabled = true;
this.theOutputAdditionalTimeAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalTimeAnalysisInformationCheckBox.Enabled = true;
}
else
{
this.theOutputTimeAnalysisTimestampHistogramCheckBox.Checked = false;
this.theOutputTimeAnalysisTimestampHistogramCheckBox.Enabled = false;
this.theOutputTimeAnalysisTimeHistogramCheckBox.Checked = false;
this.theOutputTimeAnalysisTimeHistogramCheckBox.Enabled = false;
this.theOutputAdditionalTimeAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalTimeAnalysisInformationCheckBox.Enabled = false;
}
}
}
/// <summary>
/// Processes the button click event for the "Run Analysis On Packet Capture" button
/// </summary>
/// <param name="sender">The sender for the button click event</param>
/// <param name="e">The arguments for the button click event</param>
private void RunAnalysisOnPacketCaptureButton_Click(object sender, System.EventArgs e)
{
this.AnalysePacketCapture();
}
/// <summary>
/// Processes the button click event for the "Exit" button
/// </summary>
/// <param name="sender">The sender for the button click event</param>
/// <param name="e">The arguments for the button click event</param>
private void ExitButton_Click(object sender, System.EventArgs e)
{
this.Close();
}
//// Drag and drop actions
/// <summary>
/// Processes the drag enter event on dragging a file into the main window form
/// </summary>
/// <param name="sender">The sender for the drag enter event</param>
/// <param name="e">The arguments for the drag enter event</param>
private void MainWindowForm_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
// Get the set of the files dragged and dropped into the main window form
// Will only use the first of the set as single file processing is the existing pattern for this application
string[] theFiles = (string[])e.Data.GetData(System.Windows.Forms.DataFormats.FileDrop);
// Check if this is an expected type for a packet capture
if (IsExpectedPacketCaptureType(theFiles[0]))
{
// This file is a supported type for a packet capture so start so allow the drag into the main window form
if (e.Data.GetDataPresent(System.Windows.Forms.DataFormats.FileDrop))
{
e.Effect = System.Windows.Forms.DragDropEffects.Copy;
}
else
{
e.Effect = System.Windows.Forms.DragDropEffects.None;
}
}
else
{
// This file is either an unsupported type for a packet capture or is another type of file so prevent the drag into the main window form
e.Effect = System.Windows.Forms.DragDropEffects.None;
}
}
/// <summary>
/// Processes the drag drop event on dropping a file into the main window form
/// </summary>
/// <param name="sender">The sender for the drag drop event</param>
/// <param name="e">The arguments for the drag drop event</param>
private void MainWindowForm_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
// Get the set of the files dragged and dropped into the main window form
// Will only use the first of the set as single file processing is the existing pattern for this application
string[] theFiles = (string[])e.Data.GetData(System.Windows.Forms.DataFormats.FileDrop);
// Check if this is an expected type for a packet capture
if (IsExpectedPacketCaptureType(theFiles[0]))
{
// This file is a supported type for a packet capture so start processing it
// Update the window to reflect the selected packet capture
this.ReflectSelectedPacketCapture(theFiles[0], sender);
}
}
//// Packet capture support functions
/// <summary>
/// Reflects the selection of the indicated packet capture by setting up the associated items accordingly
/// </summary>
/// <param name="thePath">The path of the selected packet capture</param>
/// <param name="sender">The sender for the initiating event</param>
private void ReflectSelectedPacketCapture(string thePath, object sender)
{
// Store the path of the indicated packet capture for use by later processing
this.theSelectedPacketCapturePath = thePath;
System.Diagnostics.Debug.WriteLine(
"Selection of the " +
System.IO.Path.GetFileName(this.theSelectedPacketCapturePath) +
" packet capture");
// Determine the type of the packet capture
this.DeterminePacketCaptureType();
switch (this.theSelectedPacketCaptureType)
{
case MainWindowFormConstants.PacketCaptureType.PCAPNextGeneration:
{
//// Analysis of a PCAP Next Generation packet capture is supported
// Enable the "Selected Packet Capture" group box
this.theSelectedPacketCaptureGroupBox.Enabled = true;
// Populate the path for the selected packet capture
this.theSelectedPacketCapturePathTextBox.Text =
System.IO.Path.GetDirectoryName(
this.theSelectedPacketCapturePath);
// Populate the name for the selected packet capture
this.theSelectedPacketCaptureNameTextBox.Text =
System.IO.Path.GetFileName(
this.theSelectedPacketCapturePath);
// This is a PCAP Next Generation packet capture
this.theSelectedPacketCaptureTypeTextBox.Text =
Properties.Resources.PCAPNextGeneration;
// Enable the buttons
this.EnablePacketCaptureAnalysisButtons();
// Reset and enable the check boxes
this.EnablePacketCaptureAnalysisCheckBoxes(sender);
break;
}
case MainWindowFormConstants.PacketCaptureType.PCAP:
{
//// Analysis of a PCAP packet capture is supported
// Enable the "Selected Packet Capture" group box
this.theSelectedPacketCaptureGroupBox.Enabled = true;
// Populate the path for the selected packet capture
this.theSelectedPacketCapturePathTextBox.Text =
System.IO.Path.GetDirectoryName(
this.theSelectedPacketCapturePath);
// Populate the name for the selected packet capture
this.theSelectedPacketCaptureNameTextBox.Text =
System.IO.Path.GetFileName(
this.theSelectedPacketCapturePath);
// This is a PCAP packet capture
this.theSelectedPacketCaptureTypeTextBox.Text =
Properties.Resources.PCAP;
// Enable the buttons
this.EnablePacketCaptureAnalysisButtons();
// Reset and enable the check boxes
this.EnablePacketCaptureAnalysisCheckBoxes(sender);
break;
}
case MainWindowFormConstants.PacketCaptureType.NASnifferDOS:
{
//// Analysis of an NA Sniffer (DOS) packet capture is supported
// Enable the "Selected Packet Capture" group box
this.theSelectedPacketCaptureGroupBox.Enabled = true;
// Populate the path for the selected packet capture
this.theSelectedPacketCapturePathTextBox.Text =
System.IO.Path.GetDirectoryName(
this.theSelectedPacketCapturePath);
// Populate the name for the selected packet capture
this.theSelectedPacketCaptureNameTextBox.Text =
System.IO.Path.GetFileName(
this.theSelectedPacketCapturePath);
// This is an NA Sniffer (DOS) packet capture
this.theSelectedPacketCaptureTypeTextBox.Text =
Properties.Resources.NASnifferDOS;
// Enable the buttons
this.EnablePacketCaptureAnalysisButtons();
// Reset and enable the check boxes
this.EnablePacketCaptureAnalysisCheckBoxes(sender);
break;
}
case MainWindowFormConstants.PacketCaptureType.Incorrect:
{
//// Analysis of this packet capture is not supported
// Enable the "Selected Packet Capture" group box
this.theSelectedPacketCaptureGroupBox.Enabled = true;
// Populate the path for the selected packet capture
this.theSelectedPacketCapturePathTextBox.Text =
System.IO.Path.GetDirectoryName(
this.theSelectedPacketCapturePath);
// Populate the name for the selected packet capture
this.theSelectedPacketCaptureNameTextBox.Text =
System.IO.Path.GetFileName(
this.theSelectedPacketCapturePath);
// This packet capture has an incorrect file extension for the form of packet capture it contains
this.theSelectedPacketCaptureTypeTextBox.Text =
"<Incorrect Packet Capture Type For File Extension>";
// Reset the buttons
this.ResetPacketCaptureAnalysisButtons();
// Reset and disable the check boxes
this.DisablePacketCaptureAnalysisCheckBoxes(sender);
break;
}
case MainWindowFormConstants.PacketCaptureType.Unknown:
default:
{
//// Analysis of this packet capture is not supported
// Enable the "Selected Packet Capture" group box
this.theSelectedPacketCaptureGroupBox.Enabled = true;
// Populate the path for the selected packet capture
this.theSelectedPacketCapturePathTextBox.Text =
System.IO.Path.GetDirectoryName(
this.theSelectedPacketCapturePath);
// Populate the name for the selected packet capture
this.theSelectedPacketCaptureNameTextBox.Text =
System.IO.Path.GetFileName(
this.theSelectedPacketCapturePath);
// This packet capture is either an unsupported form of packet capture or is another type of file
this.theSelectedPacketCaptureTypeTextBox.Text =
"<Unknown Packet Capture Type>";
// Reset the buttons
this.ResetPacketCaptureAnalysisButtons();
// Reset and disable the check boxes
this.DisablePacketCaptureAnalysisCheckBoxes(sender);
break;
}
}
}
/// <summary>
/// Clears the currently selected packet capture and resets the associated items
/// </summary>
/// <param name="sender">The sender for the initiating event</param>
private void ClearSelectedPacketCapture(object sender)
{
this.theSelectedPacketCapturePath = null;
this.theSelectedPacketCaptureType =
MainWindowFormConstants.PacketCaptureType.Unknown;
// Disable the "Selected Packet Capture" group box
this.theSelectedPacketCaptureGroupBox.Enabled = false;
// Clear the path, name and type for the selected packet capture
this.theSelectedPacketCapturePathTextBox.Text = string.Empty;
this.theSelectedPacketCaptureNameTextBox.Text = string.Empty;
this.theSelectedPacketCaptureTypeTextBox.Text = string.Empty;
// Disable the button to clear the selected package capture
this.theClearSelectedPacketCaptureButton.Enabled = false;
// Disable the button to open the package capture
this.theOpenSelectedPackageCaptureButton.Enabled = false;
// Disable the button to start the analysis on the packet capture
this.theRunAnalysisOnSelectedPackageCaptureButton.Enabled = false;
// Reset and disable the check boxes
this.DisablePacketCaptureAnalysisCheckBoxes(sender);
}
//// Packet capture type
/// <summary>
/// Determines the type of the packet capture from the initial bytes and ensure that it is of the expected type for the file extension
/// </summary>
private void DeterminePacketCaptureType()
{
//// Determine the type of the packet capture
// Declare a file stream for the packet capture for reading
System.IO.FileStream theFileStream = null;
// Use a try/finally pattern to avoid multiple disposals of a resource
try
{
// Open a file stream for the packet capture for reading
theFileStream = System.IO.File.OpenRead(this.theSelectedPacketCapturePath);
// Open a binary reader for the file stream for the packet capture
using (System.IO.BinaryReader theBinaryReader =
new System.IO.BinaryReader(theFileStream))
{
// The resources for the file stream for the packet capture will be disposed of by the binary reader so set it back to null here to prevent the finally clause performing an additional disposal
theFileStream = null;
string theFileExtension = System.IO.Path.GetExtension(this.theSelectedPacketCapturePath);
switch (theBinaryReader.ReadUInt32())
{
case (uint)PacketCapture.PCAPNGPackageCapture.Constants.BlockType.SectionHeaderBlock:
{
if (MainWindowFormConstants.ExpectedPCAPNextGenerationPacketCaptureFileExtensions.Any(theFileExtension.Equals))
{
// This is a PCAP Next Generation packet capture
this.theSelectedPacketCaptureType =
MainWindowFormConstants.PacketCaptureType.PCAPNextGeneration;
}
else
{
System.Diagnostics.Debug.WriteLine(
"The " +
System.IO.Path.GetFileName(this.theSelectedPacketCapturePath) +
" packet capture should be a PCAP Next Generation packet capture based on its initial bytes, but its file extension " +
theFileExtension +
" is incorrect for that type of packet capture!!!");
this.theSelectedPacketCaptureType =
MainWindowFormConstants.PacketCaptureType.Incorrect;
}
break;
}
case (uint)PacketCapture.PCAPPackageCapture.Constants.LittleEndianMagicNumber:
case (uint)PacketCapture.PCAPPackageCapture.Constants.BigEndianMagicNumber:
{
if (MainWindowFormConstants.ExpectedPCAPPacketCaptureFileExtensions.Any(theFileExtension.Equals))
{
// This is a PCAP packet capture
this.theSelectedPacketCaptureType =
MainWindowFormConstants.PacketCaptureType.PCAP;
}
else
{
System.Diagnostics.Debug.WriteLine(
"The " +
System.IO.Path.GetFileName(this.theSelectedPacketCapturePath) +
" packet capture should be a PCAP packet capture based on its initial bytes, but its file extension " +
theFileExtension +
" is incorrect for that type of packet capture!!!");
this.theSelectedPacketCaptureType =
MainWindowFormConstants.PacketCaptureType.Incorrect;
}
break;
}
case (uint)PacketCapture.SnifferPackageCapture.Constants.ExpectedMagicNumberHighest:
{
if (MainWindowFormConstants.ExpectedNASnifferDOSPacketCaptureFileExtensions.Any(theFileExtension.Equals))
{
// This is an NA Sniffer (DOS) packet capture
this.theSelectedPacketCaptureType =
MainWindowFormConstants.PacketCaptureType.NASnifferDOS;
}
else
{
System.Diagnostics.Debug.WriteLine(
"The " +
System.IO.Path.GetFileName(this.theSelectedPacketCapturePath) +
" packet capture should be an NA Sniffer (DOS) packet capture based on its initial bytes, but its file extension " +
theFileExtension +
" is incorrect for that type of packet capture!!!");
this.theSelectedPacketCaptureType =
MainWindowFormConstants.PacketCaptureType.Incorrect;
}
break;
}
default:
{
// This packet capture is either an unsupported form of packet capture or is another type of file
this.theSelectedPacketCaptureType =
MainWindowFormConstants.PacketCaptureType.Unknown;
break;
}
}
}
}
finally
{
// Dispose of the resources for the file stream for the packet capture if this action has not already taken place above
if (theFileStream != null)
{
theFileStream.Dispose();
}
}
}
/// <summary>
/// Performs analysis of the currently selected packet capture
/// </summary>
private void AnalysePacketCapture()
{
bool theResult = true;
// Declare an instance of the progress window form
ProgressWindowForm theProgressWindowForm = null;
// Use a try/finally pattern to avoid multiple disposals of a resource
try
{
// Create an instance of the progress window form
theProgressWindowForm = new PacketCaptureAnalyzer.ProgressWindowForm();
// Show the progress window form now the analysis has started
theProgressWindowForm.Show();
theProgressWindowForm.Activate();
// Update the label now the reading of the packet capture has started - the progress bar will stay at zero
theProgressWindowForm.ProgressBarLabel = "Reading Packet Capture Into System Memory";
theProgressWindowForm.ProgressBar = 0;
theProgressWindowForm.Refresh();
theProgressWindowForm.ProgressBar = 5;
// Obtain the name of the packet capture
string thePacketCaptureFileName =
System.IO.Path.GetFileName(
this.theSelectedPacketCapturePath);
theProgressWindowForm.ProgressBar = 10;
using (Analysis.DebugInformation theDebugInformation =
new Analysis.DebugInformation(
this.theSelectedPacketCapturePath + ".txt",
this.theEnableDebugInformationCheckBox.Checked,
this.theEnableInformationEventsInDebugInformationCheckBox.Checked,
this.theRedirectDebugInformationToOutputCheckBox.Checked))
{
theProgressWindowForm.ProgressBar = 20;
// Start the processing of the packet capture
theDebugInformation.WriteTestRunEvent(
"Processing of the " +
thePacketCaptureFileName +
" packet capture started");
theDebugInformation.WriteBlankLine();
theDebugInformation.WriteTextLine(
new string('=', 144));
theDebugInformation.WriteBlankLine();
// Perform the actions to initialize the analysis of the packet capture
theResult = this.InitialiseAnalysisForPacketCapture(
theDebugInformation,
theProgressWindowForm,
thePacketCaptureFileName);
// Dependent on the result of the processing above, display a debug message to indicate success or otherwise
if (theResult)
{
// Display a debug message to indicate parsing of the packet capture completed successfully
theDebugInformation.WriteTestRunEvent(
"Parsing of the " +
thePacketCaptureFileName +
" packet capture completed successfully");
// Perform the actions to analyze the packet capture
theResult = this.PerformAnalysisForPacketCapture(
theDebugInformation,
theProgressWindowForm,
thePacketCaptureFileName);
theDebugInformation.WriteBlankLine();
theDebugInformation.WriteTextLine(
new string('=', 144));
theDebugInformation.WriteBlankLine();
// Completed the processing of the packet capture
theDebugInformation.WriteTestRunEvent(
"Processing of the " +
thePacketCaptureFileName +
" packet capture completed");
}
else
{
theDebugInformation.WriteBlankLine();
theDebugInformation.WriteTextLine(
new string('=', 144));
theDebugInformation.WriteBlankLine();
// Display a debug message to indicate processing of the packet capture failed
theDebugInformation.WriteErrorEvent(
"Processing of the " +
thePacketCaptureFileName +
" packet capture failed!!!");
}
if (theProgressWindowForm != null)
{
// Hide and close the progress window form now the analysis has completed
theProgressWindowForm.Hide();
theProgressWindowForm.Close();
// The resources for the progress window form will have been disposed by closing it so prevent the finally clause performing an additional disposal
theProgressWindowForm = null;
}
//// Dependent on the result of the processing above, display a message box to indicate success or otherwise
System.Windows.Forms.DialogResult theMessageBoxResult;
System.Windows.Forms.MessageBoxOptions theMessageBoxOptions =
new System.Windows.Forms.MessageBoxOptions();
if (System.Globalization.CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft)
{
theMessageBoxOptions |=
System.Windows.Forms.MessageBoxOptions.RtlReading |
System.Windows.Forms.MessageBoxOptions.RightAlign;
}
if (theResult)
{
if (this.theEnableDebugInformationCheckBox.Checked)
{
// Display a message box to indicate analysis of the packet capture completed successfully and ask whether to open the output file
theMessageBoxResult =
System.Windows.Forms.MessageBox.Show(
Properties.Resources.AnalysisOfThePacketCaptureCompletedSuccessfully +
System.Environment.NewLine +
System.Environment.NewLine +
Properties.Resources.DoYouWantToOpenTheOutputFile,
Properties.Resources.RunAnalysisOnSelectedPacketCapture,
System.Windows.Forms.MessageBoxButtons.YesNo,
System.Windows.Forms.MessageBoxIcon.Question,
System.Windows.Forms.MessageBoxDefaultButton.Button1,
theMessageBoxOptions);
}
else
{
// Display a message box to indicate analysis of the packet capture completed successfully
theMessageBoxResult =
System.Windows.Forms.MessageBox.Show(
Properties.Resources.AnalysisOfThePacketCaptureCompletedSuccessfully,
Properties.Resources.RunAnalysisOnSelectedPacketCapture,
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Information,
System.Windows.Forms.MessageBoxDefaultButton.Button1,
theMessageBoxOptions);
}
}
else
{
if (this.theEnableDebugInformationCheckBox.Checked)
{
// Display a message box to indicate analysis of the packet capture failed and ask whether to open the output file
theMessageBoxResult =
System.Windows.Forms.MessageBox.Show(
Properties.Resources.AnalysisOfThePacketCaptureFailed +
System.Environment.NewLine +
System.Environment.NewLine +
Properties.Resources.DoYouWantToOpenTheOutputFile,
Properties.Resources.RunAnalysisOnSelectedPacketCapture,
System.Windows.Forms.MessageBoxButtons.YesNo,
System.Windows.Forms.MessageBoxIcon.Error,
System.Windows.Forms.MessageBoxDefaultButton.Button1,
theMessageBoxOptions);
}
else
{
// Display a message box to indicate analysis of the packet capture failed
theMessageBoxResult =
System.Windows.Forms.MessageBox.Show(
Properties.Resources.AnalysisOfThePacketCaptureFailed,
Properties.Resources.RunAnalysisOnSelectedPacketCapture,
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error,
System.Windows.Forms.MessageBoxDefaultButton.Button1,
theMessageBoxOptions);
}
}
//// Dispose of the resources for the analysis processing if these actions have not already taken place above
if (this.theLatencyAnalysisProcessing != null)
{
this.theLatencyAnalysisProcessing.Dispose();
}
if (this.theBurstAnalysisProcessing != null)
{
this.theBurstAnalysisProcessing.Dispose();
}
if (this.theTimeAnalysisProcessing != null)
{
this.theTimeAnalysisProcessing.Dispose();
}
// Dependent on the button selection at the message box, open the output file
if (theMessageBoxResult == System.Windows.Forms.DialogResult.Yes)
{
theDebugInformation.Open();
}
}
}
finally
{
// Dispose of the resources for the progress window form if this action has not already taken place above
if (theProgressWindowForm != null)
{
theProgressWindowForm.Dispose();
}
}
}
/// <summary>
/// Performs the actions to initialize the analysis of the packet capture
/// </summary>
/// <param name="theDebugInformation">The object that provides for the logging of debug information</param>
/// <param name="theProgressWindowForm">The progress window form</param>
/// <param name="thePacketCaptureFileName">The name of the packet capture</param>
/// <returns>Boolean flag that indicates whether the actions to initialize the analysis of the packet capture was successful</returns>
private bool InitialiseAnalysisForPacketCapture(Analysis.DebugInformation theDebugInformation, ProgressWindowForm theProgressWindowForm, string thePacketCaptureFileName)
{
bool theResult = true;
theProgressWindowForm.ProgressBar = 30;
// Only perform the latency analysis if the check box was selected for it on the main window form
if (this.thePerformLatencyAnalysisCheckBox.Checked)
{
this.theLatencyAnalysisProcessing =
new Analysis.LatencyAnalysis.Processing(
theDebugInformation,
this.theOutputLatencyAnalysisHistogramCheckBox.Checked,
this.theOutputAdditionalLatencyAnalysisInformationCheckBox.Checked,
this.theSelectedPacketCapturePath);
// Initialise the functionality to perform latency analysis on the messages found
this.theLatencyAnalysisProcessing.Create();
}
theProgressWindowForm.ProgressBar = 35;
// Only perform the burst analysis if the check box was selected for it on the main window form
if (this.thePerformBurstAnalysisCheckBox.Checked)
{
this.theBurstAnalysisProcessing =
new Analysis.BurstAnalysis.Processing(
theDebugInformation,
this.theOutputBurstAnalysisHistogramCheckBox.Checked,
this.theOutputAdditionalBurstAnalysisInformationCheckBox.Checked,
this.theSelectedPacketCapturePath);
// Initialise the functionality to perform burst analysis on the messages found
this.theBurstAnalysisProcessing.Create();
}
theProgressWindowForm.ProgressBar = 40;
// Only perform the time analysis if the check box was selected for it on the main window form
if (this.thePerformTimeAnalysisCheckBox.Checked)
{
this.theTimeAnalysisProcessing =
new Analysis.TimeAnalysis.Processing(
theDebugInformation,
this.theOutputTimeAnalysisTimestampHistogramCheckBox.Checked,
this.theOutputTimeAnalysisTimeHistogramCheckBox.Checked,
this.theOutputAdditionalTimeAnalysisInformationCheckBox.Checked,
this.theSelectedPacketCapturePath);
// Initialise the functionality to perform time analysis on the messages found
this.theTimeAnalysisProcessing.Create();
}
theProgressWindowForm.ProgressBar = 45;
switch (this.theSelectedPacketCaptureType)
{
case MainWindowFormConstants.PacketCaptureType.PCAPNextGeneration:
{
theDebugInformation.WriteInformationEvent(
"This is a PCAP Next Generation packet capture");
PacketCapture.PCAPNGPackageCapture.Processing thePCAPNGPackageCaptureProcessing =
new PacketCapture.PCAPNGPackageCapture.Processing(
theProgressWindowForm,
theDebugInformation,
this.thePerformLatencyAnalysisCheckBox.Checked,
this.theLatencyAnalysisProcessing,
this.thePerformBurstAnalysisCheckBox.Checked,
this.theBurstAnalysisProcessing,
this.thePerformTimeAnalysisCheckBox.Checked,
this.theTimeAnalysisProcessing,
this.theSelectedPacketCapturePath,
this.theUseAlternativeSequenceNumberCheckBox.Checked,
this.theMinimizeMemoryUsageCheckBox.Checked);
theProgressWindowForm.ProgressBar = 50;
theResult = thePCAPNGPackageCaptureProcessing.ProcessPacketCapture();
break;
}
case MainWindowFormConstants.PacketCaptureType.PCAP:
{
theDebugInformation.WriteInformationEvent(
"This is a PCAP packet capture");
PacketCapture.PCAPPackageCapture.Processing thePCAPPackageCaptureProcessing =
new PacketCapture.PCAPPackageCapture.Processing(
theProgressWindowForm,
theDebugInformation,
this.thePerformLatencyAnalysisCheckBox.Checked,
this.theLatencyAnalysisProcessing,
this.thePerformBurstAnalysisCheckBox.Checked,
this.theBurstAnalysisProcessing,
this.thePerformTimeAnalysisCheckBox.Checked,
this.theTimeAnalysisProcessing,
this.theSelectedPacketCapturePath,
this.theUseAlternativeSequenceNumberCheckBox.Checked,
this.theMinimizeMemoryUsageCheckBox.Checked);
theProgressWindowForm.ProgressBar = 50;
theResult = thePCAPPackageCaptureProcessing.ProcessPacketCapture();
break;
}
case MainWindowFormConstants.PacketCaptureType.NASnifferDOS:
{
theDebugInformation.WriteInformationEvent(
"This is an NA Sniffer (DOS) packet capture");
PacketCapture.SnifferPackageCapture.Processing theSnifferPackageCaptureProcessing =
new PacketCapture.SnifferPackageCapture.Processing(
theProgressWindowForm,
theDebugInformation,
this.thePerformLatencyAnalysisCheckBox.Checked,
this.theLatencyAnalysisProcessing,
this.thePerformBurstAnalysisCheckBox.Checked,
this.theBurstAnalysisProcessing,
this.thePerformTimeAnalysisCheckBox.Checked,
this.theTimeAnalysisProcessing,
this.theSelectedPacketCapturePath,
this.theUseAlternativeSequenceNumberCheckBox.Checked,
this.theMinimizeMemoryUsageCheckBox.Checked);
theProgressWindowForm.ProgressBar = 50;
theResult = theSnifferPackageCaptureProcessing.ProcessPacketCapture();
break;
}
default:
{
theDebugInformation.WriteErrorEvent(
"The" +
thePacketCaptureFileName +
" packet capture is of an unknown or incorrect type!!!");
theResult = false;
break;
}
}
return theResult;
}
/// <summary>
/// Performs the actions to analyze the packet capture
/// </summary>
/// <param name="theDebugInformation">The object that provides for the logging of debug information</param>
/// <param name="theProgressWindowForm">The progress window form</param>
/// <param name="thePacketCaptureFileName">The name of the packet capture</param>
/// <returns>Boolean flag that indicates whether performing the actions to analyze the packet capture was successful</returns>
private bool PerformAnalysisForPacketCapture(Analysis.DebugInformation theDebugInformation, ProgressWindowForm theProgressWindowForm, string thePacketCaptureFileName)
{
bool theResult = true;
int theScaling = 0;
if (this.thePerformLatencyAnalysisCheckBox.Checked ||
this.thePerformTimeAnalysisCheckBox.Checked ||
this.thePerformBurstAnalysisCheckBox.Checked)
{
// Update the label now the analysis of the packet capture has started - the progress bar will stay at zero
theProgressWindowForm.ProgressBarLabel = "Performing Analysis Of Packet Capture";
theProgressWindowForm.ProgressBar = 0;
theProgressWindowForm.Refresh();
// Calculate the scaling to use for the progress bar
if (this.thePerformLatencyAnalysisCheckBox.Checked &&
!this.thePerformTimeAnalysisCheckBox.Checked)
{
// Only one set of analysis will be run
theScaling = 1;
}
else if (!this.thePerformLatencyAnalysisCheckBox.Checked &&
this.thePerformTimeAnalysisCheckBox.Checked)
{
// Only one set of analysis will be run
theScaling = 1;
}
else
{
// Both sets of analysis will be run
theScaling = 2;
}
}
// Only perform the latency analysis if the check box was selected for it on the main window form
if (this.thePerformLatencyAnalysisCheckBox.Checked)
{
theDebugInformation.WriteBlankLine();
theDebugInformation.WriteTextLine(
new string('=', 144));
theDebugInformation.WriteBlankLine();
//// Finalise the latency analysis on the messages found including printing the results to debug output
//// Only perform this action if the analysis of the packet capture completed successfully
// Read the start time to allow later calculation of the duration of the latency analysis finalisation
System.DateTime theLatencyAnalysisStartTime = System.DateTime.Now;
theDebugInformation.WriteTestRunEvent(
"Latency analysis for the " +
thePacketCaptureFileName +
" packet capture started");
theProgressWindowForm.ProgressBar += 20 / theScaling;
this.theLatencyAnalysisProcessing.Finalise();
theProgressWindowForm.ProgressBar += 60 / theScaling;
//// Compute the duration between the start and the end times
System.DateTime theLatencyAnalysisEndTime = System.DateTime.Now;
System.TimeSpan theLatencyAnalysisDuration =
theLatencyAnalysisEndTime - theLatencyAnalysisStartTime;
theDebugInformation.WriteTestRunEvent(
"Latency analysis for the " +
thePacketCaptureFileName +
" packet capture completed in " +
theLatencyAnalysisDuration.TotalSeconds.ToString(System.Globalization.CultureInfo.CurrentCulture) +
" seconds");
theProgressWindowForm.ProgressBar += 20 / theScaling;
}
// Only perform the burst analysis if the check box was selected for it on the main window form
if (this.thePerformBurstAnalysisCheckBox.Checked)
{
theDebugInformation.WriteBlankLine();
theDebugInformation.WriteTextLine(
new string('=', 144));
theDebugInformation.WriteBlankLine();
//// Finalise the burst analysis on the messages found including printing the results to debug output
//// Only perform this action if the analysis of the packet capture completed successfully
// Read the start time to allow later calculation of the duration of the burst analysis finalisation
System.DateTime theBurstAnalysisStartTime = System.DateTime.Now;
theDebugInformation.WriteTestRunEvent(
"Burst analysis for the " +
thePacketCaptureFileName +
" packet capture started");
//// theProgressWindowForm.ProgressBar += 20 / theScaling;
this.theBurstAnalysisProcessing.Finalise();
//// theProgressWindowForm.ProgressBar += 60 / theScaling;
//// Compute the duration between the start and the end times
System.DateTime theBurstAnalysisEndTime = System.DateTime.Now;
System.TimeSpan theBurstAnalysisDuration =
theBurstAnalysisEndTime - theBurstAnalysisStartTime;
theDebugInformation.WriteTestRunEvent(
"Burst analysis for the " +
thePacketCaptureFileName +
" packet capture completed in " +
theBurstAnalysisDuration.TotalSeconds.ToString(System.Globalization.CultureInfo.CurrentCulture) +
" seconds");
//// theProgressWindowForm.ProgressBar += 20 / theScaling;
}
// Only perform the time analysis if the check box was selected for it on the main window form
if (this.thePerformTimeAnalysisCheckBox.Checked)
{
theDebugInformation.WriteBlankLine();
theDebugInformation.WriteTextLine(
new string('=', 144));
theDebugInformation.WriteBlankLine();
//// Finalise the time analysis on the messages found including printing the results to debug output
//// Only perform this action if the analysis of the packet capture completed successfully
// Read the start time to allow later calculation of the duration of the time analysis finalisation
System.DateTime theTimeAnalysisStartTime = System.DateTime.Now;
theDebugInformation.WriteTestRunEvent(
"Time analysis for the " +
thePacketCaptureFileName +
" packet capture started");
theProgressWindowForm.ProgressBar += 20 / theScaling;
this.theTimeAnalysisProcessing.Finalise();
theProgressWindowForm.ProgressBar += 60 / theScaling;
//// Compute the duration between the start and the end times
System.DateTime theTimeAnalysisEndTime = System.DateTime.Now;
System.TimeSpan theTimeAnalysisDuration =
theTimeAnalysisEndTime - theTimeAnalysisStartTime;
theDebugInformation.WriteTestRunEvent(
"Time analysis for the " +
thePacketCaptureFileName +
" packet capture completed in " +
theTimeAnalysisDuration.TotalSeconds.ToString(System.Globalization.CultureInfo.CurrentCulture) +
" seconds");
theProgressWindowForm.ProgressBar += 20 / theScaling;
}
return theResult;
}
//// Button support functions
/// <summary>
/// Enables the buttons concerned with packet capture analysis on the main window form
/// </summary>
private void EnablePacketCaptureAnalysisButtons()
{
//// Enable the buttons
// 1) Enable the button to clear the selected package capture
this.theClearSelectedPacketCaptureButton.Enabled = true;
// 2) Enable the button to open the package capture
this.theOpenSelectedPackageCaptureButton.Enabled = true;
// 3) Disable the button to start the analysis on the packet capture - enabled on selection of the output file
this.theRunAnalysisOnSelectedPackageCaptureButton.Enabled = true;
}
/// <summary>
/// Resets the buttons concerned with packet capture analysis on the main window form
/// </summary>
private void ResetPacketCaptureAnalysisButtons()
{
//// Reset the buttons
this.theClearSelectedPacketCaptureButton.Enabled = true;
this.theOpenSelectedPackageCaptureButton.Enabled = false;
this.theRunAnalysisOnSelectedPackageCaptureButton.Enabled = false;
}
//// Check box support functions
/// <summary>
/// Resets and then enables the check boxes (and group boxes) concerned with packet capture analysis on the main window form
/// </summary>
/// <param name="sender">The sender for the initiating event</param>
private void EnablePacketCaptureAnalysisCheckBoxes(object sender)
{
//// Enable the check boxes
// Guard against infinite recursion
if (sender != this.theEnableDebugInformationCheckBox)
{
this.theEnableDebugInformationCheckBox.Checked = true;
this.theEnableDebugInformationCheckBox.Enabled = true;
this.theDebugInformationGroupBox.Enabled = true;
}
// Match the state of the "Enable Information Events" check box to the state of the "Enable" check box
this.theEnableInformationEventsInDebugInformationCheckBox.Checked =
this.theEnableDebugInformationCheckBox.Checked;
this.theEnableInformationEventsInDebugInformationCheckBox.Enabled = true;
this.theRedirectDebugInformationToOutputCheckBox.Checked = false;
this.theRedirectDebugInformationToOutputCheckBox.Enabled = true;
this.theLatencyAnalysisGroupBox.Enabled = true;
this.thePerformLatencyAnalysisCheckBox.Checked = false;
this.thePerformLatencyAnalysisCheckBox.Enabled = true;
this.theOutputLatencyAnalysisHistogramCheckBox.Checked = false;
this.theOutputLatencyAnalysisHistogramCheckBox.Enabled = false;
this.theOutputAdditionalLatencyAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalLatencyAnalysisInformationCheckBox.Enabled = false;
this.theBurstAnalysisGroupBox.Enabled = true;
this.thePerformBurstAnalysisCheckBox.Checked = false;
this.thePerformBurstAnalysisCheckBox.Enabled = true;
this.theOutputBurstAnalysisHistogramCheckBox.Checked = false;
this.theOutputBurstAnalysisHistogramCheckBox.Enabled = false;
this.theOutputAdditionalBurstAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalBurstAnalysisInformationCheckBox.Enabled = false;
this.theTimeAnalysisGroupBox.Enabled = true;
this.thePerformTimeAnalysisCheckBox.Checked = false;
this.thePerformTimeAnalysisCheckBox.Enabled = true;
this.theOutputTimeAnalysisTimestampHistogramCheckBox.Checked = false;
this.theOutputTimeAnalysisTimestampHistogramCheckBox.Enabled = false;
this.theOutputTimeAnalysisTimeHistogramCheckBox.Checked = false;
this.theOutputTimeAnalysisTimeHistogramCheckBox.Enabled = false;
this.theOutputAdditionalTimeAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalTimeAnalysisInformationCheckBox.Enabled = false;
// Do not change the "Minimize Memory Usage" check box on a change to the "Enable" check box in the "Debug Information" group box
if (sender != this.theEnableDebugInformationCheckBox)
{
this.theUseAlternativeSequenceNumberCheckBox.Checked = false;
this.theUseAlternativeSequenceNumberCheckBox.Enabled = true;
this.theMinimizeMemoryUsageCheckBox.Checked = false;
this.theMinimizeMemoryUsageCheckBox.Enabled = true;
}
}
/// <summary>
/// Resets and then disables the check boxes (and group boxes) concerned with packet capture analysis on the main window form
/// </summary>
/// <param name="sender">The sender for the initiating event</param>
private void DisablePacketCaptureAnalysisCheckBoxes(object sender)
{
//// Disable the check boxes
// Guard against infinite recursion
if (sender != this.theEnableDebugInformationCheckBox)
{
this.theEnableDebugInformationCheckBox.Checked = false;
this.theEnableDebugInformationCheckBox.Enabled = false;
this.theDebugInformationGroupBox.Enabled = false;
}
// Match the state of the "Enable Information Events" check box to the state of the "Enable" check box
this.theEnableInformationEventsInDebugInformationCheckBox.Checked =
this.theEnableDebugInformationCheckBox.Checked;
this.theEnableInformationEventsInDebugInformationCheckBox.Enabled = false;
this.theRedirectDebugInformationToOutputCheckBox.Checked = false;
this.theRedirectDebugInformationToOutputCheckBox.Enabled = false;
this.theLatencyAnalysisGroupBox.Enabled = false;
this.thePerformLatencyAnalysisCheckBox.Checked = false;
this.thePerformLatencyAnalysisCheckBox.Enabled = false;
this.theOutputLatencyAnalysisHistogramCheckBox.Checked = false;
this.theOutputLatencyAnalysisHistogramCheckBox.Enabled = false;
this.theOutputAdditionalLatencyAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalLatencyAnalysisInformationCheckBox.Enabled = false;
this.theBurstAnalysisGroupBox.Enabled = false;
this.thePerformBurstAnalysisCheckBox.Checked = false;
this.thePerformBurstAnalysisCheckBox.Enabled = false;
this.theOutputBurstAnalysisHistogramCheckBox.Checked = false;
this.theOutputBurstAnalysisHistogramCheckBox.Enabled = false;
this.theOutputAdditionalBurstAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalBurstAnalysisInformationCheckBox.Enabled = false;
this.theTimeAnalysisGroupBox.Enabled = false;
this.thePerformTimeAnalysisCheckBox.Checked = false;
this.thePerformTimeAnalysisCheckBox.Enabled = false;
this.theOutputTimeAnalysisTimestampHistogramCheckBox.Checked = false;
this.theOutputTimeAnalysisTimestampHistogramCheckBox.Enabled = false;
this.theOutputTimeAnalysisTimeHistogramCheckBox.Checked = false;
this.theOutputTimeAnalysisTimeHistogramCheckBox.Enabled = false;
this.theOutputAdditionalTimeAnalysisInformationCheckBox.Checked = false;
this.theOutputAdditionalTimeAnalysisInformationCheckBox.Enabled = false;
// Do not change the "Minimize Memory Usage" check box on a change to the "Enable" check box in the "Debug Information" group box
if (sender != this.theEnableDebugInformationCheckBox)
{
this.theUseAlternativeSequenceNumberCheckBox.Checked = false;
this.theUseAlternativeSequenceNumberCheckBox.Enabled = false;
this.theMinimizeMemoryUsageCheckBox.Checked = false;
this.theMinimizeMemoryUsageCheckBox.Enabled = false;
}
}
}
}
| |
/*
* 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.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.IO;
using System.Text;
using Microsoft.CSharp;
//using Microsoft.JScript;
using Microsoft.VisualBasic;
using log4net;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
{
public class Compiler : ICompiler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// * Uses "LSL2Converter" to convert LSL to C# if necessary.
// * Compiles C#-code into an assembly
// * Returns assembly name ready for AppDomain load.
//
// Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
//
internal enum enumCompileType
{
lsl = 0,
cs = 1,
vb = 2
}
/// <summary>
/// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
/// </summary>
public int LinesToRemoveOnError = 3;
private enumCompileType DefaultCompileLanguage;
private bool WriteScriptSourceToDebugFile;
private bool CompileWithDebugInformation;
private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
private bool m_insertCoopTerminationCalls;
private string FilePrefix;
private string ScriptEnginesPath = null;
// mapping between LSL and C# line/column numbers
private ICodeConverter LSL_Converter;
private List<string> m_warnings = new List<string>();
// private object m_syncy = new object();
private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
// private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files
private static UInt64 scriptCompileCounter = 0; // And a counter
public IScriptEngine m_scriptEngine;
private Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>> m_lineMaps =
new Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>>();
public bool in_startup = true;
public Compiler(IScriptEngine scriptEngine)
{
m_scriptEngine = scriptEngine;
ScriptEnginesPath = scriptEngine.ScriptEnginePath;
ReadConfig();
}
public void ReadConfig()
{
// Get some config
WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", false);
CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true);
bool DeleteScriptsOnStartup = m_scriptEngine.Config.GetBoolean("DeleteScriptsOnStartup", true);
m_insertCoopTerminationCalls = m_scriptEngine.Config.GetString("ScriptStopStrategy", "abort") == "co-op";
// Get file prefix from scriptengine name and make it file system safe:
FilePrefix = "CommonCompiler";
foreach (char c in Path.GetInvalidFileNameChars())
{
FilePrefix = FilePrefix.Replace(c, '_');
}
if (in_startup)
{
in_startup = false;
CheckOrCreateScriptsDirectory();
// First time we start? Delete old files
if (DeleteScriptsOnStartup)
DeleteOldFiles();
}
// Map name and enum type of our supported languages
LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs);
LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb);
LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl);
// Allowed compilers
string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl");
AllowedCompilers.Clear();
#if DEBUG
m_log.Debug("[Compiler]: Allowed languages: " + allowComp);
#endif
foreach (string strl in allowComp.Split(','))
{
string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
if (!LanguageMapping.ContainsKey(strlan))
{
m_log.Error("[Compiler]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
}
else
{
#if DEBUG
//m_log.Debug("[Compiler]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
#endif
}
AllowedCompilers.Add(strlan, true);
}
if (AllowedCompilers.Count == 0)
m_log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
// Default language
string defaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower();
// Is this language recognized at all?
if (!LanguageMapping.ContainsKey(defaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
defaultCompileLanguage = "lsl";
}
// Is this language in allow-list?
if (!AllowedCompilers.ContainsKey(defaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
}
else
{
#if DEBUG
// m_log.Debug("[Compiler]: " +
// "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language.");
#endif
// LANGUAGE IS IN ALLOW-LIST
DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage];
}
// We now have an allow-list, a mapping list, and a default language
}
/// <summary>
/// Create the directory where compiled scripts are stored if it does not already exist.
/// </summary>
private void CheckOrCreateScriptsDirectory()
{
if (!Directory.Exists(ScriptEnginesPath))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString());
}
}
if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString())))
{
try
{
Directory.CreateDirectory(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()));
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()) + "\": " + ex.ToString());
}
}
}
/// <summary>
/// Delete old script files
/// </summary>
private void DeleteOldFiles()
{
foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_compiled*"))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
}
}
foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_source*"))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
}
}
}
////private ICodeCompiler icc = codeProvider.CreateCompiler();
//public string CompileFromFile(string LSOFileName)
//{
// switch (Path.GetExtension(LSOFileName).ToLower())
// {
// case ".txt":
// case ".lsl":
// Common.ScriptEngineBase.Shared.SendToDebug("Source code is LSL, converting to CS");
// return CompileFromLSLText(File.ReadAllText(LSOFileName));
// case ".cs":
// Common.ScriptEngineBase.Shared.SendToDebug("Source code is CS");
// return CompileFromCSText(File.ReadAllText(LSOFileName));
// default:
// throw new Exception("Unknown script type.");
// }
//}
public string GetCompilerOutput(string assetID)
{
return Path.Combine(ScriptEnginesPath, Path.Combine(
m_scriptEngine.World.RegionInfo.RegionID.ToString(),
FilePrefix + "_compiled_" + assetID + ".dll"));
}
public string GetCompilerOutput(UUID assetID)
{
return GetCompilerOutput(assetID.ToString());
}
public void PerformScriptCompile(
string source, string asset, UUID ownerUUID,
out string assembly, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
{
PerformScriptCompile(source, asset, ownerUUID, false, out assembly, out linemap);
}
public void PerformScriptCompile(
string source, string asset, UUID ownerUUID, bool alwaysRecompile,
out string assembly, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
{
// m_log.DebugFormat("[Compiler]: Checking script for asset {0} in {1}\n{2}", asset, m_scriptEngine.World.Name, source);
IScriptModuleComms comms = m_scriptEngine.World.RequestModuleInterface<IScriptModuleComms>();
linemap = null;
m_warnings.Clear();
assembly = GetCompilerOutput(asset);
// m_log.DebugFormat("[Compiler]: Retrieved assembly {0} for asset {1} in {2}", assembly, asset, m_scriptEngine.World.Name);
CheckOrCreateScriptsDirectory();
// Don't recompile if we're not forced to and we already have it
// Performing 3 file exists tests for every script can still be slow
if (!alwaysRecompile && File.Exists(assembly) && File.Exists(assembly + ".text") && File.Exists(assembly + ".map"))
{
// m_log.DebugFormat("[Compiler]: Found existing assembly {0} for asset {1} in {2}", assembly, asset, m_scriptEngine.World.Name);
// If we have already read this linemap file, then it will be in our dictionary.
// Don't build another copy of the dictionary (saves memory) and certainly
// don't keep reading the same file from disk multiple times.
if (!m_lineMaps.ContainsKey(assembly))
m_lineMaps[assembly] = ReadMapFile(assembly + ".map");
linemap = m_lineMaps[assembly];
return;
}
// m_log.DebugFormat("[Compiler]: Compiling assembly {0} for asset {1} in {2}", assembly, asset, m_scriptEngine.World.Name);
if (source == String.Empty)
throw new Exception("Cannot find script assembly and no script text present");
enumCompileType language = DefaultCompileLanguage;
if (source.StartsWith("//c#", true, CultureInfo.InvariantCulture))
language = enumCompileType.cs;
if (source.StartsWith("//vb", true, CultureInfo.InvariantCulture))
{
language = enumCompileType.vb;
// We need to remove //vb, it won't compile with that
source = source.Substring(4, source.Length - 4);
}
if (source.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
language = enumCompileType.lsl;
// m_log.DebugFormat("[Compiler]: Compile language is {0}", language);
if (!AllowedCompilers.ContainsKey(language.ToString()))
{
// Not allowed to compile to this language!
string errtext = String.Empty;
errtext += "The compiler for language \"" + language.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
throw new Exception(errtext);
}
if (m_scriptEngine.World.Permissions.CanCompileScript(ownerUUID, (int)language) == false)
{
// Not allowed to compile to this language!
string errtext = String.Empty;
errtext += ownerUUID + " is not in list of allowed users for this scripting language. Script will not be executed!";
throw new Exception(errtext);
}
string compileScript = source;
if (language == enumCompileType.lsl)
{
// Its LSL, convert it to C#
LSL_Converter = (ICodeConverter)new CSCodeGenerator(comms, m_insertCoopTerminationCalls);
compileScript = LSL_Converter.Convert(source);
// copy converter warnings into our warnings.
foreach (string warning in LSL_Converter.GetWarnings())
{
AddWarning(warning);
}
linemap = ((CSCodeGenerator)LSL_Converter).PositionMap;
// Write the linemap to a file and save it in our dictionary for next time.
m_lineMaps[assembly] = linemap;
WriteMapFile(assembly + ".map", linemap);
}
switch (language)
{
case enumCompileType.cs:
case enumCompileType.lsl:
compileScript = CreateCSCompilerScript(
compileScript,
m_scriptEngine.ScriptClassName,
m_scriptEngine.ScriptBaseClassName,
m_scriptEngine.ScriptBaseClassParameters);
break;
case enumCompileType.vb:
compileScript = CreateVBCompilerScript(
compileScript, m_scriptEngine.ScriptClassName, m_scriptEngine.ScriptBaseClassName);
break;
}
assembly = CompileFromDotNetText(compileScript, language, asset, assembly);
}
public string[] GetWarnings()
{
return m_warnings.ToArray();
}
private void AddWarning(string warning)
{
if (!m_warnings.Contains(warning))
{
m_warnings.Add(warning);
}
}
// private static string CreateJSCompilerScript(string compileScript)
// {
// compileScript = String.Empty +
// "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" +
// "package SecondLife {\r\n" +
// "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
// compileScript +
// "} }\r\n";
// return compileScript;
// }
public static string CreateCSCompilerScript(
string compileScript, string className, string baseClassName, ParameterInfo[] constructorParameters)
{
compileScript = string.Format(
@"using OpenSim.Region.ScriptEngine.Shared;
using System.Collections.Generic;
namespace SecondLife
{{
public class {0} : {1}
{{
public {0}({2}) : base({3}) {{}}
{4}
}}
}}",
className,
baseClassName,
constructorParameters != null
? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.ToString()))
: "",
constructorParameters != null
? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.Name))
: "",
compileScript);
return compileScript;
}
public static string CreateVBCompilerScript(string compileScript, string className, string baseClassName)
{
compileScript = String.Empty +
"Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " +
String.Empty + "NameSpace SecondLife:" +
String.Empty + "Public Class " + className + ": Inherits " + baseClassName +
"\r\nPublic Sub New()\r\nEnd Sub: " +
compileScript +
":End Class :End Namespace\r\n";
return compileScript;
}
/// <summary>
/// Compile .NET script to .Net assembly (.dll)
/// </summary>
/// <param name="Script">CS script</param>
/// <returns>Filename to .dll assembly</returns>
internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset, string assembly)
{
// m_log.DebugFormat("[Compiler]: Compiling to assembly\n{0}", Script);
string ext = "." + lang.ToString();
// Output assembly name
scriptCompileCounter++;
try
{
if (File.Exists(assembly))
{
File.SetAttributes(assembly, FileAttributes.Normal);
File.Delete(assembly);
}
}
catch (Exception e) // NOTLEGIT - Should be just FileIOException
{
throw new Exception("Unable to delete old existing " +
"script-file before writing new. Compile aborted: " +
e.ToString());
}
// DEBUG - write source to disk
if (WriteScriptSourceToDebugFile)
{
string srcFileName = FilePrefix + "_source_" +
Path.GetFileNameWithoutExtension(assembly) + ext;
try
{
File.WriteAllText(Path.Combine(Path.Combine(
ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()),
srcFileName), Script);
}
catch (Exception ex) //NOTLEGIT - Should be just FileIOException
{
m_log.Error("[Compiler]: Exception while " +
"trying to write script source to file \"" +
srcFileName + "\": " + ex.ToString());
}
}
// Do actual compile
CompilerParameters parameters = new CompilerParameters();
parameters.IncludeDebugInformation = true;
string rootPath = AppDomain.CurrentDomain.BaseDirectory;
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenMetaverseTypes.dll"));
if (m_scriptEngine.ScriptReferencedAssemblies != null)
Array.ForEach<string>(
m_scriptEngine.ScriptReferencedAssemblies,
a => parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, a)));
parameters.GenerateExecutable = false;
parameters.OutputAssembly = assembly;
parameters.IncludeDebugInformation = CompileWithDebugInformation;
//parameters.WarningLevel = 1; // Should be 4?
parameters.TreatWarningsAsErrors = false;
CompilerResults results;
switch (lang)
{
case enumCompileType.vb:
results = VBcodeProvider.CompileAssemblyFromSource(
parameters, Script);
break;
case enumCompileType.cs:
case enumCompileType.lsl:
bool complete = false;
bool retried = false;
do
{
lock (CScodeProvider)
{
results = CScodeProvider.CompileAssemblyFromSource(
parameters, Script);
}
// Deal with an occasional segv in the compiler.
// Rarely, if ever, occurs twice in succession.
// Line # == 0 and no file name are indications that
// this is a native stack trace rather than a normal
// error log.
if (results.Errors.Count > 0)
{
if (!retried && string.IsNullOrEmpty(results.Errors[0].FileName) &&
results.Errors[0].Line == 0)
{
// System.Console.WriteLine("retrying failed compilation");
retried = true;
}
else
{
complete = true;
}
}
else
{
complete = true;
}
} while (!complete);
break;
default:
throw new Exception("Compiler is not able to recongnize " +
"language type \"" + lang.ToString() + "\"");
}
// foreach (Type type in results.CompiledAssembly.GetTypes())
// {
// foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))
// {
// m_log.DebugFormat("[COMPILER]: {0}.{1}", type.FullName, method.Name);
// }
// }
//
// WARNINGS AND ERRORS
//
bool hadErrors = false;
string errtext = String.Empty;
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
string severity = CompErr.IsWarning ? "Warning" : "Error";
KeyValuePair<int, int> errorPos;
// Show 5 errors max, but check entire list for errors
if (severity == "Error")
{
// C# scripts will not have a linemap since theres no line translation involved.
if (!m_lineMaps.ContainsKey(assembly))
errorPos = new KeyValuePair<int, int>(CompErr.Line, CompErr.Column);
else
errorPos = FindErrorPosition(CompErr.Line, CompErr.Column, m_lineMaps[assembly]);
string text = CompErr.ErrorText;
// Use LSL type names
if (lang == enumCompileType.lsl)
text = ReplaceTypes(CompErr.ErrorText);
// The Second Life viewer's script editor begins
// countingn lines and columns at 0, so we subtract 1.
errtext += String.Format("({0},{1}): {4} {2}: {3}\n",
errorPos.Key - 1, errorPos.Value - 1,
CompErr.ErrorNumber, text, severity);
hadErrors = true;
}
}
}
if (hadErrors)
{
throw new Exception(errtext);
}
// On today's highly asynchronous systems, the result of
// the compile may not be immediately apparent. Wait a
// reasonable amount of time before giving up on it.
if (!File.Exists(assembly))
{
for (int i = 0; i < 20 && !File.Exists(assembly); i++)
{
System.Threading.Thread.Sleep(250);
}
// One final chance...
if (!File.Exists(assembly))
{
errtext = String.Empty;
errtext += "No compile error. But not able to locate compiled file.";
throw new Exception(errtext);
}
}
// m_log.DebugFormat("[Compiler] Compiled new assembly "+
// "for {0}", asset);
// Because windows likes to perform exclusive locks, we simply
// write out a textual representation of the file here
//
// Read the binary file into a buffer
//
FileInfo fi = new FileInfo(assembly);
if (fi == null)
{
errtext = String.Empty;
errtext += "No compile error. But not able to stat file.";
throw new Exception(errtext);
}
Byte[] data = new Byte[fi.Length];
try
{
using (FileStream fs = File.Open(assembly, FileMode.Open, FileAccess.Read))
fs.Read(data, 0, data.Length);
}
catch (Exception)
{
errtext = String.Empty;
errtext += "No compile error. But not able to open file.";
throw new Exception(errtext);
}
// Convert to base64
//
string filetext = System.Convert.ToBase64String(data);
Byte[] buf = Encoding.ASCII.GetBytes(filetext);
using (FileStream sfs = File.Create(assembly + ".text"))
sfs.Write(buf, 0, buf.Length);
return assembly;
}
private class kvpSorter : IComparer<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>>
{
public int Compare(KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> a,
KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> b)
{
int kc = a.Key.Key.CompareTo(b.Key.Key);
return (kc != 0) ? kc : a.Key.Value.CompareTo(b.Key.Value);
}
}
public static KeyValuePair<int, int> FindErrorPosition(int line,
int col, Dictionary<KeyValuePair<int, int>,
KeyValuePair<int, int>> positionMap)
{
if (positionMap == null || positionMap.Count == 0)
return new KeyValuePair<int, int>(line, col);
KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
out ret))
return ret;
var sorted = new List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>>(positionMap);
sorted.Sort(new kvpSorter());
int l = 1;
int c = 1;
int pl = 1;
foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> posmap in sorted)
{
//m_log.DebugFormat("[Compiler]: Scanning line map {0},{1} --> {2},{3}", posmap.Key.Key, posmap.Key.Value, posmap.Value.Key, posmap.Value.Value);
int nl = posmap.Value.Key + line - posmap.Key.Key; // New, translated LSL line and column.
int nc = posmap.Value.Value + col - posmap.Key.Value;
// Keep going until we find the first point passed line,col.
if (posmap.Key.Key > line)
{
//m_log.DebugFormat("[Compiler]: Line is larger than requested {0},{1}, returning {2},{3}", line, col, l, c);
if (pl < line)
{
//m_log.DebugFormat("[Compiler]: Previous line ({0}) is less than requested line ({1}), setting column to 1.", pl, line);
c = 1;
}
break;
}
if (posmap.Key.Key == line && posmap.Key.Value > col)
{
// Never move l,c backwards.
if (nl > l || (nl == l && nc > c))
{
//m_log.DebugFormat("[Compiler]: Using offset relative to this: {0} + {1} - {2}, {3} + {4} - {5} = {6}, {7}",
// posmap.Value.Key, line, posmap.Key.Key, posmap.Value.Value, col, posmap.Key.Value, nl, nc);
l = nl;
c = nc;
}
//m_log.DebugFormat("[Compiler]: Column is larger than requested {0},{1}, returning {2},{3}", line, col, l, c);
break;
}
pl = posmap.Key.Key;
l = posmap.Value.Key;
c = posmap.Value.Value;
}
return new KeyValuePair<int, int>(l, c);
}
string ReplaceTypes(string message)
{
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
"string");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
"integer");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
"float");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
"list");
return message;
}
private static void WriteMapFile(string filename, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
{
string mapstring = String.Empty;
foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in linemap)
{
KeyValuePair<int, int> k = kvp.Key;
KeyValuePair<int, int> v = kvp.Value;
mapstring += String.Format("{0},{1},{2},{3}\n", k.Key, k.Value, v.Key, v.Value);
}
Byte[] mapbytes = Encoding.ASCII.GetBytes(mapstring);
using (FileStream mfs = File.Create(filename))
mfs.Write(mapbytes, 0, mapbytes.Length);
}
private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ReadMapFile(string filename)
{
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
try
{
using (StreamReader r = File.OpenText(filename))
{
linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
string line;
while ((line = r.ReadLine()) != null)
{
String[] parts = line.Split(new Char[] { ',' });
int kk = System.Convert.ToInt32(parts[0]);
int kv = System.Convert.ToInt32(parts[1]);
int vk = System.Convert.ToInt32(parts[2]);
int vv = System.Convert.ToInt32(parts[3]);
KeyValuePair<int, int> k = new KeyValuePair<int, int>(kk, kv);
KeyValuePair<int, int> v = new KeyValuePair<int, int>(vk, vv);
linemap[k] = v;
}
}
}
catch
{
linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
}
return linemap;
}
}
}
| |
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Mozu.Api.Contracts.Fulfillment {
/// <summary>
///
/// </summary>
[DataContract]
public class CanceledItem {
/// <summary>
/// Gets or Sets ActualPrice
/// </summary>
[DataMember(Name="actualPrice", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "actualPrice")]
public Nullable<decimal> ActualPrice { get; set; }
/// <summary>
/// Gets or Sets AllowsBackOrder
/// </summary>
[DataMember(Name="allowsBackOrder", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "allowsBackOrder")]
public bool? AllowsBackOrder { get; set; }
/// <summary>
/// Gets or Sets Attributes
/// </summary>
[DataMember(Name="attributes", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "attributes")]
public Dictionary<string, Object> Attributes { get; set; }
/// <summary>
/// Gets or Sets AuditInfo
/// </summary>
[DataMember(Name="auditInfo", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "auditInfo")]
public AuditInfo AuditInfo { get; set; }
/// <summary>
/// Gets or Sets BackorderReleaseDate
/// </summary>
[DataMember(Name="backorderReleaseDate", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "backorderReleaseDate")]
public DateTime? BackorderReleaseDate { get; set; }
/// <summary>
/// Gets or Sets BlockAssignment
/// </summary>
[DataMember(Name="blockAssignment", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "blockAssignment")]
public bool? BlockAssignment { get; set; }
/// <summary>
/// Gets or Sets CanceledReason
/// </summary>
[DataMember(Name="canceledReason", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "canceledReason")]
public CanceledReason CanceledReason { get; set; }
/// <summary>
/// Gets or Sets Data
/// </summary>
[DataMember(Name="data", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "data")]
public Dictionary<string, Object> Data { get; set; }
/// <summary>
/// Gets or Sets Duty
/// </summary>
[DataMember(Name="duty", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "duty")]
public Nullable<decimal> Duty { get; set; }
/// <summary>
/// Gets or Sets ExpectedDeliveryDate
/// </summary>
[DataMember(Name="expectedDeliveryDate", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "expectedDeliveryDate")]
public DateTime? ExpectedDeliveryDate { get; set; }
/// <summary>
/// Gets or Sets FulfillmentItemType
/// </summary>
[DataMember(Name="fulfillmentItemType", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "fulfillmentItemType")]
public string FulfillmentItemType { get; set; }
/// <summary>
/// Gets or Sets Handling
/// </summary>
[DataMember(Name="handling", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "handling")]
public Nullable<decimal> Handling { get; set; }
/// <summary>
/// Gets or Sets HandlingDiscount
/// </summary>
[DataMember(Name="handlingDiscount", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "handlingDiscount")]
public Nullable<decimal> HandlingDiscount { get; set; }
/// <summary>
/// Gets or Sets HandlingTax
/// </summary>
[DataMember(Name="handlingTax", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "handlingTax")]
public Nullable<decimal> HandlingTax { get; set; }
/// <summary>
/// Gets or Sets ImageUrl
/// </summary>
[DataMember(Name="imageUrl", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "imageUrl")]
public string ImageUrl { get; set; }
/// <summary>
/// Gets or Sets IsTaxable
/// </summary>
[DataMember(Name="isTaxable", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "isTaxable")]
public bool? IsTaxable { get; set; }
/// <summary>
/// Gets or Sets ItemDiscount
/// </summary>
[DataMember(Name="itemDiscount", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "itemDiscount")]
public Nullable<decimal> ItemDiscount { get; set; }
/// <summary>
/// Gets or Sets ItemTax
/// </summary>
[DataMember(Name="itemTax", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "itemTax")]
public Nullable<decimal> ItemTax { get; set; }
/// <summary>
/// Gets or Sets LineId
/// </summary>
[DataMember(Name="lineId", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "lineId")]
public int? LineId { get; set; }
/// <summary>
/// Gets or Sets LineItemCost
/// </summary>
[DataMember(Name="lineItemCost", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "lineItemCost")]
public Nullable<decimal> LineItemCost { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or Sets OptionAttributeFQN
/// </summary>
[DataMember(Name="optionAttributeFQN", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "optionAttributeFQN")]
public string OptionAttributeFQN { get; set; }
/// <summary>
/// Gets or Sets Options
/// </summary>
[DataMember(Name="options", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "options")]
public List<ProductOption> Options { get; set; }
/// <summary>
/// Gets or Sets OriginalOrderItemId
/// </summary>
[DataMember(Name="originalOrderItemId", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "originalOrderItemId")]
public string OriginalOrderItemId { get; set; }
/// <summary>
/// Gets or Sets OverridePrice
/// </summary>
[DataMember(Name="overridePrice", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "overridePrice")]
public Nullable<decimal> OverridePrice { get; set; }
/// <summary>
/// Gets or Sets ParentId
/// </summary>
[DataMember(Name="parentId", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "parentId")]
public string ParentId { get; set; }
/// <summary>
/// Gets or Sets PartNumber
/// </summary>
[DataMember(Name="partNumber", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "partNumber")]
public string PartNumber { get; set; }
/// <summary>
/// Gets or Sets ProductCode
/// </summary>
[DataMember(Name="productCode", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "productCode")]
public string ProductCode { get; set; }
/// <summary>
/// Gets or Sets Quantity
/// </summary>
[DataMember(Name="quantity", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "quantity")]
public int? Quantity { get; set; }
/// <summary>
/// Gets or Sets ReadyForPickupQuantity
/// </summary>
[DataMember(Name="readyForPickupQuantity", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "readyForPickupQuantity")]
public int? ReadyForPickupQuantity { get; set; }
/// <summary>
/// Gets or Sets Shipping
/// </summary>
[DataMember(Name="shipping", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "shipping")]
public Nullable<decimal> Shipping { get; set; }
/// <summary>
/// Gets or Sets ShippingDiscount
/// </summary>
[DataMember(Name="shippingDiscount", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "shippingDiscount")]
public Nullable<decimal> ShippingDiscount { get; set; }
/// <summary>
/// Gets or Sets ShippingTax
/// </summary>
[DataMember(Name="shippingTax", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "shippingTax")]
public Nullable<decimal> ShippingTax { get; set; }
/// <summary>
/// Gets or Sets Sku
/// </summary>
[DataMember(Name="sku", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "sku")]
public string Sku { get; set; }
/// <summary>
/// Gets or Sets TaxData
/// </summary>
[DataMember(Name="taxData", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "taxData")]
public Object TaxData { get; set; }
/// <summary>
/// Gets or Sets TaxableHandling
/// </summary>
[DataMember(Name="taxableHandling", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "taxableHandling")]
public Nullable<decimal> TaxableHandling { get; set; }
/// <summary>
/// Gets or Sets TaxableLineItemCost
/// </summary>
[DataMember(Name="taxableLineItemCost", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "taxableLineItemCost")]
public Nullable<decimal> TaxableLineItemCost { get; set; }
/// <summary>
/// Gets or Sets TaxableShipping
/// </summary>
[DataMember(Name="taxableShipping", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "taxableShipping")]
public Nullable<decimal> TaxableShipping { get; set; }
/// <summary>
/// Gets or Sets TransferQuantity
/// </summary>
[DataMember(Name="transferQuantity", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "transferQuantity")]
public int? TransferQuantity { get; set; }
/// <summary>
/// Gets or Sets UnitPrice
/// </summary>
[DataMember(Name="unitPrice", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "unitPrice")]
public Nullable<decimal> UnitPrice { get; set; }
/// <summary>
/// Gets or Sets Upc
/// </summary>
[DataMember(Name="upc", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "upc")]
public string Upc { get; set; }
/// <summary>
/// Gets or Sets VariationProductCode
/// </summary>
[DataMember(Name="variationProductCode", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "variationProductCode")]
public string VariationProductCode { get; set; }
/// <summary>
/// Gets or Sets Weight
/// </summary>
[DataMember(Name="weight", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "weight")]
public Nullable<decimal> Weight { get; set; }
/// <summary>
/// Gets or Sets WeightUnit
/// </summary>
[DataMember(Name="weightUnit", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "weightUnit")]
public string WeightUnit { get; set; }
/// <summary>
/// Gets or Sets WeightedDutyAdjustment
/// </summary>
[DataMember(Name="weightedDutyAdjustment", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "weightedDutyAdjustment")]
public Nullable<decimal> WeightedDutyAdjustment { get; set; }
/// <summary>
/// Gets or Sets WeightedHandlingAdjustment
/// </summary>
[DataMember(Name="weightedHandlingAdjustment", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "weightedHandlingAdjustment")]
public Nullable<decimal> WeightedHandlingAdjustment { get; set; }
/// <summary>
/// Gets or Sets WeightedHandlingTaxAdjustment
/// </summary>
[DataMember(Name="weightedHandlingTaxAdjustment", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "weightedHandlingTaxAdjustment")]
public Nullable<decimal> WeightedHandlingTaxAdjustment { get; set; }
/// <summary>
/// Gets or Sets WeightedLineItemTaxAdjustment
/// </summary>
[DataMember(Name="weightedLineItemTaxAdjustment", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "weightedLineItemTaxAdjustment")]
public Nullable<decimal> WeightedLineItemTaxAdjustment { get; set; }
/// <summary>
/// Gets or Sets WeightedShipmentAdjustment
/// </summary>
[DataMember(Name="weightedShipmentAdjustment", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "weightedShipmentAdjustment")]
public Nullable<decimal> WeightedShipmentAdjustment { get; set; }
/// <summary>
/// Gets or Sets WeightedShippingAdjustment
/// </summary>
[DataMember(Name="weightedShippingAdjustment", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "weightedShippingAdjustment")]
public Nullable<decimal> WeightedShippingAdjustment { get; set; }
/// <summary>
/// Gets or Sets WeightedShippingTaxAdjustment
/// </summary>
[DataMember(Name="weightedShippingTaxAdjustment", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "weightedShippingTaxAdjustment")]
public Nullable<decimal> WeightedShippingTaxAdjustment { get; set; }
/// <summary>
/// Get 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 CanceledItem {\n");
sb.Append(" ActualPrice: ").Append(ActualPrice).Append("\n");
sb.Append(" AllowsBackOrder: ").Append(AllowsBackOrder).Append("\n");
sb.Append(" Attributes: ").Append(Attributes).Append("\n");
sb.Append(" AuditInfo: ").Append(AuditInfo).Append("\n");
sb.Append(" BackorderReleaseDate: ").Append(BackorderReleaseDate).Append("\n");
sb.Append(" BlockAssignment: ").Append(BlockAssignment).Append("\n");
sb.Append(" CanceledReason: ").Append(CanceledReason).Append("\n");
sb.Append(" Data: ").Append(Data).Append("\n");
sb.Append(" Duty: ").Append(Duty).Append("\n");
sb.Append(" ExpectedDeliveryDate: ").Append(ExpectedDeliveryDate).Append("\n");
sb.Append(" FulfillmentItemType: ").Append(FulfillmentItemType).Append("\n");
sb.Append(" Handling: ").Append(Handling).Append("\n");
sb.Append(" HandlingDiscount: ").Append(HandlingDiscount).Append("\n");
sb.Append(" HandlingTax: ").Append(HandlingTax).Append("\n");
sb.Append(" ImageUrl: ").Append(ImageUrl).Append("\n");
sb.Append(" IsTaxable: ").Append(IsTaxable).Append("\n");
sb.Append(" ItemDiscount: ").Append(ItemDiscount).Append("\n");
sb.Append(" ItemTax: ").Append(ItemTax).Append("\n");
sb.Append(" LineId: ").Append(LineId).Append("\n");
sb.Append(" LineItemCost: ").Append(LineItemCost).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" OptionAttributeFQN: ").Append(OptionAttributeFQN).Append("\n");
sb.Append(" Options: ").Append(Options).Append("\n");
sb.Append(" OriginalOrderItemId: ").Append(OriginalOrderItemId).Append("\n");
sb.Append(" OverridePrice: ").Append(OverridePrice).Append("\n");
sb.Append(" ParentId: ").Append(ParentId).Append("\n");
sb.Append(" PartNumber: ").Append(PartNumber).Append("\n");
sb.Append(" ProductCode: ").Append(ProductCode).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" ReadyForPickupQuantity: ").Append(ReadyForPickupQuantity).Append("\n");
sb.Append(" Shipping: ").Append(Shipping).Append("\n");
sb.Append(" ShippingDiscount: ").Append(ShippingDiscount).Append("\n");
sb.Append(" ShippingTax: ").Append(ShippingTax).Append("\n");
sb.Append(" Sku: ").Append(Sku).Append("\n");
sb.Append(" TaxData: ").Append(TaxData).Append("\n");
sb.Append(" TaxableHandling: ").Append(TaxableHandling).Append("\n");
sb.Append(" TaxableLineItemCost: ").Append(TaxableLineItemCost).Append("\n");
sb.Append(" TaxableShipping: ").Append(TaxableShipping).Append("\n");
sb.Append(" TransferQuantity: ").Append(TransferQuantity).Append("\n");
sb.Append(" UnitPrice: ").Append(UnitPrice).Append("\n");
sb.Append(" Upc: ").Append(Upc).Append("\n");
sb.Append(" VariationProductCode: ").Append(VariationProductCode).Append("\n");
sb.Append(" Weight: ").Append(Weight).Append("\n");
sb.Append(" WeightUnit: ").Append(WeightUnit).Append("\n");
sb.Append(" WeightedDutyAdjustment: ").Append(WeightedDutyAdjustment).Append("\n");
sb.Append(" WeightedHandlingAdjustment: ").Append(WeightedHandlingAdjustment).Append("\n");
sb.Append(" WeightedHandlingTaxAdjustment: ").Append(WeightedHandlingTaxAdjustment).Append("\n");
sb.Append(" WeightedLineItemTaxAdjustment: ").Append(WeightedLineItemTaxAdjustment).Append("\n");
sb.Append(" WeightedShipmentAdjustment: ").Append(WeightedShipmentAdjustment).Append("\n");
sb.Append(" WeightedShippingAdjustment: ").Append(WeightedShippingAdjustment).Append("\n");
sb.Append(" WeightedShippingTaxAdjustment: ").Append(WeightedShippingTaxAdjustment).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get 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);
}
}
}
| |
// 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.Threading;
using System.IO;
using System.Collections;
namespace System.Diagnostics
{
internal static class TraceInternal
{
private static volatile string s_appName = null;
private static volatile TraceListenerCollection s_listeners;
private static volatile bool s_autoFlush;
private static volatile bool s_useGlobalLock;
[ThreadStatic]
private static int t_indentLevel;
private static volatile int s_indentSize;
private static volatile bool s_settingsInitialized;
// this is internal so TraceSource can use it. We want to lock on the same object because both TraceInternal and
// TraceSource could be writing to the same listeners at the same time.
internal static readonly object critSec = new object();
public static TraceListenerCollection Listeners
{
get
{
InitializeSettings();
if (s_listeners == null)
{
lock (critSec)
{
if (s_listeners == null)
{
// In the absence of config support, the listeners by default add
// DefaultTraceListener to the listener collection.
s_listeners = new TraceListenerCollection();
TraceListener defaultListener = new DefaultTraceListener();
defaultListener.IndentLevel = t_indentLevel;
defaultListener.IndentSize = s_indentSize;
s_listeners.Add(defaultListener);
}
}
}
return s_listeners;
}
}
internal static string AppName
{
get
{
if (s_appName == null)
{
// This needs to be updated once we have the correct property implemented in the Environment class.
// Bug:895000 is tracking this.
s_appName = "DEFAULT_APPNAME";
}
return s_appName;
}
}
public static bool AutoFlush
{
get
{
InitializeSettings();
return s_autoFlush;
}
set
{
InitializeSettings();
s_autoFlush = value;
}
}
public static bool UseGlobalLock
{
get
{
InitializeSettings();
return s_useGlobalLock;
}
set
{
InitializeSettings();
s_useGlobalLock = value;
}
}
public static int IndentLevel
{
get { return t_indentLevel; }
set
{
// Use global lock
lock (critSec)
{
// We don't want to throw here -- it is very bad form to have debug or trace
// code throw exceptions!
if (value < 0)
{
value = 0;
}
t_indentLevel = value;
if (s_listeners != null)
{
foreach (TraceListener listener in Listeners)
{
listener.IndentLevel = t_indentLevel;
}
}
}
}
}
public static int IndentSize
{
get
{
InitializeSettings();
return s_indentSize;
}
set
{
InitializeSettings();
SetIndentSize(value);
}
}
private static void SetIndentSize(int value)
{
// Use global lock
lock (critSec)
{
// We don't want to throw here -- it is very bad form to have debug or trace
// code throw exceptions!
if (value < 0)
{
value = 0;
}
s_indentSize = value;
if (s_listeners != null)
{
foreach (TraceListener listener in Listeners)
{
listener.IndentSize = s_indentSize;
}
}
}
}
public static void Indent()
{
// Use global lock
lock (critSec)
{
InitializeSettings();
if (t_indentLevel < Int32.MaxValue)
{
t_indentLevel++;
}
foreach (TraceListener listener in Listeners)
{
listener.IndentLevel = t_indentLevel;
}
}
}
public static void Unindent()
{
// Use global lock
lock (critSec)
{
InitializeSettings();
if (t_indentLevel > 0)
{
t_indentLevel--;
}
foreach (TraceListener listener in Listeners)
{
listener.IndentLevel = t_indentLevel;
}
}
}
public static void Flush()
{
if (s_listeners != null)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.Flush();
}
}
else
{
listener.Flush();
}
}
}
}
}
public static void Close()
{
if (s_listeners != null)
{
// Use global lock
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.Dispose();
}
}
}
}
public static void Assert(bool condition)
{
if (condition) return;
Fail(string.Empty);
}
public static void Assert(bool condition, string message)
{
if (condition) return;
Fail(message);
}
public static void Assert(bool condition, string message, string detailMessage)
{
if (condition) return;
Fail(message, detailMessage);
}
public static void Fail(string message)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.Fail(message);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.Fail(message);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.Fail(message);
if (AutoFlush) listener.Flush();
}
}
}
}
public static void Fail(string message, string detailMessage)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.Fail(message, detailMessage);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.Fail(message, detailMessage);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.Fail(message, detailMessage);
if (AutoFlush) listener.Flush();
}
}
}
}
private static void InitializeSettings()
{
if (!s_settingsInitialized)
{
// we should avoid 2 threads altering the state concurrently for predictable behavior
// though it may not be strictly necessary at present
lock (critSec)
{
if (!s_settingsInitialized)
{
SetIndentSize(DiagnosticsConfiguration.IndentSize);
s_autoFlush = DiagnosticsConfiguration.AutoFlush;
s_useGlobalLock = DiagnosticsConfiguration.UseGlobalLock;
s_settingsInitialized = true;
}
}
}
}
// This method refreshes all the data from the configuration file, so that updated to the configuration file are mirrored
// in the System.Diagnostics.Trace class
static internal void Refresh()
{
lock (critSec)
{
s_settingsInitialized = false;
s_listeners = null;
}
InitializeSettings();
}
public static void TraceEvent(TraceEventType eventType, int id, string format, params object[] args)
{
TraceEventCache EventCache = new TraceEventCache();
if (UseGlobalLock)
{
lock (critSec)
{
if (args == null)
{
foreach (TraceListener listener in Listeners)
{
listener.TraceEvent(EventCache, AppName, eventType, id, format);
if (AutoFlush) listener.Flush();
}
}
else
{
foreach (TraceListener listener in Listeners)
{
listener.TraceEvent(EventCache, AppName, eventType, id, format, args);
if (AutoFlush) listener.Flush();
}
}
}
}
else
{
if (args == null)
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.TraceEvent(EventCache, AppName, eventType, id, format);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.TraceEvent(EventCache, AppName, eventType, id, format);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.TraceEvent(EventCache, AppName, eventType, id, format, args);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.TraceEvent(EventCache, AppName, eventType, id, format, args);
if (AutoFlush) listener.Flush();
}
}
}
}
}
public static void Write(string message)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.Write(message);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.Write(message);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.Write(message);
if (AutoFlush) listener.Flush();
}
}
}
}
public static void Write(object value)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.Write(value);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.Write(value);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.Write(value);
if (AutoFlush) listener.Flush();
}
}
}
}
public static void Write(string message, string category)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.Write(message, category);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.Write(message, category);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.Write(message, category);
if (AutoFlush) listener.Flush();
}
}
}
}
public static void Write(object value, string category)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.Write(value, category);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.Write(value, category);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.Write(value, category);
if (AutoFlush) listener.Flush();
}
}
}
}
public static void WriteLine(string message)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.WriteLine(message);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.WriteLine(message);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.WriteLine(message);
if (AutoFlush) listener.Flush();
}
}
}
}
public static void WriteLine(object value)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.WriteLine(value);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.WriteLine(value);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.WriteLine(value);
if (AutoFlush) listener.Flush();
}
}
}
}
public static void WriteLine(string message, string category)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.WriteLine(message, category);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.WriteLine(message, category);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.WriteLine(message, category);
if (AutoFlush) listener.Flush();
}
}
}
}
public static void WriteLine(object value, string category)
{
if (UseGlobalLock)
{
lock (critSec)
{
foreach (TraceListener listener in Listeners)
{
listener.WriteLine(value, category);
if (AutoFlush) listener.Flush();
}
}
}
else
{
foreach (TraceListener listener in Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.WriteLine(value, category);
if (AutoFlush) listener.Flush();
}
}
else
{
listener.WriteLine(value, category);
if (AutoFlush) listener.Flush();
}
}
}
}
public static void WriteIf(bool condition, string message)
{
if (condition)
Write(message);
}
public static void WriteIf(bool condition, object value)
{
if (condition)
Write(value);
}
public static void WriteIf(bool condition, string message, string category)
{
if (condition)
Write(message, category);
}
public static void WriteIf(bool condition, object value, string category)
{
if (condition)
Write(value, category);
}
public static void WriteLineIf(bool condition, string message)
{
if (condition)
WriteLine(message);
}
public static void WriteLineIf(bool condition, object value)
{
if (condition)
WriteLine(value);
}
public static void WriteLineIf(bool condition, string message, string category)
{
if (condition)
WriteLine(message, category);
}
public static void WriteLineIf(bool condition, object value, string category)
{
if (condition)
WriteLine(value, category);
}
}
}
| |
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
using System;
namespace ForieroEditor.Platforms.iOS.Xcode.PBX
{
enum TokenType
{
EOF,
Invalid,
String,
QuotedString,
Comment,
Semicolon, // ;
Comma, // ,
Eq, // =
LParen, // (
RParen, // )
LBrace, // {
RBrace, // }
}
class Token
{
public TokenType type;
// the line of the input stream the token starts in (0-based)
public int line;
// start and past-the-end positions of the token in the input stream
public int begin, end;
}
class TokenList : List<Token>
{
}
class Lexer
{
string text;
int pos;
int length;
int line;
public static TokenList Tokenize(string text)
{
var lexer = new Lexer();
lexer.SetText(text);
return lexer.ScanAll();
}
public void SetText(string text)
{
this.text = text + " "; // to prevent out-of-bounds access during look ahead
pos = 0;
length = text.Length;
line = 0;
}
public TokenList ScanAll()
{
var tokens = new TokenList();
while (true)
{
var tok = new Token();
ScanOne(tok);
tokens.Add(tok);
if (tok.type == TokenType.EOF)
break;
}
return tokens;
}
void UpdateNewlineStats(char ch)
{
if (ch == '\n')
line++;
}
// tokens list is modified in the case when we add BrokenLine token and need to remove already
// added tokens for the current line
void ScanOne(Token tok)
{
while (true)
{
while (pos < length && Char.IsWhiteSpace(text[pos]))
{
UpdateNewlineStats(text[pos]);
pos++;
}
if (pos >= length)
{
tok.type = TokenType.EOF;
break;
}
char ch = text[pos];
char ch2 = text[pos+1];
if (ch == '\"')
ScanQuotedString(tok);
else if (ch == '/' && ch2 == '*')
ScanMultilineComment(tok);
else if (ch == '/' && ch2 == '/')
ScanComment(tok);
else if (IsOperator(ch))
ScanOperator(tok);
else
ScanString(tok); // be more robust and accept whatever is left
return;
}
}
void ScanString(Token tok)
{
tok.type = TokenType.String;
tok.begin = pos;
while (pos < length)
{
char ch = text[pos];
char ch2 = text[pos+1];
if (Char.IsWhiteSpace(ch))
break;
else if (ch == '\"')
break;
else if (ch == '/' && ch2 == '*')
break;
else if (ch == '/' && ch2 == '/')
break;
else if (IsOperator(ch))
break;
pos++;
}
tok.end = pos;
tok.line = line;
}
void ScanQuotedString(Token tok)
{
tok.type = TokenType.QuotedString;
tok.begin = pos;
pos++;
while (pos < length)
{
// ignore escaped quotes
if (text[pos] == '\\' && text[pos+1] == '\"')
{
pos += 2;
continue;
}
// note that we close unclosed quotes
if (text[pos] == '\"')
break;
UpdateNewlineStats(text[pos]);
pos++;
}
pos++;
tok.end = pos;
tok.line = line;
}
void ScanMultilineComment(Token tok)
{
tok.type = TokenType.Comment;
tok.begin = pos;
pos += 2;
while (pos < length)
{
if (text[pos] == '*' && text[pos+1] == '/')
break;
// we support multiline comments
UpdateNewlineStats(text[pos]);
pos++;
}
pos += 2;
tok.end = pos;
tok.line = line;
}
void ScanComment(Token tok)
{
tok.type = TokenType.Comment;
tok.begin = pos;
pos += 2;
while (pos < length)
{
if (text[pos] == '\n')
break;
pos++;
}
UpdateNewlineStats(text[pos]);
pos++;
tok.end = pos;
tok.line = line;
}
bool IsOperator(char ch)
{
if (ch == ';' || ch == ',' || ch == '=' || ch == '(' || ch == ')' || ch == '{' || ch == '}')
return true;
return false;
}
void ScanOperator(Token tok)
{
switch (text[pos])
{
case ';': ScanOperatorSpecific(tok, TokenType.Semicolon); return;
case ',': ScanOperatorSpecific(tok, TokenType.Comma); return;
case '=': ScanOperatorSpecific(tok, TokenType.Eq); return;
case '(': ScanOperatorSpecific(tok, TokenType.LParen); return;
case ')': ScanOperatorSpecific(tok, TokenType.RParen); return;
case '{': ScanOperatorSpecific(tok, TokenType.LBrace); return;
case '}': ScanOperatorSpecific(tok, TokenType.RBrace); return;
default: return;
}
}
void ScanOperatorSpecific(Token tok, TokenType type)
{
tok.type = type;
tok.begin = pos;
pos++;
tok.end = pos;
tok.line = line;
}
}
} // namespace ForieroEditor.Platforms.iOS.Xcode
| |
#if(NET6_0_OR_GREATER)
using System;
using System.IO;
using System.Reflection;
#endif
using System.Collections.Generic;
using System.Linq;
using Jint.Native;
using Jint.Runtime;
using Xunit;
namespace Jint.Tests.Runtime;
public class ModuleTests
{
private readonly Engine _engine;
public ModuleTests()
{
_engine = new Engine();
}
[Fact]
public void ShouldExportNamed()
{
_engine.AddModule("my-module", @"export const value = 'exported value';");
var ns = _engine.ImportModule("my-module");
Assert.Equal("exported value", ns.Get("value").AsString());
}
[Fact]
public void ShouldExportNamedListRenamed()
{
_engine.AddModule("my-module", @"const value1 = 1; const value2 = 2; export { value1 as renamed1, value2 as renamed2 }");
var ns = _engine.ImportModule("my-module");
Assert.Equal(1, ns.Get("renamed1").AsInteger());
Assert.Equal(2, ns.Get("renamed2").AsInteger());
}
[Fact]
public void ShouldExportDefault()
{
_engine.AddModule("my-module", @"export default 'exported value';");
var ns = _engine.ImportModule("my-module");
Assert.Equal("exported value", ns.Get("default").AsString());
}
[Fact]
public void ShouldExportAll()
{
_engine.AddModule("module1", @"export const value = 'exported value';");
_engine.AddModule("module2", @"export * from 'module1';");
var ns = _engine.ImportModule("module2");
Assert.Equal("exported value", ns.Get("value").AsString());
}
[Fact]
public void ShouldImportNamed()
{
_engine.AddModule("imported-module", @"export const value = 'exported value';");
_engine.AddModule("my-module", @"import { value } from 'imported-module'; export const exported = value;");
var ns = _engine.ImportModule("my-module");
Assert.Equal("exported value", ns.Get("exported").AsString());
}
[Fact]
public void ShouldImportRenamed()
{
_engine.AddModule("imported-module", @"export const value = 'exported value';");
_engine.AddModule("my-module", @"import { value as renamed } from 'imported-module'; export const exported = renamed;");
var ns = _engine.ImportModule("my-module");
Assert.Equal("exported value", ns.Get("exported").AsString());
}
[Fact]
public void ShouldImportDefault()
{
_engine.AddModule("imported-module", @"export default 'exported value';");
_engine.AddModule("my-module", @"import imported from 'imported-module'; export const exported = imported;");
var ns = _engine.ImportModule("my-module");
Assert.Equal("exported value", ns.Get("exported").AsString());
}
[Fact]
public void ShouldImportAll()
{
_engine.AddModule("imported-module", @"export const value = 'exported value';");
_engine.AddModule("my-module", @"import * as imported from 'imported-module'; export const exported = imported.value;");
var ns = _engine.ImportModule("my-module");
Assert.Equal("exported value", ns.Get("exported").AsString());
}
[Fact]
public void ShouldImportDynamically()
{
var received = false;
_engine.AddModule("imported-module", builder => builder.ExportFunction("signal", () => received = true));
_engine.AddModule("my-module", @"import('imported-module').then(ns => { ns.signal(); });");
_engine.ImportModule("my-module");
_engine.RunAvailableContinuations();
Assert.True(received);
}
[Fact]
public void ShouldPropagateParseError()
{
_engine.AddModule("imported", @"export const invalid;");
_engine.AddModule("my-module", @"import { invalid } from 'imported';");
var exc = Assert.Throws<JavaScriptException>(() => _engine.ImportModule("my-module"));
Assert.Equal("Error while loading module: error in module 'imported': Line 1: Missing initializer in const declaration", exc.Message);
}
[Fact]
public void ShouldPropagateLinkError()
{
_engine.AddModule("imported", @"export invalid;");
_engine.AddModule("my-module", @"import { value } from 'imported';");
var exc = Assert.Throws<JavaScriptException>(() => _engine.ImportModule("my-module"));
Assert.Equal("Error while loading module: error in module 'imported': Line 1: Unexpected identifier", exc.Message);
Assert.Equal("my-module", exc.Location.Source);
}
[Fact]
public void ShouldPropagateExecuteError()
{
_engine.AddModule("my-module", @"throw new Error('imported successfully');");
var exc = Assert.Throws<JavaScriptException>(() => _engine.ImportModule("my-module"));
Assert.Equal("imported successfully", exc.Message);
Assert.Equal("my-module", exc.Location.Source);
}
[Fact]
public void ShouldPropagateThrowStatementThroughJavaScriptImport()
{
_engine.AddModule("imported-module", @"throw new Error('imported successfully');");
_engine.AddModule("my-module", @"import 'imported-module';");
var exc = Assert.Throws<JavaScriptException>(() => _engine.ImportModule("my-module"));
Assert.Equal("imported successfully", exc.Message);
}
[Fact]
public void ShouldAddModuleFromJsValue()
{
_engine.AddModule("my-module", builder => builder.ExportValue("value", JsString.Create("hello world")));
var ns = _engine.ImportModule("my-module");
Assert.Equal("hello world", ns.Get("value").AsString());
}
[Fact]
public void ShouldAddModuleFromClrInstance()
{
_engine.AddModule("imported-module", builder => builder.ExportObject("value", new ImportedClass { Value = "instance value" }));
_engine.AddModule("my-module", @"import { value } from 'imported-module'; export const exported = value.value;");
var ns = _engine.ImportModule("my-module");
Assert.Equal("instance value", ns.Get("exported").AsString());
}
[Fact]
public void ShouldAllowInvokeUserDefinedClass()
{
_engine.AddModule("user", "export class UserDefined { constructor(v) { this._v = v; } hello(c) { return `hello ${this._v}${c}`; } }");
var ctor = _engine.ImportModule("user").Get("UserDefined");
var instance = _engine.Construct(ctor, JsString.Create("world"));
var result = instance.GetMethod("hello").Call(instance, JsString.Create("!"));
Assert.Equal("hello world!", result);
}
[Fact]
public void ShouldAddModuleFromClrType()
{
_engine.AddModule("imported-module", builder => builder.ExportType<ImportedClass>());
_engine.AddModule("my-module", @"import { ImportedClass } from 'imported-module'; export const exported = new ImportedClass().value;");
var ns = _engine.ImportModule("my-module");
Assert.Equal("hello world", ns.Get("exported").AsString());
}
[Fact]
public void ShouldAddModuleFromClrFunction()
{
var received = new List<string>();
_engine.AddModule("imported-module", builder => builder
.ExportFunction("act_noargs", () => received.Add("act_noargs"))
.ExportFunction("act_args", args => received.Add($"act_args:{args[0].AsString()}"))
.ExportFunction("fn_noargs", () =>
{
received.Add("fn_noargs");
return "ret";
})
.ExportFunction("fn_args", args =>
{
received.Add($"fn_args:{args[0].AsString()}");
return "ret";
})
);
_engine.AddModule("my-module", @"
import * as fns from 'imported-module';
export const result = [fns.act_noargs(), fns.act_args('ok'), fns.fn_noargs(), fns.fn_args('ok')];");
var ns = _engine.ImportModule("my-module");
Assert.Equal(new[] { "act_noargs", "act_args:ok", "fn_noargs", "fn_args:ok" }, received.ToArray());
Assert.Equal(new[] { "undefined", "undefined", "ret", "ret" }, ns.Get("result").AsArray().Select(x => x.ToString()).ToArray());
}
private class ImportedClass
{
public string Value { get; set; } = "hello world";
}
[Fact]
public void ShouldAllowExportMultipleImports()
{
_engine.AddModule("@mine/import1", builder => builder.ExportValue("value1", JsNumber.Create(1)));
_engine.AddModule("@mine/import2", builder => builder.ExportValue("value2", JsNumber.Create(2)));
_engine.AddModule("@mine", "export * from '@mine/import1'; export * from '@mine/import2'");
_engine.AddModule("app", @"import { value1, value2 } from '@mine'; export const result = `${value1} ${value2}`");
var ns = _engine.ImportModule("app");
Assert.Equal("1 2", ns.Get("result").AsString());
}
[Fact]
public void ShouldAllowNamedStarExport()
{
_engine.AddModule("imported-module", builder => builder.ExportValue("value1", 5));
_engine.AddModule("my-module", "export * as ns from 'imported-module';");
var ns = _engine.ImportModule("my-module");
Assert.Equal(5, ns.Get("ns").Get("value1").AsNumber());
}
[Fact]
public void ShouldAllowChaining()
{
_engine.AddModule("dependent-module", "export const dependency = 1;");
_engine.AddModule("my-module", builder => builder
.AddSource("import { dependency } from 'dependent-module';")
.AddSource("export const output = dependency + 1;")
.ExportValue("num", JsNumber.Create(-1))
);
var ns = _engine.ImportModule("my-module");
Assert.Equal(2, ns.Get("output").AsInteger());
Assert.Equal(-1, ns.Get("num").AsInteger());
}
[Fact]
public void ShouldImportOnlyOnce()
{
var called = 0;
_engine.AddModule("imported-module", builder => builder.ExportFunction("count", args => called++));
_engine.AddModule("my-module", @"import { count } from 'imported-module'; count();");
_engine.ImportModule("my-module");
_engine.ImportModule("my-module");
Assert.Equal(1, called);
}
[Fact]
public void ShouldAllowSelfImport()
{
_engine.AddModule("my-globals", @"export const globals = { counter: 0 };");
_engine.AddModule("my-module", @"
import { globals } from 'my-globals';
import {} from 'my-module';
globals.counter++;
export const count = globals.counter;
");
var ns= _engine.ImportModule("my-module");
Assert.Equal(1, ns.Get("count").AsInteger());
}
[Fact]
public void ShouldAllowCyclicImport()
{
// https://tc39.es/ecma262/#sec-example-cyclic-module-record-graphs
_engine.AddModule("B", @"import { a } from 'A'; export const b = 'b';");
_engine.AddModule("A", @"import { b } from 'B'; export const a = 'a';");
var nsA = _engine.ImportModule("A");
var nsB = _engine.ImportModule("B");
Assert.Equal("a", nsA.Get("a").AsString());
Assert.Equal("b", nsB.Get("b").AsString());
}
#if(NET6_0_OR_GREATER)
[Fact]
public void CanLoadModuleImportsFromFiles()
{
var engine = new Engine(options => options.EnableModules(GetBasePath()));
engine.AddModule("my-module", "import { User } from './modules/user.js'; export const user = new User('John', 'Doe');");
var ns = engine.ImportModule("my-module");
Assert.Equal("John Doe", ns["user"].Get("name").AsString());
}
[Fact]
public void CanImportFromFile()
{
var engine = new Engine(options => options.EnableModules(GetBasePath()));
var ns = engine.ImportModule("./modules/format-name.js");
var result = engine.Invoke(ns.Get("formatName"), "John", "Doe").AsString();
Assert.Equal("John Doe", result);
}
private static string GetBasePath()
{
var assemblyPath = new Uri(typeof(ModuleTests).GetTypeInfo().Assembly.Location).LocalPath;
var assemblyDirectory = new FileInfo(assemblyPath).Directory;
return Path.Combine(
assemblyDirectory?.Parent?.Parent?.Parent?.FullName ?? throw new NullReferenceException("Could not find tests base path"),
"Runtime",
"Scripts");
}
#endif
}
| |
/*
* Copyright 2007-2012 JetBrains s.r.o.
*
* 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;
namespace SQLServerBackupTool.Lib.Annotations
{
/// <summary>
/// Indicates that marked element should be localized or not.
/// </summary>
/// <example>
/// <code>
/// [LocalizationRequiredAttribute(true)]
/// public class Foo
/// {
/// private string str = "my string"; // Warning: Localizable string
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class LocalizationRequiredAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="LocalizationRequiredAttribute"/> class with
/// <see cref="Required"/> set to <see langword="true"/>.
/// </summary>
public LocalizationRequiredAttribute()
: this(true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalizationRequiredAttribute"/> class.
/// </summary>
/// <param name="required"><c>true</c> if a element should be localized; otherwise, <c>false</c>.</param>
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
/// <summary>
/// Gets a value indicating whether a element should be localized.
/// <value><c>true</c> if a element should be localized; otherwise, <c>false</c>.</value>
/// </summary>
[UsedImplicitly]
public bool Required { get; private set; }
/// <summary>
/// Returns whether the value of the given object is equal to the current <see cref="LocalizationRequiredAttribute"/>.
/// </summary>
/// <param name="obj">The object to test the value equality of. </param>
/// <returns>
/// <c>true</c> if the value of the given object is equal to that of the current; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
var attribute = obj as LocalizationRequiredAttribute;
return attribute != null && attribute.Required == Required;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A hash code for the current <see cref="LocalizationRequiredAttribute"/>.</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
}
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor.
/// The format string should be in <see cref="string.Format(IFormatProvider,string,object[])"/> -like form
/// </summary>
/// <example>
/// <code>
/// [StringFormatMethod("message")]
/// public void ShowError(string message, params object[] args)
/// {
/// //Do something
/// }
/// public void Foo()
/// {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class StringFormatMethodAttribute : Attribute
{
/// <summary>
/// Initializes new instance of StringFormatMethodAttribute
/// </summary>
/// <param name="formatParameterName">Specifies which parameter of an annotated method should be treated as format-string</param>
public StringFormatMethodAttribute(string formatParameterName)
{
FormatParameterName = formatParameterName;
}
/// <summary>
/// Gets format parameter name
/// </summary>
[UsedImplicitly]
public string FormatParameterName { get; private set; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one of the parameters
/// of the caller function.
/// For example, ReSharper annotates the parameter of <see cref="System.ArgumentNullException"/>.
/// </summary>
/// <example>
/// <code>
/// public void Foo(string param)
/// {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class InvokerParameterNameAttribute : Attribute { }
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <see cref="System.ComponentModel.INotifyPropertyChanged"/> interface
/// and this method is used to notify that some property value changed.
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item><c>NotifyChanged(string)</c></item>
/// <item><c>NotifyChanged(params string[])</c></item>
/// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item>
/// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item>
/// <item><c>SetProperty{T}(ref T, T, string)</c></item>
/// </list>
/// </remarks>
/// <example>
/// <code>
/// public class Foo : INotifyPropertyChanged
/// {
/// public event PropertyChangedEventHandler PropertyChanged;
///
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName)
/// {}
///
/// private string _name;
/// public string Name
/// {
/// get { return _name; }
/// set
/// {
/// _name = value;
/// NotifyChanged("LastName"); // Warning
/// }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item><c>NotifyChanged("Property")</c></item>
/// <item><c>NotifyChanged(() => Property)</c></item>
/// <item><c>NotifyChanged((VM x) => x.Property)</c></item>
/// <item><c>SetProperty(ref myField, value, "Property")</c></item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute() { }
public NotifyPropertyChangedInvocatorAttribute(string parameterName)
{
ParameterName = parameterName;
}
[UsedImplicitly]
public string ParameterName { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage.
/// </summary>
/// <example>
/// <code>
/// [CanBeNull]
/// public object Test()
/// {
/// return null;
/// }
///
/// public void UseTest()
/// {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class CanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>
/// </summary>
/// <example>
/// <code>
/// [NotNull]
/// public object Foo()
/// {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class NotNullAttribute : Attribute { }
/// <summary>
/// Describes dependency between method input and output.
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted. <br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) for method output means that the methos doesn't return normally. <br/>
/// <c>canbenull</c> annotation is only applicable for output parameters. <br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, or use single attribute with rows separated by semicolon. <br/>
/// </syntax>
/// <examples>
/// <list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // Regular Assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // String.IsNullOrEmpty
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null, and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list>
/// </examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string fdt)
: this(fdt, false)
{
}
public ContractAnnotationAttribute([NotNull] string fdt, bool forceFullStates)
{
FDT = fdt;
ForceFullStates = forceFullStates;
}
public string FDT { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c> should be used instead.
/// However, using '==' or '!=' for comparison with <c>null</c> is always permitted.
/// </summary>
/// <example>
/// <code>
/// [CannotApplyEqualityOperator]
/// class NoEquality
/// {
/// }
///
/// class UsesNoEquality
/// {
/// public void Test()
/// {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
///
/// if (ca1 != null) // OK
/// {
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute { }
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked with
/// the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example>
/// <code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// public class ComponentAttribute : Attribute
/// {}
///
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// public class MyComponent : IComponent
/// {}
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
/// <summary>
/// Initializes new instance of BaseTypeRequiredAttribute
/// </summary>
/// <param name="baseType">Specifies which types are required</param>
public BaseTypeRequiredAttribute(Type baseType)
{
BaseTypes = new[] { baseType };
}
/// <summary>
/// Gets enumerations of specified base types
/// </summary>
public Type[] BaseTypes { get; private set; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library),
/// so this symbol will not be marked as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class UsedImplicitlyAttribute : Attribute
{
[UsedImplicitly]
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
[UsedImplicitly]
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly]
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
[UsedImplicitly]
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
[UsedImplicitly]
public ImplicitUseKindFlags UseKindFlags { get; private set; }
/// <summary>
/// Gets value indicating what is meant to be used
/// </summary>
[UsedImplicitly]
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper
/// to not mark symbols marked with such attributes as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class MeansImplicitUseAttribute : Attribute
{
[UsedImplicitly]
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
[UsedImplicitly]
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly]
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default)
{
}
[UsedImplicitly]
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
[UsedImplicitly]
public ImplicitUseKindFlags UseKindFlags { get; private set; }
/// <summary>
/// Gets value indicating what is meant to be used
/// </summary>
[UsedImplicitly]
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>
/// Only entity marked with attribute considered used
/// </summary>
Access = 1,
/// <summary>
/// Indicates implicit assignment to a member
/// </summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>
/// Indicates implicit instantiation of a type
/// </summary>
InstantiatedNoFixedConstructorSignature = 8,
}
/// <summary>
/// Specify what is considered used implicitly when marked with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>
/// Members of entity marked with attribute are considered used
/// </summary>
Members = 2,
/// <summary>
/// Entity marked with attribute and all its members considered used
/// </summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API which should not be removed and so is treated as used.
/// </summary>
[MeansImplicitUse]
public sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute() { }
public PublicAPIAttribute(string comment) { }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack.
/// If the parameter is a delegate, indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated while the method is executed.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = true)]
public sealed class InstantHandleAttribute : Attribute { }
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <see cref="System.Diagnostics.Contracts.PureAttribute"/>
/// </summary>
/// <example>
/// <code>
/// [Pure]
/// private int Multiply(int x, int y)
/// {
/// return x*y;
/// }
///
/// public void Foo()
/// {
/// const int a=2, b=2;
/// Multiply(a, b); // Waring: Return value of pure method is not used
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public sealed class PureAttribute : Attribute { }
/// <summary>
/// Indicates that a parameter is a path to a file or a folder within a web project.
/// Path can be relative or absolute, starting from web root (~).
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute() { }
[UsedImplicitly]
public PathReferenceAttribute([PathReference] string basePath)
{
BasePath = basePath;
}
[UsedImplicitly]
public string BasePath { get; private set; }
}
// ASP.NET MVC attributes
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC action.
/// If applied to a method, the MVC action name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <see cref="System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)"/>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcActionAttribute : Attribute
{
[UsedImplicitly]
public string AnonymousProperty { get; private set; }
public AspMvcActionAttribute() { }
public AspMvcActionAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC araa.
/// Use this attribute for custom wrappers similar to
/// <see cref="System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)"/>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcAreaAttribute : PathReferenceAttribute
{
[UsedImplicitly]
public string AnonymousProperty { get; private set; }
[UsedImplicitly]
public AspMvcAreaAttribute() { }
public AspMvcAreaAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC controller.
/// If applied to a method, the MVC controller name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <see cref="System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)"/>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcControllerAttribute : Attribute
{
[UsedImplicitly]
public string AnonymousProperty { get; private set; }
public AspMvcControllerAttribute() { }
public AspMvcControllerAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master.
/// Use this attribute for custom wrappers similar to
/// <see cref="System.Web.Mvc.Controller.View(String, String)"/>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcMasterAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type.
/// Use this attribute for custom wrappers similar to
/// <see cref="System.Web.Mvc.Controller.View(String, Object)"/>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcModelTypeAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC partial view.
/// If applied to a method, the MVC partial view name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <see cref="System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)"/>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcPartialViewAttribute : PathReferenceAttribute { }
/// <summary>
/// ASP.NET MVC attribute. Allows disabling all inspections for MVC views within a class or a method.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AspMvcSupressViewErrorAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <see cref="System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)"/>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcDisplayTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <see cref="System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)"/>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcEditorTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC view.
/// If applied to a method, the MVC view name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <see cref="System.Web.Mvc.Controller.View(Object)"/>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewAttribute : PathReferenceAttribute { }
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name.
/// </summary>
/// <example>
/// <code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl)
/// {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public sealed class AspMvcActionSelectorAttribute : Attribute { }
// Razor attributes
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <see cref="System.Web.WebPages.WebPageBase.RenderSection(String)"/>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, Inherited = true)]
public sealed class RazorSectionAttribute : Attribute { }
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedRegionOperationsClientTest
{
[xunit::FactAttribute]
public void DeleteRequestObject()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
DeleteRegionOperationRequest request = new DeleteRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
DeleteRegionOperationResponse expectedResponse = new DeleteRegionOperationResponse { };
mockGrpcClient.Setup(x => x.Delete(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
DeleteRegionOperationResponse response = client.Delete(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteRequestObjectAsync()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
DeleteRegionOperationRequest request = new DeleteRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
DeleteRegionOperationResponse expectedResponse = new DeleteRegionOperationResponse { };
mockGrpcClient.Setup(x => x.DeleteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeleteRegionOperationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
DeleteRegionOperationResponse responseCallSettings = await client.DeleteAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
DeleteRegionOperationResponse responseCancellationToken = await client.DeleteAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Delete()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
DeleteRegionOperationRequest request = new DeleteRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
DeleteRegionOperationResponse expectedResponse = new DeleteRegionOperationResponse { };
mockGrpcClient.Setup(x => x.Delete(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
DeleteRegionOperationResponse response = client.Delete(request.Project, request.Region, request.Operation);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAsync()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
DeleteRegionOperationRequest request = new DeleteRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
DeleteRegionOperationResponse expectedResponse = new DeleteRegionOperationResponse { };
mockGrpcClient.Setup(x => x.DeleteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeleteRegionOperationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
DeleteRegionOperationResponse responseCallSettings = await client.DeleteAsync(request.Project, request.Region, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
DeleteRegionOperationResponse responseCancellationToken = await client.DeleteAsync(request.Project, request.Region, request.Operation, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
GetRegionOperationRequest request = new GetRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
GetRegionOperationRequest request = new GetRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
GetRegionOperationRequest request = new GetRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Get(request.Project, request.Region, request.Operation);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
GetRegionOperationRequest request = new GetRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.GetAsync(request.Project, request.Region, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.Operation, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void WaitRequestObject()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
WaitRegionOperationRequest request = new WaitRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Wait(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Wait(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task WaitRequestObjectAsync()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
WaitRegionOperationRequest request = new WaitRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.WaitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.WaitAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.WaitAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Wait()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
WaitRegionOperationRequest request = new WaitRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.Wait(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
Operation response = client.Wait(request.Project, request.Region, request.Operation);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task WaitAsync()
{
moq::Mock<RegionOperations.RegionOperationsClient> mockGrpcClient = new moq::Mock<RegionOperations.RegionOperationsClient>(moq::MockBehavior.Strict);
WaitRegionOperationRequest request = new WaitRegionOperationRequest
{
Operation = "operation615a23f7",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
Operation expectedResponse = new Operation
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
User = "userb1cb11ee",
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
StartTime = "start_timebd8dd9c4",
OperationGroupId = "operation_group_idd2040cf0",
TargetLink = "target_link9b435dc0",
Progress = 278622268,
Error = new Error(),
EndTime = "end_time89285d30",
Region = "regionedb20d96",
OperationType = "operation_typeece9e153",
Status = Operation.Types.Status.Pending,
HttpErrorMessage = "http_error_messageb5ef3c7f",
TargetId = 6263187990225347157UL,
ClientOperationId = "client_operation_id4e51b631",
StatusMessage = "status_message2c618f86",
HttpErrorStatusCode = 1766362655,
Description = "description2cf9da67",
InsertTime = "insert_time7467185a",
SelfLink = "self_link7e87f12d",
Warnings = { new Warnings(), },
};
mockGrpcClient.Setup(x => x.WaitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Operation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RegionOperationsClient client = new RegionOperationsClientImpl(mockGrpcClient.Object, null);
Operation responseCallSettings = await client.WaitAsync(request.Project, request.Region, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Operation responseCancellationToken = await client.WaitAsync(request.Project, request.Region, request.Operation, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using Dashboard.Models;
namespace dashboard.Migrations
{
[DbContext(typeof(DashboardContext))]
partial class DashboardContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Dashboard.Models.AdministrativeService", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int>("Accounting");
b.Property<int>("Adjustment");
b.Property<int>("AdministratorsPayroll");
b.Property<int>("AmortizationOrganizationCost");
b.Property<int>("AmortizationStartupCost");
b.Property<int>("AutoExpense");
b.Property<int>("CentralOfficeOverhead");
b.Property<int>("Communications");
b.Property<int>("DataProcessing");
b.Property<int>("DuesAndSubscriptions");
b.Property<int>("EmployeeBenefit");
b.Property<int>("Entertaining");
b.Property<int>("GrandTotal");
b.Property<int>("InventoryLicenseTax");
b.Property<int>("Legal");
b.Property<int>("ManagementService");
b.Property<int>("NonPropertyInsurance");
b.Property<int>("OfficeStaffPayroll");
b.Property<int>("Other");
b.Property<int>("Supply");
b.Property<int>("Total");
b.Property<int>("Travel");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.AdministrativeServiceOther", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int>("DepreciationTransportationEquipment");
b.Property<int>("EmployeeBenefit");
b.Property<int>("InterestWorkingCapitalAndAutoLoan");
b.Property<int>("MedicalContractedService");
b.Property<int>("MedicalPayroll");
b.Property<int>("MedicalSupply");
b.Property<int>("MedicalTotal");
b.Property<int>("QualityAssurance");
b.Property<int>("TrainingContractedService");
b.Property<int>("TrainingPayroll");
b.Property<int>("TrainingSupply");
b.Property<int>("TrainingTotal");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.AllowanceAndAdjustmentsToRevenue", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int>("AdministrativeAdjustment");
b.Property<int>("CharityServiceComprehensiveCare");
b.Property<int>("CharityServiceOther");
b.Property<int>("ConctractualAllowanceComprehensiveCareMedicare");
b.Property<int>("ContractualAllowanceComprehensiveCareMedicalAssitance");
b.Property<int>("ContractualAllowanceOtherMedicalAssistance");
b.Property<int>("ContractualAllowanceOtherMedicare");
b.Property<string>("Custom1Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("Custom1Revenue");
b.Property<int>("DubiousAccountsProvision");
b.Property<int>("PriorYearSettlementMedicalAssistance");
b.Property<int>("PriorYearSettlementMedicare");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.AncillaryRevenue", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int>("AttachmentsRevenue");
b.Property<string>("Custom1Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("Custom1Revenue");
b.Property<string>("Custom2Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("Custom2Revenue");
b.Property<int>("EquipmentRental");
b.Property<int>("Laboratory");
b.Property<int>("MedicalSupplies");
b.Property<int>("OccupationalTherapy");
b.Property<int>("Oxygen");
b.Property<int>("Pharmacy");
b.Property<int>("PhysicalTherapy");
b.Property<int>("PhysicianCare");
b.Property<int>("Radiology");
b.Property<int>("RecreationalActivities");
b.Property<int>("SpeechTherapy");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.CapitalPropertyService", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int>("HomeOfficeEquipmentDepreciation");
b.Property<int>("HomeOfficeEquipmentInterest");
b.Property<int>("HomeOfficeRealEstateDepreciation");
b.Property<int>("HomeOfficeRealEstateInterest");
b.Property<int>("RecurringAdjustment");
b.Property<int>("RecurringMajorEquipmentInsurance");
b.Property<int>("RecurringMajorEquipmentInterest");
b.Property<int>("RecurringMajorEquipmentTax");
b.Property<int>("RecurringMortgageAcquisitionCostAmortization");
b.Property<int>("RecurringRealEstateInsurance");
b.Property<int>("RecurringRealEstateInterest");
b.Property<int>("RecurringRealEstateTax");
b.Property<int>("RecurringTotal");
b.Property<int>("ReplacedAdjustment");
b.Property<int>("ReplacedLeaseholdImprovementAmortization");
b.Property<int>("ReplacedMajorEquipmentDepreciation");
b.Property<int>("ReplacedMajorEquipmentRental");
b.Property<int>("ReplacedRealEstateDepreciation");
b.Property<int>("ReplacedRealEstateRental");
b.Property<int>("ReplacedTotal");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.CountyAverage", b =>
{
b.Property<int>("CountyCode");
b.Property<int>("FiscalYear");
b.Property<int?>("ComprehensiveDays");
b.Property<decimal?>("ComprehensiveRevenuePerDay");
b.Property<decimal?>("DietaryExpensePerDay");
b.Property<decimal?>("GovernmentAndAdministrativeExpensePerDay");
b.Property<decimal?>("HousekeepingAndLaundryExpensePerDay");
b.Property<int?>("MedicaidDays");
b.Property<decimal?>("MedicaidDaysPercent");
b.Property<decimal?>("MedicaidRevenuePerDay");
b.Property<int?>("MedicareDays");
b.Property<decimal?>("MedicareDaysPercent");
b.Property<decimal?>("MedicareRevenuePerDay");
b.Property<decimal?>("NetIncomePerDay");
b.Property<decimal?>("NetIncomePerRevenuePercent");
b.Property<decimal?>("NursingCareExpensePerDay");
b.Property<decimal?>("NursingOccupancyPercent");
b.Property<int?>("OtherComprehensiveDays");
b.Property<decimal?>("OtherComprehensiveDaysPercent");
b.Property<decimal?>("OtherComprehensiveRevenuePerDay");
b.Property<decimal?>("OtherPatientCareExpensePerDay");
b.Property<decimal?>("OtherRevenuePerDay");
b.Property<int?>("PrivateDays");
b.Property<decimal?>("PrivateDaysPercent");
b.Property<decimal?>("PrivateRevenuePerDay");
b.Property<decimal?>("PropertyExpensePerDay");
b.Property<decimal?>("RealEstateTaxPerDay");
b.Property<decimal?>("TotalExpensePerDay");
b.Property<decimal?>("TotalRevenuePerDay");
b.HasKey("CountyCode", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.Description", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<DateTime>("FiscalEndDate")
.HasAnnotation("Relational:ColumnType", "date");
b.Property<int>("OperatingDays");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.Home", b =>
{
b.Property<int>("PIN");
b.Property<string>("City")
.IsRequired();
b.Property<int>("CountyCode");
b.Property<string>("CountyName")
.IsRequired();
b.Property<double>("Latitude");
b.Property<double>("Longitude");
b.Property<string>("Name")
.IsRequired();
b.Property<long>("Phone");
b.Property<string>("State")
.IsRequired()
.HasAnnotation("MaxLength", 2)
.HasAnnotation("Relational:ColumnType", "nchar");
b.Property<string>("Street")
.IsRequired();
b.Property<int>("ZipCode");
b.HasKey("PIN");
});
modelBuilder.Entity("Dashboard.Models.NursingCareService", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int>("ContractedService");
b.Property<int>("EmployeeBenefits");
b.Property<int>("OtherAdjustments");
b.Property<int>("OtherCosts");
b.Property<int>("Payroll");
b.Property<int>("Supply");
b.Property<int>("Total");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.OperationsSummary", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int>("AdministrativeServiceAdjustedExpense");
b.Property<int>("AdministrativeServiceBookExpense");
b.Property<int>("BeforeIncomeTaxNetIncome");
b.Property<int>("CapitalOrPropertyServiceAdjusedExpense");
b.Property<int>("CapitalOrPropertyServiceBookExpense");
b.Property<int>("CapitalValueRentalAdjustedExpense");
b.Property<int>("CapitalValueRentalBookExpense");
b.Property<int>("GrossOperatingProfit");
b.Property<int>("IncomeTaxProvision");
b.Property<int>("LessAllowancesAndAdjustmentsRevenue");
b.Property<int>("NetRevenue");
b.Property<int>("NonOperatingRevenue");
b.Property<int>("NonReimbursableExpense");
b.Property<int>("NursingCareServiceAdjustedExpense");
b.Property<int>("NursingCareServiceBookExpense");
b.Property<int>("OtherPatientCareServiceAdjustedExpense");
b.Property<int>("OtherPatientCareServiceBookExpense");
b.Property<int>("PerFinancialStatementsNetIncome");
b.Property<int>("RoutineServiceBookExpense");
b.Property<int>("RoutineServiceRevenue");
b.Property<int>("RoutingServiceAdjustedExpense");
b.Property<int>("SpecialServiceRevenue");
b.Property<int>("TotalAdjustedOperatingExpense");
b.Property<int>("TotalBookOperatingExpense");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.PatientCareService", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int>("BarberAndBeautyShopPayroll");
b.Property<int>("EmployeeBenefit");
b.Property<int?>("LaboratoryContractedService");
b.Property<int?>("LaboratoryPayroll");
b.Property<int?>("LaboratorySupply");
b.Property<int>("MedicalDirectorContractedService");
b.Property<int>("MedicalDirectorPayroll");
b.Property<int>("MedicalDirectorSupply");
b.Property<int>("OccupationalTherapyContractedService");
b.Property<int>("OccupationalTherapyPayroll");
b.Property<int>("OccupationalTherapySupply");
b.Property<int>("Other");
b.Property<int>("OtherAdjustment");
b.Property<int>("OxygenContractedService");
b.Property<int>("OxygenPayroll");
b.Property<int>("OxygenSupply");
b.Property<int>("PatientCareContractedService");
b.Property<int>("PatientCarePayroll");
b.Property<int>("PatientCareSupply");
b.Property<int>("PharmacyContractedService");
b.Property<int>("PharmacyOverTheCounterDrugs");
b.Property<int>("PharmacyPayroll");
b.Property<int>("PharmacySupply");
b.Property<int>("PhysicalTherapyContractedService");
b.Property<int>("PhysicalTherapyPayroll");
b.Property<int>("PhysicalTherapySupply");
b.Property<int?>("RadiologyContractedService");
b.Property<int?>("RadiologyPayroll");
b.Property<int?>("RadiologySupply");
b.Property<int>("RawFood");
b.Property<int>("RecreationContractedService");
b.Property<int>("RecreationPayroll");
b.Property<int>("RecreationSupply");
b.Property<int>("ReligiousServiceContractedService");
b.Property<int>("ReligiousServiceOther");
b.Property<int>("ReligiousServicePayroll");
b.Property<int>("ReligiousServiceSupply");
b.Property<int>("ReligiousServiceTotal");
b.Property<int>("SocialServiceContractedService");
b.Property<int>("SocialServiceOther");
b.Property<int>("SocialServicePayroll");
b.Property<int>("SocialServiceSupply");
b.Property<int>("SocialServiceTotal");
b.Property<int?>("SpeechTherapyContractedService");
b.Property<int?>("SpeechTherapyPayroll");
b.Property<int?>("SpeechTherapySupply");
b.Property<int>("Total");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.RoutineService", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int>("DietaryAdjustment");
b.Property<decimal?>("DietaryBenefit")
.ValueGeneratedOnAddOrUpdate()
.HasAnnotation("Relational:ColumnType", "numeric");
b.Property<int>("DietaryContractedService");
b.Property<int>("DietaryOther");
b.Property<int>("DietaryPayroll");
b.Property<int>("DietarySupply");
b.Property<int>("DietaryTotal");
b.Property<int>("EmployeeBenefit");
b.Property<int>("HousekeepingAdjustment");
b.Property<decimal?>("HousekeepingAndLaundryBenefit")
.ValueGeneratedOnAddOrUpdate()
.HasAnnotation("Relational:ColumnType", "numeric");
b.Property<int>("HousekeepingContractService");
b.Property<int>("HousekeepingOther");
b.Property<int>("HousekeepingPayroll");
b.Property<int>("HousekeepingSupply");
b.Property<int>("HousekeepingTotal");
b.Property<int>("LaundryAdjustment");
b.Property<int>("LaundryContractedService");
b.Property<int>("LaundryLinenReplacement");
b.Property<int>("LaundryOther");
b.Property<int>("LaundryPayroll");
b.Property<int>("LaundrySupply");
b.Property<int>("LaundryTotal");
b.Property<int>("MainenanceMinorEquipment");
b.Property<int>("MaintenanceAdjustment");
b.Property<int>("MaintenanceContractedService");
b.Property<int>("MaintenanceOther");
b.Property<int>("MaintenancePayroll");
b.Property<int>("MaintenanceRepair");
b.Property<int>("MaintenanceSupply");
b.Property<int>("MaintenanceTotal");
b.Property<int>("MaintenanceUtility");
b.Property<decimal?>("PropertyBenefit")
.ValueGeneratedOnAddOrUpdate()
.HasAnnotation("Relational:ColumnType", "numeric");
b.Property<int>("Total");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.RoutineServiceRevenue", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<string>("ComprehensiveCareCustom1Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("ComprehensiveCareCustom1PatientDays");
b.Property<int>("ComprehensiveCareCustom1Revenue");
b.Property<string>("ComprehensiveCareCustom2Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("ComprehensiveCareCustom2PatientDays");
b.Property<int>("ComprehensiveCareCustom2Revenue");
b.Property<string>("ComprehensiveCareCustom3Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("ComprehensiveCareCustom3PatientDays");
b.Property<int>("ComprehensiveCareCustom3Revenue");
b.Property<int>("ComprehensiveCareMedicaidPatientDays");
b.Property<int>("ComprehensiveCareMedicaidRevenue");
b.Property<int>("ComprehensiveCareMedicarePatientDays");
b.Property<int>("ComprehensiveCareMedicareRevenue");
b.Property<int?>("ComprehensiveCareOtherPatientDaysTotal")
.ValueGeneratedOnAddOrUpdate();
b.Property<int?>("ComprehensiveCareOtherRevenueTotal")
.ValueGeneratedOnAddOrUpdate();
b.Property<int?>("ComprehensiveCarePatientDaysTotal")
.ValueGeneratedOnAddOrUpdate();
b.Property<int>("ComprehensiveCarePrivatePatientDays");
b.Property<int>("ComprehensiveCarePrivateRevenue");
b.Property<int?>("ComprehensiveCareRevenueTotal")
.ValueGeneratedOnAddOrUpdate();
b.Property<string>("OtherCareCustom1Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("OtherCareCustom1PatientDays");
b.Property<int>("OtherCareCustom1Revenue");
b.Property<string>("OtherCareCustom2Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("OtherCareCustom2PatientDays");
b.Property<int>("OtherCareCustom2Revenue");
b.Property<string>("OtherCareCustom3Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("OtherCareCustom3PatientDays");
b.Property<int>("OtherCareCustom3Revenue");
b.Property<string>("OtherCareCustom4Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("OtherCareCustom4PatientDays");
b.Property<int>("OtherCareCustom4Revenue");
b.Property<string>("OtherCareCustom5Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("OtherCareCustom5PatientDays");
b.Property<int>("OtherCareCustom5Revenue");
b.Property<string>("OtherCareCustom6Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("OtherCareCustom6PatientDays");
b.Property<int>("OtherCareCustom6Revenue");
b.Property<string>("OtherCareCustom7Name")
.HasAnnotation("MaxLength", 70);
b.Property<int>("OtherCareCustom7PatientDays");
b.Property<int>("OtherCareCustom7Revenue");
b.Property<int?>("OtherCarePatientDaysTotal")
.ValueGeneratedOnAddOrUpdate();
b.Property<int?>("OtherCareRevenueTotal")
.ValueGeneratedOnAddOrUpdate();
b.Property<int?>("RevenueTotal")
.ValueGeneratedOnAddOrUpdate();
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.StateAverage", b =>
{
b.Property<string>("State")
.HasAnnotation("MaxLength", 2);
b.Property<int>("FiscalYear");
b.Property<int?>("ComprehensiveDays");
b.Property<decimal?>("ComprehensiveRevenuePerDay");
b.Property<decimal?>("DietaryExpensePerDay");
b.Property<decimal?>("GovernmentAndAdministrativeExpensePerDay");
b.Property<decimal?>("HousekeepingAndLaundryExpensePerDay");
b.Property<int?>("MedicaidDays");
b.Property<decimal?>("MedicaidDaysPercent");
b.Property<decimal?>("MedicaidRevenuePerDay");
b.Property<int?>("MedicareDays");
b.Property<decimal?>("MedicareDaysPercent");
b.Property<decimal?>("MedicareRevenuePerDay");
b.Property<decimal?>("NetIncomePerDay");
b.Property<decimal?>("NetIncomePerRevenuePercent");
b.Property<decimal?>("NursingCareExpensePerDay");
b.Property<decimal?>("NursingOccupancyPercent");
b.Property<int?>("OtherComprehensiveDays");
b.Property<decimal?>("OtherComprehensiveDaysPercent");
b.Property<decimal?>("OtherComprehensiveRevenuePerDay");
b.Property<decimal?>("OtherPatientCareExpensePerDay");
b.Property<decimal?>("OtherRevenuePerDay");
b.Property<int?>("PrivateDays");
b.Property<decimal?>("PrivateDaysPercent");
b.Property<decimal?>("PrivateRevenuePerDay");
b.Property<decimal?>("PropertyExpensePerDay");
b.Property<decimal?>("RealEstateTaxPerDay");
b.Property<decimal?>("TotalExpensePerDay");
b.Property<decimal?>("TotalRevenuePerDay");
b.HasKey("State", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.Statistics", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int>("AvailableComprehensiveDays");
b.Property<double?>("ComprehensiveMedicaidPercent");
b.Property<double>("ComprehensiveOccupancyPercent");
b.Property<int>("MedicaidComprehensiveDays");
b.Property<int>("MedicareComprehensiveDays");
b.Property<int>("PrivatePayComprehensiveDays");
b.Property<int>("TotalComprehensiveDays");
b.HasKey("PIN", "FiscalYear");
});
modelBuilder.Entity("Dashboard.Models.Summary", b =>
{
b.Property<int>("PIN");
b.Property<int>("FiscalYear");
b.Property<int?>("AvailableDays");
b.Property<int?>("CertifiedBedCount");
b.Property<int>("ComprehensiveCareCustom1InsuranceDays");
b.Property<int>("ComprehensiveCareCustom2InsuranceDays");
b.Property<int>("ComprehensiveCareCustom3InsuranceDays");
b.Property<decimal?>("ComprehensiveDailyCensus");
b.Property<int?>("ComprehensiveDays");
b.Property<decimal?>("ComprehensivePayor1DailyCensus");
b.Property<decimal>("ComprehensivePayor1DailyCensusPercent");
b.Property<int>("ComprehensivePayor1Days");
b.Property<string>("ComprehensivePayor1Name");
b.Property<decimal?>("ComprehensivePayor1Revenue");
b.Property<decimal>("ComprehensivePayor1RevenuePerDay");
b.Property<decimal?>("ComprehensivePayor2DailyCensus");
b.Property<decimal>("ComprehensivePayor2DailyCensusPercent");
b.Property<int>("ComprehensivePayor2Days");
b.Property<string>("ComprehensivePayor2Name");
b.Property<decimal?>("ComprehensivePayor2Revenue");
b.Property<decimal>("ComprehensivePayor2RevenuePerDay");
b.Property<decimal?>("ComprehensivePayor3DailyCensus");
b.Property<decimal>("ComprehensivePayor3DailyCensusPercent");
b.Property<int>("ComprehensivePayor3Days");
b.Property<string>("ComprehensivePayor3Name");
b.Property<decimal?>("ComprehensivePayor3Revenue");
b.Property<decimal>("ComprehensivePayor3RevenuePerDay");
b.Property<int?>("ComprehensiveRevenue");
b.Property<decimal>("ComprehensiveRevenuePerDay");
b.Property<decimal?>("ComprehensiveRevenuePercent");
b.Property<decimal?>("DietaryExpense");
b.Property<decimal>("DietaryExpensePerDay");
b.Property<decimal?>("DietaryExpensePerRevenuePercent");
b.Property<int?>("GovernmentAndAdministrativeExpense");
b.Property<decimal>("GovernmentAndAdministrativeExpensePerDay");
b.Property<decimal?>("GovernmentAndAdministrativeExpensePerRevenuePercent");
b.Property<decimal?>("HousekeepingAndLaundryExpense");
b.Property<decimal>("HousekeepingAndLaundryExpensePerDay");
b.Property<decimal?>("HousekeepingAndLaundryExpensePerRevenuePercent");
b.Property<decimal?>("ImpliedMaxValue");
b.Property<decimal?>("ImpliedMaxValuePerBed");
b.Property<decimal?>("ImpliedMinValue");
b.Property<decimal?>("ImpliedMinValuePerBed");
b.Property<decimal?>("MedicaidDailyCensus");
b.Property<int>("MedicaidDays");
b.Property<decimal?>("MedicaidDaysPercent");
b.Property<int?>("MedicaidRevenue");
b.Property<decimal>("MedicaidRevenuePerDay");
b.Property<decimal?>("MedicareDailyCensus");
b.Property<int>("MedicareDays");
b.Property<decimal?>("MedicareDaysPercent");
b.Property<decimal?>("MedicareRevenue");
b.Property<decimal>("MedicareRevenuePerDay");
b.Property<decimal?>("NetIncome");
b.Property<decimal?>("NetIncomePerBed");
b.Property<decimal>("NetIncomePerDay");
b.Property<decimal?>("NetIncomePerRevenuePercent");
b.Property<int?>("NursingCareExpense");
b.Property<decimal>("NursingCareExpensePerDay");
b.Property<decimal?>("NursingCareExpensePerRevenuePercent");
b.Property<decimal?>("NursingOccupancyPercent");
b.Property<int>("OperatingDays");
b.Property<int?>("OtherCareDays");
b.Property<decimal?>("OtherComprehensiveDailyCensus");
b.Property<int?>("OtherComprehensiveDays");
b.Property<decimal?>("OtherComprehensiveDaysPercent");
b.Property<decimal?>("OtherComprehensiveRevenue");
b.Property<decimal>("OtherComprehensiveRevenuePerDay");
b.Property<int>("OtherPatientCareExpense");
b.Property<decimal>("OtherPatientCareExpensePerDay");
b.Property<decimal?>("OtherPatientCareExpensePerRevenuePercent");
b.Property<int?>("OtherRevenue");
b.Property<decimal>("OtherRevenuePerDay");
b.Property<decimal?>("OtherRevenuePercent");
b.Property<decimal?>("PrivateDailyCensus");
b.Property<int>("PrivateDays");
b.Property<decimal?>("PrivateDaysPercent");
b.Property<int>("PrivateRevenue");
b.Property<decimal>("PrivateRevenuePerDay");
b.Property<decimal?>("PropertyExpense");
b.Property<decimal>("PropertyExpensePerDay");
b.Property<decimal?>("PropertyExpensePerRevenuePercent");
b.Property<int>("RealEstateTax");
b.Property<decimal>("RealEstateTaxPerDay");
b.Property<decimal?>("RealEstateTaxPerRevenuePercent");
b.Property<int>("SpecialServiceRevenue");
b.Property<int?>("TotalDays");
b.Property<decimal?>("TotalExpense");
b.Property<decimal>("TotalExpensePerDay");
b.Property<decimal?>("TotalExpensePerRevenuePercent");
b.Property<int?>("TotalRevenue");
b.Property<decimal>("TotalRevenuePerDay");
b.Property<int>("UnadjustedComprehensivePayor1Revenue");
b.Property<int>("UnadjustedComprehensivePayor2Revenue");
b.Property<int>("UnadjustedComprehensivePayor3Revenue");
b.Property<int?>("UnadjustedMedicareRevenue");
b.Property<int?>("UnadjustedOtherComprehensiveRevenue");
b.HasKey("PIN", "FiscalYear");
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.RetryPolicies;
using Microsoft.WindowsAzure.Storage.Table;
using TechSmith.Hyde.Common;
namespace TechSmith.Hyde.Table.Azure
{
internal class AzureTableEntityTableContext : ITableContext
{
private readonly ICloudStorageAccount _storageAccount;
private readonly Queue<ExecutableTableOperation> _operations = new Queue<ExecutableTableOperation>();
private readonly TableRequestOptions _retriableTableRequest = new TableRequestOptions
{
RetryPolicy = new ExponentialRetry( TimeSpan.FromSeconds( 1 ), 4 )
};
public AzureTableEntityTableContext( ICloudStorageAccount storageAccount )
{
_storageAccount = storageAccount;
}
public IFilterable<T> CreateQuery<T>( string tableName ) where T : new()
{
return new AzureQuery<T>( Table( tableName ) );
}
public IFilterable<dynamic> CreateQuery( string tableName, bool includeETagForDynamic )
{
return new AzureDynamicQuery( Table( tableName ), includeETagForDynamic );
}
public void AddNewItem( string tableName, TableItem tableItem )
{
GenericTableEntity genericTableEntity = GenericTableEntity.HydrateFrom( tableItem );
var operation = TableOperation.Insert( genericTableEntity );
_operations.Enqueue( new ExecutableTableOperation( tableName, operation, TableOperationType.Insert, tableItem.PartitionKey, tableItem.RowKey ) );
}
public void Upsert( string tableName, TableItem tableItem )
{
// Upsert does not use an ETag (If-Match header) - http://msdn.microsoft.com/en-us/library/windowsazure/hh452242.aspx
GenericTableEntity genericTableEntity = GenericTableEntity.HydrateFrom( tableItem );
var operation = TableOperation.InsertOrReplace( genericTableEntity );
_operations.Enqueue( new ExecutableTableOperation( tableName, operation, TableOperationType.InsertOrReplace, tableItem.PartitionKey, tableItem.RowKey ) );
}
public void Update( string tableName, TableItem tableItem, ConflictHandling conflictHandling )
{
GenericTableEntity genericTableEntity = GenericTableEntity.HydrateFrom( tableItem );
if ( ShouldForceOverwrite( conflictHandling, genericTableEntity ) )
{
genericTableEntity.ETag = "*";
}
var operation = TableOperation.Replace( genericTableEntity );
_operations.Enqueue( new ExecutableTableOperation( tableName, operation, TableOperationType.Replace, tableItem.PartitionKey, tableItem.RowKey ) );
}
private static bool ShouldForceOverwrite( ConflictHandling conflictHandling, GenericTableEntity genericTableEntity )
{
return string.IsNullOrEmpty( genericTableEntity.ETag ) || conflictHandling.Equals( ConflictHandling.Overwrite );
}
public void Merge( string tableName, TableItem tableItem, ConflictHandling conflictHandling )
{
GenericTableEntity genericTableEntity = GenericTableEntity.HydrateFrom( tableItem );
if ( ShouldForceOverwrite( conflictHandling, genericTableEntity ) )
{
genericTableEntity.ETag = "*";
}
var operation = TableOperation.Merge( genericTableEntity );
_operations.Enqueue( new ExecutableTableOperation( tableName, operation, TableOperationType.Merge, tableItem.PartitionKey, tableItem.RowKey ) );
}
public void DeleteItem( string tableName, string partitionKey, string rowKey )
{
var operation = TableOperation.Delete( new GenericTableEntity
{
ETag = "*",
PartitionKey = partitionKey,
RowKey = rowKey
} );
_operations.Enqueue( new ExecutableTableOperation( tableName, operation, TableOperationType.Delete, partitionKey, rowKey ) );
}
public void DeleteItem( string tableName, TableItem tableItem, ConflictHandling conflictHandling )
{
var genericTableEntity = GenericTableEntity.HydrateFrom( tableItem );
if ( ShouldForceOverwrite( conflictHandling, genericTableEntity ) )
{
genericTableEntity.ETag = "*";
}
var operation = TableOperation.Delete( genericTableEntity );
_operations.Enqueue( new ExecutableTableOperation( tableName, operation, TableOperationType.Delete, tableItem.PartitionKey, tableItem.RowKey ) );
}
public Task SaveAsync( Execute executeMethod )
{
if ( !_operations.Any() )
{
return Task.FromResult( 0 );
}
try
{
switch ( executeMethod )
{
case Execute.Individually:
{
return SaveIndividualAsync( new List<ExecutableTableOperation>( _operations ) );
}
case Execute.InBatches:
{
return SaveBatchAsync( new List<ExecutableTableOperation>( _operations ) );
}
case Execute.Atomically:
{
return SaveAtomicallyAsync( new List<ExecutableTableOperation>( _operations ) );
}
default:
{
throw new ArgumentException( "Unsupported execution method: " + executeMethod );
}
}
}
finally
{
_operations.Clear();
}
}
private async Task SaveIndividualAsync( IEnumerable<ExecutableTableOperation> operations )
{
foreach ( var executableTableOperation in operations )
{
await ToTask( executableTableOperation ).ConfigureAwait( false );
}
}
private Task ToTask( ExecutableTableOperation operation )
{
var table = Table( operation.Table );
return HandleTableStorageExceptions( TableOperationType.Delete == operation.OperationType, table.ExecuteAsync( operation.Operation, _retriableTableRequest, null ) );
}
private static async Task HandleTableStorageExceptions( bool isUnbatchedDelete, Task action )
{
try
{
await action.ConfigureAwait( false );
}
catch ( StorageException ex )
{
if ( ex.RequestInformation.HttpStatusCode == (int) HttpStatusCode.NotFound && isUnbatchedDelete )
{
return;
}
if ( ex.RequestInformation.HttpStatusCode == (int) HttpStatusCode.BadRequest &&
isUnbatchedDelete &&
ex.RequestInformation.ExtendedErrorInformation.ErrorCode == "OutOfRangeInput" )
{
// The table does not exist.
return;
}
if ( ex.RequestInformation.HttpStatusCode == (int) HttpStatusCode.Conflict )
{
throw new EntityAlreadyExistsException( "Entity already exists", ex );
}
if ( ex.RequestInformation.HttpStatusCode == (int) HttpStatusCode.NotFound )
{
throw new EntityDoesNotExistException( "Entity does not exist", ex );
}
if ( ex.RequestInformation.HttpStatusCode == (int) HttpStatusCode.PreconditionFailed )
{
throw new EntityHasBeenChangedException( "Entity has been changed", ex );
}
if ( ex.RequestInformation.HttpStatusCode == (int) HttpStatusCode.BadRequest )
{
throw new InvalidOperationException( "Table storage returned 'Bad Request'", ex );
}
throw;
}
}
private static List<List<ExecutableTableOperation>> ValidateAndSplitIntoBatches(
IEnumerable<ExecutableTableOperation> operations )
{
// For two operations to appear in the same batch...
Func<ExecutableTableOperation, ExecutableTableOperation, bool> canBatch = ( op1, op2 ) =>
// they must be on the same table
op1.Table == op2.Table
// and the same partition
&& op1.PartitionKey == op2.PartitionKey
// and neither can be a delete,
&& !( op1.OperationType == TableOperationType.Delete || op2.OperationType == TableOperationType.Delete )
// and the row keys must be different.
&& op1.RowKey != op2.RowKey;
// Group consecutive batchable operations
var batches = new List<List<ExecutableTableOperation>> { new List<ExecutableTableOperation>() };
foreach ( var nextOperation in operations )
{
// start a new batch if the current batch is full, or if any operation in the current
// batch conflicts with the next operation.
if ( batches.Last().Count == 100 || batches.Last().Any( op => !canBatch( op, nextOperation ) ) )
{
batches.Add( new List<ExecutableTableOperation>() );
}
batches.Last().Add( nextOperation );
}
return batches;
}
private async Task SaveBatchAsync( IEnumerable<ExecutableTableOperation> operations )
{
var batches = ValidateAndSplitIntoBatches( operations );
foreach ( var batch in batches )
{
// No need to use an EGT for a single operation.
if ( batch.Count == 1 )
{
await SaveIndividualAsync( new[] { batch[0] } ).ConfigureAwait( false );
continue;
}
await SaveAtomicallyAsync( batch ).ConfigureAwait( false );
}
}
private TableBatchOperation ValidateAndCreateBatchOperation( IEnumerable<ExecutableTableOperation> operations, out CloudTable table )
{
var operationsList = operations.ToList();
var partitionKeys = operationsList.Select( op => op.PartitionKey ).Distinct();
if ( partitionKeys.Count() > 1 )
{
throw new InvalidOperationException( "Cannot atomically execute operations on different partitions" );
}
var tables = operationsList.Select( op => op.Table ).Distinct().ToList();
if ( tables.Count() > 1 )
{
throw new InvalidOperationException( "Cannot atomically execute operations on multiple tables" );
}
var batchOperation = new TableBatchOperation();
foreach ( var tableOperation in operationsList )
{
batchOperation.Add( tableOperation.Operation );
}
table = batchOperation.Count == 0 ? null : Table( tables[0] );
return batchOperation;
}
private Task SaveAtomicallyAsync( IEnumerable<ExecutableTableOperation> operations )
{
CloudTable table;
var batchOperation = ValidateAndCreateBatchOperation( operations, out table );
if ( batchOperation.Count == 0 )
{
return Task.FromResult( 0 );
}
return HandleTableStorageExceptions( false, table.ExecuteBatchAsync( batchOperation, _retriableTableRequest, null ) );
}
private CloudTable Table( string tableName )
{
bool hasSecondaryEndpoint = !string.IsNullOrWhiteSpace( _storageAccount.ReadonlyFallbackTableEndpoint );
Uri primaryEndpoint = new Uri( _storageAccount.TableEndpoint );
StorageUri storageUri = hasSecondaryEndpoint ? new StorageUri( primaryEndpoint, new Uri( _storageAccount.ReadonlyFallbackTableEndpoint ) ) : new StorageUri( primaryEndpoint );
var cloudTableClient = new CloudTableClient( storageUri, _storageAccount.Credentials );
if ( hasSecondaryEndpoint )
{
cloudTableClient.DefaultRequestOptions.LocationMode = LocationMode.PrimaryThenSecondary;
}
return cloudTableClient.GetTableReference( tableName );
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
#if BUILD_PEANUTBUTTER_INTERNAL
namespace Imported.PeanutButter.Utils
#else
namespace PeanutButter.Utils
#endif
{
/// <summary>
/// Used to describe a wrapper
/// - IsValid should flag whether or not the wrapping was successful
/// </summary>
#if BUILD_PEANUTBUTTER_INTERNAL
internal
#else
public
#endif
interface IEnumerableWrapper
{
/// <summary>
/// Flag: communicates if the wrapping was successful. Unsuccessful wraps
/// will result in empty enumerations.
/// </summary>
bool IsValid { get; }
}
/// <summary>
/// Wraps an object which would be an acceptable enumerable in a foreach
/// (due to .NET compile-time duck-typing) into an actual IEnumerator
/// </summary>
#if BUILD_PEANUTBUTTER_INTERNAL
internal
#else
public
#endif
class EnumerableWrapper : IEnumerable, IEnumerableWrapper
{
/// <inheritdoc />
public bool IsValid { get; }
private readonly object _toWrap;
private static readonly BindingFlags PublicInstance = BindingFlags.Public | BindingFlags.Instance;
private static readonly Type EnumeratorType = typeof(IEnumerator);
private static readonly PropertyInfo[] EnumeratorProps = EnumeratorType.GetProperties(PublicInstance);
private static readonly MethodInfo[] RequiredEnumeratorMethods =
EnumeratorType.GetMethods(PublicInstance)
// Reset is optional!
.Where(mi => mi.Name != nameof(IEnumerator.Reset))
.ToArray();
/// <summary>
/// Construct an EnumerableWrapper around a (hopefully) enumerable object
/// </summary>
/// <param name="toWrap"></param>
public EnumerableWrapper(object toWrap)
{
if (toWrap == null)
{
IsValid = false;
return;
}
_toWrap = toWrap;
var getEnumeratorMethod = toWrap.GetType()
.GetMethod(nameof(GetEnumerator));
IsValid = getEnumeratorMethod != null &&
(IsEnumeratorType(getEnumeratorMethod.ReturnType) ||
IsEnumeratorType(getEnumeratorMethod.Invoke(toWrap, new object[0])?.GetType()));
}
/// <inheritdoc />
public IEnumerator GetEnumerator()
{
return MakeEnumerator<object>();
}
/// <summary>
/// Creates the enumerator
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected IEnumerator<T> MakeEnumerator<T>()
{
var result = new EnumeratorWrapper<T>(_toWrap);
return result.IsValid
? result
: new EnumeratorWrapper<T>(new T[0]); // fake no results
}
private bool IsEnumeratorType(
Type returnType)
{
return returnType != null &&
PropsAreAtLeast(
EnumeratorProps,
returnType.GetProperties(PublicInstance)) &&
MethodsAreAtLeast(
RequiredEnumeratorMethods,
returnType.GetMethods(PublicInstance));
}
private bool MethodsAreAtLeast(
MethodInfo[] required,
MethodInfo[] test)
{
return required.Select(r => test.Any(t => MethodsMatch(r, t)))
.Aggregate(true, (acc, cur) => acc && cur);
}
private bool MethodsMatch(
MethodInfo left,
MethodInfo right)
{
if (left.Name != right.Name ||
!left.ReturnType.IsAssignableFrom(right.ReturnType))
{
return false;
}
var leftParams = left.GetParameters();
var rightParams = right.GetParameters();
if (leftParams.Length != rightParams.Length)
{
return false;
}
return leftParams.Zip(rightParams, Tuple.Create)
.Aggregate(
true,
(acc, cur) => acc && cur.Item1.ParameterType == cur.Item2.ParameterType
);
}
private bool PropsAreAtLeast(
PropertyInfo[] required,
PropertyInfo[] test)
{
return required
.Select(l => test.Any(r => PropsMatch(l, r)))
.Aggregate(true, (acc, cur) => acc && cur);
}
private bool PropsMatch(
PropertyInfo left,
PropertyInfo right)
{
return left.Name == right.Name &&
left.PropertyType.IsAssignableFrom(right.PropertyType);
}
}
/// <summary>
/// Provides the typed EnumerableWrapper
/// </summary>
/// <typeparam name="T"></typeparam>
#if BUILD_PEANUTBUTTER_INTERNAL
internal
#else
public
#endif
class EnumerableWrapper<T> : EnumerableWrapper, IEnumerable<T>
{
/// <inheritdoc />
public EnumerableWrapper(object toWrap) : base(toWrap)
{
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return MakeEnumerator<T>();
}
}
/// <summary>
/// Wraps an object which would be an acceptable enumerator in a foreach
/// (due to .NET compile-time duck-typing) into an actual IEnumerator
/// </summary>
#if BUILD_PEANUTBUTTER_INTERNAL
internal
#else
public
#endif
class EnumeratorWrapper<T> : IEnumerator<T>, IEnumerableWrapper
{
/// <inheritdoc />
public bool IsValid { get; private set; }
private PropertyInfo _currentPropInfo;
private MethodInfo _moveNextMethod;
private MethodInfo _resetMethod;
private readonly object _wrapped;
private readonly MethodInfo _getEnumeratorMethod;
private static readonly object[] NO_ARGS = new object[0];
private static BindingFlags PublicInstance = BindingFlags.Public | BindingFlags.Instance;
/// <inheritdoc />
public EnumeratorWrapper(object toWrap)
{
var wrappedType = toWrap.GetType();
var methods = wrappedType.GetMethods(PublicInstance);
_getEnumeratorMethod = methods.FirstOrDefault(
mi => mi.Name == "GetEnumerator"
);
GrabEnumeratorReturnMembers();
ValidateEnumeratorResult();
if (IsValid)
{
_wrapped = _getEnumeratorMethod?.Invoke(toWrap, NO_ARGS);
}
}
private void ValidateEnumeratorResult()
{
IsValid = _currentPropInfo != null &&
_currentPropInfo.CanRead &&
typeof(T).IsAssignableFrom(_currentPropInfo.PropertyType) &&
_moveNextMethod != null;
}
private void GrabEnumeratorReturnMembers()
{
if (_getEnumeratorMethod == null)
{
return;
}
var enumeratorReturnType = _getEnumeratorMethod.ReturnType;
_currentPropInfo = enumeratorReturnType.GetProperty(nameof(Current));
var methods = enumeratorReturnType.GetMethods(PublicInstance);
_moveNextMethod = methods.FirstOrDefault(
mi => mi.Name == nameof(MoveNext) &&
mi.ReturnType == typeof(bool) &&
mi.GetParameters().Length == 0);
_resetMethod = methods.FirstOrDefault(
mi => mi.Name == nameof(Reset) &&
mi.ReturnType == typeof(void) &&
mi.GetParameters().Length == 0);
}
/// <summary>
/// Implements the MoveNext functionality of IEnumerable
/// </summary>
public bool MoveNext()
{
return (bool) _moveNextMethod.Invoke(_wrapped, NO_ARGS);
}
/// <summary>
/// Implements the Reset functionality of IEnumerable
/// </summary>
public void Reset()
{
// Not always required -- optionally implemented
// https://docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerator.reset?view=netframework-4.8
_resetMethod?.Invoke(_wrapped, NO_ARGS);
}
object IEnumerator.Current => Current;
/// <inheritdoc />
public T Current => TryConvert(_currentPropInfo.GetValue(_wrapped));
private T TryConvert(object getValue)
{
// this should always succeed, but in the case where the underlying
// enumerator is misbehaving, we just spit out default(T)
if (getValue is T matched)
{
return matched;
}
return getValue.TryChangeType<T>(out var converted)
? converted
: default(T);
}
/// <inheritdoc />
public void Dispose()
{
// nothing to do
}
}
}
| |
// 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 Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Dsa.Tests
{
public sealed class DSASignVerify_Array : DSASignVerify
{
public override byte[] SignData(DSA dsa, byte[] data, HashAlgorithmName hashAlgorithm) =>
dsa.SignData(data, hashAlgorithm);
public override bool VerifyData(DSA dsa, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) =>
dsa.VerifyData(data, signature, hashAlgorithm);
protected override void UseAfterDispose(DSA dsa, byte[] data, byte[] sig)
{
base.UseAfterDispose(dsa, data, sig);
byte[] hash = new byte[20];
Assert.Throws<ObjectDisposedException>(() => dsa.CreateSignature(hash));
Assert.Throws<ObjectDisposedException>(() => dsa.VerifySignature(hash, sig));
}
[Fact]
public void InvalidStreamArrayArguments_Throws()
{
using (DSA dsa = DSAFactory.Create(1024))
{
AssertExtensions.Throws<ArgumentNullException>("rgbHash", () => dsa.CreateSignature(null));
AssertExtensions.Throws<ArgumentNullException>("data", () => dsa.SignData((byte[])null, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentNullException>("data", () => dsa.SignData(null, 0, 0, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => dsa.SignData(new byte[1], -1, 0, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => dsa.SignData(new byte[1], 2, 0, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => dsa.SignData(new byte[1], 0, -1, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => dsa.SignData(new byte[1], 0, 2, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentNullException>("data", () => dsa.VerifyData((byte[])null, null, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentNullException>("data", () => dsa.VerifyData(null, 0, 0, null, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentNullException>("signature", () => dsa.VerifyData(new byte[1], null, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => dsa.VerifyData(new byte[1], -1, 0, new byte[1], HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => dsa.VerifyData(new byte[1], 2, 0, new byte[1], HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => dsa.VerifyData(new byte[1], 0, -1, new byte[1], HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => dsa.VerifyData(new byte[1], 0, 2, new byte[1], HashAlgorithmName.SHA1));
}
}
}
public sealed class DSASignVerify_Stream : DSASignVerify
{
public override byte[] SignData(DSA dsa, byte[] data, HashAlgorithmName hashAlgorithm) =>
dsa.SignData(new MemoryStream(data), hashAlgorithm);
public override bool VerifyData(DSA dsa, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) =>
dsa.VerifyData(new MemoryStream(data), signature, hashAlgorithm);
[Fact]
public void InvalidArrayArguments_Throws()
{
using (DSA dsa = DSAFactory.Create(1024))
{
AssertExtensions.Throws<ArgumentNullException>("data", () => dsa.SignData((Stream)null, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentNullException>("data", () => dsa.VerifyData((Stream)null, null, HashAlgorithmName.SHA1));
AssertExtensions.Throws<ArgumentNullException>("signature", () => dsa.VerifyData(new MemoryStream(), null, HashAlgorithmName.SHA1));
}
}
}
#if netcoreapp
public sealed class DSASignVerify_Span : DSASignVerify
{
public override byte[] SignData(DSA dsa, byte[] data, HashAlgorithmName hashAlgorithm) =>
TryWithOutputArray(dest => dsa.TrySignData(data, dest, hashAlgorithm, out int bytesWritten) ? (true, bytesWritten) : (false, 0));
public override bool VerifyData(DSA dsa, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) =>
dsa.VerifyData((ReadOnlySpan<byte>)data, (ReadOnlySpan<byte>)signature, hashAlgorithm);
protected override void UseAfterDispose(DSA dsa, byte[] data, byte[] sig)
{
base.UseAfterDispose(dsa, data, sig);
byte[] hash = new byte[20];
Assert.Throws<ObjectDisposedException>(() => dsa.TryCreateSignature(hash, sig, out _));
Assert.Throws<ObjectDisposedException>(() => dsa.VerifySignature(hash.AsSpan(), sig.AsSpan()));
}
private static byte[] TryWithOutputArray(Func<byte[], (bool, int)> func)
{
for (int length = 1; ; length = checked(length * 2))
{
var result = new byte[length];
var (success, bytesWritten) = func(result);
if (success)
{
Array.Resize(ref result, bytesWritten);
return result;
}
}
}
}
#endif
public abstract partial class DSASignVerify
{
public abstract byte[] SignData(DSA dsa, byte[] data, HashAlgorithmName hashAlgorithm);
public abstract bool VerifyData(DSA dsa, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm);
[ConditionalFact(nameof(SupportsKeyGeneration))]
public void InvalidKeySize_DoesNotInvalidateKey()
{
using (DSA dsa = DSAFactory.Create())
{
byte[] signature = SignData(dsa, DSATestData.HelloBytes, HashAlgorithmName.SHA1);
// A 2049-bit key is hard to describe, none of the providers support it.
Assert.ThrowsAny<CryptographicException>(() => dsa.KeySize = 2049);
Assert.True(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA1));
}
}
[ConditionalFact(nameof(SupportsKeyGeneration))]
public void UseAfterDispose_NewKey()
{
UseAfterDispose(false);
}
[Fact]
public void UseAfterDispose_ImportedKey()
{
UseAfterDispose(true);
}
private void UseAfterDispose(bool importKey)
{
DSA key = importKey ? DSAFactory.Create(DSATestData.GetDSA1024Params()) : DSAFactory.Create(512);
byte[] data = { 1 };
byte[] sig;
// Ensure the key is populated, then dispose it.
using (key)
{
sig = SignData(key, data, HashAlgorithmName.SHA1);
}
key.Dispose();
UseAfterDispose(key, data, sig);
Assert.Throws<ObjectDisposedException>(() => key.ImportParameters(DSATestData.GetDSA1024Params()));
// Either set_KeySize or SignData should throw.
Assert.Throws<ObjectDisposedException>(
() =>
{
key.KeySize = 576;
SignData(key, data, HashAlgorithmName.SHA1);
});
}
protected virtual void UseAfterDispose(DSA dsa, byte[] data, byte[] sig)
{
Assert.Throws<ObjectDisposedException>(
() => SignData(dsa, data, HashAlgorithmName.SHA1));
Assert.Throws<ObjectDisposedException>(
() => VerifyData(dsa, data, sig, HashAlgorithmName.SHA1));
}
[ConditionalFact(nameof(SupportsKeyGeneration))]
public void SignAndVerifyDataNew1024()
{
using (DSA dsa = DSAFactory.Create(1024))
{
byte[] signature = SignData(dsa, DSATestData.HelloBytes, new HashAlgorithmName("SHA1"));
bool signatureMatched = VerifyData(dsa, DSATestData.HelloBytes, signature, new HashAlgorithmName("SHA1"));
Assert.True(signatureMatched);
}
}
[Fact]
public void VerifyKnown_512()
{
byte[] signature = (
// r:
"E21F20B0B5E553137F6649DDC58F5E4AB7D4E6DE" +
// s:
"C37534CC7D9630339936C581690E832BD85C6C79").HexToByteArray();
using (DSA dsa = DSAFactory.Create())
{
dsa.ImportParameters(DSATestData.Dsa512Parameters);
Assert.True(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA1));
}
}
[Fact]
public void VerifyKnown_576()
{
byte[] signature = (
// r:
"490AEFA5A4F28B35183BBA3BE2536514AB13A088" +
// s:
"3F883FE96524D4CC596F67B64A3382E794C8D65B").HexToByteArray();
using (DSA dsa = DSAFactory.Create())
{
dsa.ImportParameters(DSATestData.Dsa576Parameters);
Assert.True(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA1));
}
}
[Fact]
public void PublicKey_CannotSign()
{
DSAParameters keyParameters = DSATestData.GetDSA1024Params();
keyParameters.X = null;
using (DSA dsa = DSAFactory.Create())
{
dsa.ImportParameters(keyParameters);
Assert.ThrowsAny<CryptographicException>(
() => SignData(dsa, DSATestData.HelloBytes, HashAlgorithmName.SHA1));
}
}
[Fact]
public void SignAndVerifyDataExplicit1024()
{
SignAndVerify(DSATestData.HelloBytes, "SHA1", DSATestData.GetDSA1024Params(), 40);
}
[ConditionalFact(nameof(SupportsFips186_3))]
public void SignAndVerifyDataExplicit2048()
{
SignAndVerify(DSATestData.HelloBytes, "SHA256", DSATestData.GetDSA2048Params(), 64);
}
[ConditionalFact(nameof(SupportsFips186_3))]
public void VerifyKnown_2048_SHA256()
{
byte[] signature =
{
0x92, 0x06, 0x0B, 0x57, 0xF1, 0x35, 0x20, 0x28,
0xC6, 0x54, 0x4A, 0x0F, 0x08, 0x48, 0x5F, 0x5D,
0x55, 0xA8, 0x42, 0xFB, 0x05, 0xA7, 0x3E, 0x32,
0xCA, 0xC6, 0x91, 0x77, 0x70, 0x0A, 0x68, 0x44,
0x60, 0x63, 0xF7, 0xE7, 0x96, 0x54, 0x8F, 0x4A,
0x6D, 0x47, 0x10, 0xEE, 0x9A, 0x9F, 0xC2, 0xC8,
0xDD, 0x74, 0xAE, 0x1A, 0x68, 0xF3, 0xA9, 0xB8,
0x62, 0x14, 0x50, 0xA3, 0x01, 0x1D, 0x2A, 0x22,
};
using (DSA dsa = DSAFactory.Create())
{
dsa.ImportParameters(DSATestData.GetDSA2048Params());
Assert.True(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA256));
Assert.False(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA384));
Assert.False(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA512));
}
}
[ConditionalFact(nameof(SupportsFips186_3))]
public void VerifyKnown_2048_SHA384()
{
byte[] signature =
{
0x56, 0xBA, 0x70, 0x48, 0x18, 0xBA, 0xE3, 0x43,
0xF0, 0x7F, 0x25, 0xFE, 0xEA, 0xF1, 0xDB, 0x49,
0x37, 0x15, 0xD3, 0xD0, 0x5B, 0x9D, 0x57, 0x19,
0x73, 0x44, 0xDA, 0x70, 0x8D, 0x44, 0x7D, 0xBA,
0x83, 0xDB, 0x8E, 0x8F, 0x39, 0x0F, 0x83, 0xD5,
0x0B, 0x73, 0x81, 0x77, 0x3D, 0x9B, 0x8D, 0xA4,
0xAD, 0x94, 0x3C, 0xAB, 0x7A, 0x6C, 0x81, 0x48,
0x2F, 0xCF, 0x50, 0xE3, 0x34, 0x0B, 0xEC, 0xF0,
};
using (DSA dsa = DSAFactory.Create())
{
dsa.ImportParameters(DSATestData.GetDSA2048Params());
Assert.True(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA384));
Assert.False(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA256));
Assert.False(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA512));
}
}
[ConditionalFact(nameof(SupportsFips186_3))]
public void VerifyKnown_2048_SHA512()
{
byte[] signature =
{
0x6F, 0x44, 0x68, 0x1F, 0x74, 0xF7, 0x90, 0x2F,
0x38, 0x43, 0x9B, 0x00, 0x15, 0xDA, 0xF6, 0x8F,
0x97, 0xB4, 0x4A, 0x52, 0xF7, 0xC1, 0xEC, 0x21,
0xE2, 0x44, 0x48, 0x71, 0x0F, 0xEC, 0x5E, 0xB3,
0xA1, 0xCB, 0xE4, 0x42, 0xC8, 0x1E, 0xCD, 0x3C,
0xA8, 0x15, 0x51, 0xDE, 0x0C, 0xCC, 0xAE, 0x4D,
0xEB, 0x2A, 0xE9, 0x13, 0xBB, 0x7F, 0x3C, 0xFB,
0x69, 0x8A, 0x8E, 0x0F, 0x80, 0x87, 0x2E, 0xA6,
};
using (DSA dsa = DSAFactory.Create())
{
dsa.ImportParameters(DSATestData.GetDSA2048Params());
Assert.True(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA512));
Assert.False(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA256));
Assert.False(VerifyData(dsa, DSATestData.HelloBytes, signature, HashAlgorithmName.SHA384));
}
}
[Fact]
public void VerifyKnownSignature()
{
using (DSA dsa = DSAFactory.Create())
{
byte[] data;
byte[] signature;
DSAParameters dsaParameters;
DSATestData.GetDSA1024_186_2(out dsaParameters, out signature, out data);
dsa.ImportParameters(dsaParameters);
Assert.True(VerifyData(dsa, data, signature, HashAlgorithmName.SHA1));
// Negative case
signature[signature.Length - 1] ^= 0xff;
Assert.False(VerifyData(dsa, data, signature, HashAlgorithmName.SHA1));
}
}
[ConditionalFact(nameof(SupportsFips186_3))]
public void Sign2048WithSha1()
{
byte[] data = { 1, 2, 3, 4 };
using (DSA dsa = DSAFactory.Create())
{
dsa.ImportParameters(DSATestData.GetDSA2048Params());
byte[] signature = SignData(dsa, data, HashAlgorithmName.SHA1);
Assert.True(VerifyData(dsa, data, signature, HashAlgorithmName.SHA1));
}
}
[ConditionalFact(nameof(SupportsFips186_3))]
public void Verify2048WithSha1()
{
byte[] data = { 1, 2, 3, 4 };
byte[] signature = (
"28DC05B452C8FC0E0BFE9DA067D11147D31B1F3C63E5CF95046A812417C64844868D04D3A1D23" +
"13E5DD07DE757B3A836E70A1C85DDC90CB62DE2E44746C760F2").HexToByteArray();
using (DSA dsa = DSAFactory.Create())
{
dsa.ImportParameters(DSATestData.GetDSA2048Params());
Assert.True(VerifyData(dsa, data, signature, HashAlgorithmName.SHA1), "Untampered data verifies");
data[0] ^= 0xFF;
Assert.False(VerifyData(dsa, data, signature, HashAlgorithmName.SHA1), "Tampered data verifies");
data[0] ^= 0xFF;
signature[signature.Length - 1] ^= 0xFF;
Assert.False(VerifyData(dsa, data, signature, HashAlgorithmName.SHA1), "Tampered signature verifies");
}
}
private void SignAndVerify(byte[] data, string hashAlgorithmName, DSAParameters dsaParameters, int expectedSignatureLength)
{
using (DSA dsa = DSAFactory.Create())
{
dsa.ImportParameters(dsaParameters);
byte[] signature = SignData(dsa, data, new HashAlgorithmName(hashAlgorithmName));
Assert.Equal(expectedSignatureLength, signature.Length);
bool signatureMatched = VerifyData(dsa, data, signature, new HashAlgorithmName(hashAlgorithmName));
Assert.True(signatureMatched);
}
}
internal static bool SupportsFips186_3
{
get
{
return DSAFactory.SupportsFips186_3;
}
}
public static bool SupportsKeyGeneration => DSAFactory.SupportsKeyGeneration;
}
}
| |
// 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.Linq;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class SerialStream_BeginRead : PortsTest
{
// The number of random bytes to receive for read method testing
private const int numRndBytesToRead = 16;
// The number of random bytes to receive for large input buffer testing
private const int largeNumRndBytesToRead = 2048;
// When we test Read and do not care about actually reading 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 defaultByteArraySize = 1;
private const int defaultByteOffset = 0;
private const int defaultByteCount = 1;
// The maximum buffer size when a exception occurs
private const int maxBufferSizeForException = 255;
// The maximum buffer size when a exception is not expected
private const int maxBufferSize = 8;
// Maximum time to wait for processing the read command to complete
private const int MAX_WAIT_READ_COMPLETE = 1000;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void Buffer_Null()
{
VerifyReadException(null, 0, 1, typeof(ArgumentNullException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEG1()
{
VerifyReadException(new byte[defaultByteArraySize], -1, defaultByteCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEGRND()
{
var rndGen = new Random(-55);
VerifyReadException(new byte[defaultByteArraySize], rndGen.Next(int.MinValue, 0), defaultByteCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_MinInt()
{
VerifyReadException(new byte[defaultByteArraySize], int.MinValue, defaultByteCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEG1()
{
VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, -1, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEGRND()
{
var rndGen = new Random(-55);
VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_MinInt()
{
VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, int.MinValue, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OffsetCount_EQ_Length_Plus_1()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(0, bufferLength);
int count = bufferLength + 1 - offset;
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OffsetCount_GT_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(0, bufferLength);
int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_GT_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(bufferLength, int.MaxValue);
int count = defaultByteCount;
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_GT_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = defaultByteOffset;
int count = rndGen.Next(bufferLength + 1, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasNullModem))]
public void OffsetCount_EQ_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = rndGen.Next(0, bufferLength - 1);
int count = bufferLength - offset;
VerifyRead(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, maxBufferSize);
int offset = bufferLength - 1;
var count = 1;
VerifyRead(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasNullModem))]
public void Count_EQ_Length()
{
var rndGen = new Random(-55);
int bufferLength = rndGen.Next(1, maxBufferSize);
var offset = 0;
int count = bufferLength;
VerifyRead(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasNullModem))]
public void LargeInputBuffer()
{
int bufferLength = largeNumRndBytesToRead;
var offset = 0;
int count = bufferLength;
VerifyRead(new byte[bufferLength], offset, count, largeNumRndBytesToRead);
}
[ConditionalFact(nameof(HasNullModem))]
public void Callback()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var callbackHandler = new CallbackHandler();
int elapsedTime;
Debug.WriteLine("Verifying BeginRead with a callback specified");
com1.Open();
com2.Open();
IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(new byte[numRndBytesToRead], 0, numRndBytesToRead,
callbackHandler.Callback, null);
callbackHandler.BeginReadAsyncResult = readAsyncResult;
Assert.Equal(null, readAsyncResult.AsyncState);
Assert.False(readAsyncResult.CompletedSynchronously, "Should not have completed sync (read)");
Assert.False(readAsyncResult.IsCompleted, "Should not have completed yet");
com2.Write(new byte[numRndBytesToRead], 0, numRndBytesToRead);
// callbackHandler.ReadAsyncResult guarantees that the callback has been calledhowever it does not gauarentee that
// the code calling the callback has finished it's processing
IAsyncResult callbackReadAsyncResult = callbackHandler.ReadAysncResult;
// No we have to wait for the callbackHandler to complete
elapsedTime = 0;
while (!callbackReadAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_READ_COMPLETE)
{
Thread.Sleep(10);
elapsedTime += 10;
}
Assert.Equal(null, callbackReadAsyncResult.AsyncState);
Assert.False(callbackReadAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)");
Assert.True(callbackReadAsyncResult.IsCompleted, "Should have completed (cback)");
Assert.Equal(null, readAsyncResult.AsyncState);
Assert.False(readAsyncResult.CompletedSynchronously, "Should not have completed sync (read)");
Assert.True(readAsyncResult.IsCompleted, "Should have completed (read)");
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Callback_EndReadonCallback()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var callbackHandler = new CallbackHandler(com1);
int elapsedTime;
Debug.WriteLine("Verifying BeginRead with a callback that calls EndRead");
com1.Open();
com2.Open();
IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(new byte[numRndBytesToRead], 0, numRndBytesToRead,
callbackHandler.Callback, null);
callbackHandler.BeginReadAsyncResult = readAsyncResult;
Assert.Equal(null, readAsyncResult.AsyncState);
Assert.False(readAsyncResult.CompletedSynchronously);
Assert.False(readAsyncResult.IsCompleted);
com2.Write(new byte[numRndBytesToRead], 0, numRndBytesToRead);
// callbackHandler.ReadAsyncResult guarantees that the callback has been calledhowever it does not gauarentee that
// the code calling the callback has finished it's processing
IAsyncResult callbackReadAsyncResult = callbackHandler.ReadAysncResult;
// No we have to wait for the callbackHandler to complete
elapsedTime = 0;
while (!callbackReadAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_READ_COMPLETE)
{
Thread.Sleep(10);
elapsedTime += 10;
}
Assert.Equal(null, callbackReadAsyncResult.AsyncState);
Assert.False(callbackReadAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)");
Assert.True(callbackReadAsyncResult.IsCompleted, "Should have completed (cback)");
Assert.Equal(null, readAsyncResult.AsyncState);
Assert.False(readAsyncResult.CompletedSynchronously, "Should not have completed sync (read)");
Assert.True(readAsyncResult.IsCompleted, "Should have completed (read)");
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Callback_State()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var callbackHandler = new CallbackHandler();
int elapsedTime;
Debug.WriteLine("Verifying BeginRead with a callback and state specified");
com1.Open();
com2.Open();
IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(new byte[numRndBytesToRead], 0, numRndBytesToRead,
callbackHandler.Callback, this);
callbackHandler.BeginReadAsyncResult = readAsyncResult;
Assert.Equal(this, readAsyncResult.AsyncState);
Assert.False(readAsyncResult.CompletedSynchronously);
Assert.False(readAsyncResult.IsCompleted);
com2.Write(new byte[numRndBytesToRead], 0, numRndBytesToRead);
// callbackHandler.ReadAsyncResult guarantees that the callback has been calledhowever it does not gauarentee that
// the code calling the callback has finished it's processing
IAsyncResult callbackReadAsyncResult = callbackHandler.ReadAysncResult;
// No we have to wait for the callbackHandler to complete
elapsedTime = 0;
while (!callbackReadAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_READ_COMPLETE)
{
Thread.Sleep(10);
elapsedTime += 10;
}
Assert.Equal(this, callbackReadAsyncResult.AsyncState);
Assert.False(callbackReadAsyncResult.CompletedSynchronously);
Assert.True(callbackReadAsyncResult.IsCompleted);
Assert.Equal(this, readAsyncResult.AsyncState);
Assert.False(readAsyncResult.CompletedSynchronously);
Assert.True(readAsyncResult.IsCompleted);
}
}
#endregion
#region Verification for Test Cases
private void VerifyReadException(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 read method throws {0} buffer.Lenght={1}, offset={2}, count={3}",
expectedException, bufferLength, offset, count);
com.Open();
Assert.Throws(expectedException, () => com.BaseStream.BeginRead(buffer, offset, count, null, null));
}
}
private void VerifyRead(byte[] buffer, int offset, int count)
{
VerifyRead(buffer, offset, count, numRndBytesToRead);
}
private void VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
var bytesToWrite = new byte[numberOfBytesToRead];
// Generate random bytes
for (var i = 0; i < bytesToWrite.Length; i++)
{
var randByte = (byte)rndGen.Next(0, 256);
bytesToWrite[i] = randByte;
}
// Generate some random bytes in the buffer
rndGen.NextBytes(buffer);
Debug.WriteLine("Verifying read method buffer.Lenght={0}, offset={1}, count={2} with {3} random chars", buffer.Length, offset, count, bytesToWrite.Length);
com1.ReadTimeout = 500;
com1.Open();
com2.Open();
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, buffer, offset, count);
}
}
private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count)
{
var buffer = new byte[bytesToWrite.Length];
int totalBytesRead;
int bytesToRead;
var oldRcvBuffer = (byte[])rcvBuffer.Clone();
var callbackHandler = new CallbackHandler();
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 500;
Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250);
totalBytesRead = 0;
bytesToRead = com1.BytesToRead;
do
{
IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(rcvBuffer, offset, count,
callbackHandler.Callback, this);
readAsyncResult.AsyncWaitHandle.WaitOne();
callbackHandler.BeginReadAsyncResult = readAsyncResult;
int bytesRead = com1.BaseStream.EndRead(readAsyncResult);
IAsyncResult asyncResult = callbackHandler.ReadAysncResult;
Assert.Equal(this, asyncResult.AsyncState);
Assert.False(asyncResult.CompletedSynchronously);
Assert.True(asyncResult.IsCompleted);
Assert.Equal(this, readAsyncResult.AsyncState);
Assert.False(readAsyncResult.CompletedSynchronously);
Assert.True(readAsyncResult.IsCompleted);
if ((bytesToRead > bytesRead && count != bytesRead) ||
(bytesToRead <= bytesRead && bytesRead != bytesToRead))
{
// If we have not read all of the characters that we should have
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (bytesToWrite.Length < totalBytesRead + bytesRead)
{
// If we have read in more characters then we expect
Fail("ERROR!!!: We have received more characters then were sent");
}
VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, bytesRead);
Array.Copy(rcvBuffer, offset, buffer, totalBytesRead, bytesRead);
totalBytesRead += bytesRead;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead);
}
oldRcvBuffer = (byte[])rcvBuffer.Clone();
bytesToRead = com1.BytesToRead;
} while (0 != com1.BytesToRead); // While there are more bytes to read
// Compare the bytes that were written with the ones we read
Assert.Equal(bytesToWrite, buffer.Take(bytesToWrite.Length).ToArray());
}
private void VerifyBuffer(byte[] actualBuffer, byte[] expectedBuffer, int offset, int count)
{
// Verify all character before the offset
for (var i = 0; i < offset; i++)
{
if (actualBuffer[i] != expectedBuffer[i])
{
Fail("ERROR!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]);
}
}
// Verify all character after the offset + count
for (int i = offset + count; i < actualBuffer.Length; i++)
{
if (actualBuffer[i] != expectedBuffer[i])
{
Fail("ERROR!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]);
}
}
}
private class CallbackHandler
{
private IAsyncResult _readAysncResult;
private IAsyncResult _beginReadAsyncResult;
private readonly SerialPort _com;
public CallbackHandler() : this(null) { }
public CallbackHandler(SerialPort com)
{
_com = com;
}
public void Callback(IAsyncResult readAysncResult)
{
lock (this)
{
_readAysncResult = readAysncResult;
Assert.True(readAysncResult.IsCompleted, "IAsyncResult passed into callback is not completed");
while (null == _beginReadAsyncResult)
{
Monitor.Wait(this);
}
if (null != _beginReadAsyncResult && !_beginReadAsyncResult.IsCompleted)
{
Fail("Err_7907azpu Expected IAsyncResult returned from begin read to not be completed");
}
if (null != _com)
{
_com.BaseStream.EndRead(_beginReadAsyncResult);
if (!_beginReadAsyncResult.IsCompleted)
{
Fail("Err_6498afead Expected IAsyncResult returned from begin read to not be completed");
}
if (!readAysncResult.IsCompleted)
{
Fail("Err_1398ehpo Expected IAsyncResult passed into callback to not be completed");
}
}
Monitor.Pulse(this);
}
}
public IAsyncResult ReadAysncResult
{
get
{
lock (this)
{
while (null == _readAysncResult)
{
Monitor.Wait(this);
}
return _readAysncResult;
}
}
}
public IAsyncResult BeginReadAsyncResult
{
get
{
return _beginReadAsyncResult;
}
set
{
lock (this)
{
_beginReadAsyncResult = value;
Monitor.Pulse(this);
}
}
}
}
#endregion
}
}
| |
//
// HttpRequestMessageBuilder.cs
//
// Author:
// MiNG <[email protected]>
//
// Copyright (c) 2018 Alibaba Cloud
//
// 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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Aliyun.Api.LogService.Infrastructure.Authentication;
using Aliyun.Api.LogService.Utils;
using Google.Protobuf;
using Ionic.Zlib;
using LZ4;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace Aliyun.Api.LogService.Infrastructure.Protocol.Http
{
/// <summary>
/// Builder for constructing the <see cref="HttpRequestMessage"/>.
/// </summary>
/// <inheritdoc />
public class HttpRequestMessageBuilder : IRequestBuilder<HttpRequestMessage>
{
private static readonly Byte[] EmptyByteArray = new Byte[0];
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};
private readonly HttpRequestMessage httpRequestMessage;
private readonly Encoding encoding;
private readonly String path;
private readonly IDictionary<String, String> query;
/// <summary>
/// The authentication credential.
/// </summary>
private Credential credential;
/// <summary>
/// The real content to transfer.
/// </summary>
private Object content;
/// <summary>
/// The Content-MD5 header in HEX format.
/// </summary>
private String contentMd5Hex;
/// <summary>
/// Gets the serialized content.
/// </summary>
private Byte[] SerializedContent =>
this.content == null
? null
: this.content as Byte[]
?? throw new InvalidOperationException("Content must serialized before this operation.");
/// <summary>
/// Proceed the actions after content prepared (i.e., all transforms (e.g., serialize, compress, encrypt, encode) of <see cref="content"/> are applied).
/// </summary>
private Action contentHandler;
/// <summary>
/// The signature type.
/// </summary>
private SignatureType signatureType;
public HttpRequestMessageBuilder(HttpMethod method, String uri)
{
this.httpRequestMessage = new HttpRequestMessage(method, uri);
this.encoding = Encoding.UTF8;
ParseUri(uri, out this.path, out this.query);
this.FillDefaultHeaders();
}
private static void ParseUri(String uri, out String path, out IDictionary<String, String> query)
{
var absUri = new Uri(new Uri("http://fa.ke"), uri);
path = absUri.AbsolutePath;
query = absUri.ParseQueryString()
.ToEnumerable()
.ToDictionary(kv => kv.Key, kv => kv.Value); // NOTE: Restricted mode, key cannot be duplicated.
}
private void FillDefaultHeaders()
{
this.httpRequestMessage.Headers.Date = DateTimeOffset.Now;
this.httpRequestMessage.Headers.UserAgent.Add(new ProductInfoHeaderValue("log-dotnetcore-sdk", Constants.AssemblyVersion));
this.httpRequestMessage.Headers.Add(LogHeaders.ApiVersion, "0.6.0");
}
#region Query
public IRequestBuilder<HttpRequestMessage> Query(String key, String value)
{
this.query.Add(key, value);
return this;
}
public IRequestBuilder<HttpRequestMessage> Query(Object queryModel)
{
foreach (var kv in JObject.FromObject(queryModel, JsonSerializer.CreateDefault(JsonSerializerSettings)))
{
this.query.Add(kv.Key, kv.Value.Value<String>());
}
return this;
}
#endregion
#region Header
/// <summary>
/// Set headers of <see cref="T:System.Net.Http.Headers.HttpRequestHeaders" />
/// </summary>
/// <inheritdoc />
public IRequestBuilder<HttpRequestMessage> Header(String key, String value)
{
this.httpRequestMessage.Headers.Add(key, value);
return this;
}
private void ContentHeader(Action<HttpContentHeaders> option)
{
if (this.httpRequestMessage.Content == null)
{
this.contentHandler += () => option(this.httpRequestMessage.Content.Headers);
} else
{
option(this.httpRequestMessage.Content.Headers);
}
}
private void SetBodyRawSize(Int32 size)
=> this.httpRequestMessage.Headers.Add(LogHeaders.BodyRawSize, size.ToString());
private void SetCompressType(String compressType)
=> this.httpRequestMessage.Headers.Add(LogHeaders.CompressType, compressType);
private void SetSignatureMethod(String signatureMethod)
=> this.httpRequestMessage.Headers.Add(LogHeaders.SignatureMethod, signatureMethod);
#endregion
#region Content
public IRequestBuilder<HttpRequestMessage> Content(Byte[] content)
=> this.Content((Object) content);
public IRequestBuilder<HttpRequestMessage> Content(Object content)
{
this.content = content;
if (content is Byte[] data)
{
this.SetBodyRawSize(data.Length);
}
return this;
}
#endregion
#region Serialize
public IRequestBuilder<HttpRequestMessage> Serialize(SerializeType serializeType)
{
switch (this.content)
{
case null:
throw new InvalidOperationException("Nothing to serialize.");
case Byte[] _:
throw new InvalidOperationException("Content has already been serialized.");
}
switch (serializeType)
{
case SerializeType.Json:
{
this.ContentHeader(x => x.ContentType = new MediaTypeHeaderValue("application/json"));
var json = JsonConvert.SerializeObject(this.content, JsonSerializerSettings);
this.Content(this.encoding.GetBytes(json));
break;
}
case SerializeType.Protobuf:
{
if (!(this.content is IMessage protoMessage))
{
throw new ArgumentException("Serialization of ProtoBuf requires IMessage.");
}
this.ContentHeader(x => x.ContentType = new MediaTypeHeaderValue("application/x-protobuf"));
this.Content(protoMessage.ToByteArray());
break;
}
default:
{
throw new ArgumentOutOfRangeException(nameof(serializeType), serializeType, null);
}
}
return this;
}
#endregion Serialize
#region Compress
public IRequestBuilder<HttpRequestMessage> Compress(CompressType compressType)
{
if (this.SerializedContent == null)
{
throw new InvalidOperationException("Nothing to compress.");
}
switch (compressType)
{
case CompressType.None:
{
break;
}
case CompressType.Lz4:
{
this.SetCompressType("lz4");
this.content = LZ4Codec.Encode(this.SerializedContent, 0, this.SerializedContent.Length);
break;
}
case CompressType.Deflate:
{
this.SetCompressType("deflate");
this.content = ZlibStream.CompressBuffer(this.SerializedContent);
break;
}
default:
{
throw new ArgumentOutOfRangeException(nameof(compressType), compressType, null);
}
}
return this;
}
#endregion Compress
#region Authentication
public IRequestBuilder<HttpRequestMessage> Authenticate(Credential credential)
{
Ensure.NotNull(credential, nameof(credential));
Ensure.NotEmpty(credential.AccessKeyId, nameof(credential.AccessKeyId));
Ensure.NotEmpty(credential.AccessKey, nameof(credential.AccessKey));
this.credential = credential;
return this;
}
#endregion
#region Sign
public IRequestBuilder<HttpRequestMessage> Sign(SignatureType signatureType)
{
this.signatureType = signatureType;
return this;
}
private Byte[] ComputeSignature()
{
switch (this.signatureType)
{
case SignatureType.HmacSha1:
{
using (var hasher = new HMACSHA1(this.encoding.GetBytes(this.credential.AccessKey)))
{
this.SetSignatureMethod("hmac-sha1"); // This header must be set before generating sign source.
var signSource = this.GenerateSignSource();
var sign = hasher.ComputeHash(this.encoding.GetBytes(signSource));
return sign;
}
}
default:
{
throw new ArgumentOutOfRangeException(nameof(this.signatureType), this.signatureType, "Currently only support [hmac-sha1] signature.");
}
}
}
private String GenerateSignSource()
{
var verb = this.httpRequestMessage.Method.Method;
var contentMd5 = this.contentMd5Hex;
var contentType = this.httpRequestMessage.Content?.Headers.ContentType.MediaType;
var date = this.httpRequestMessage.Headers.Date?.ToString("r"); /* RFC 822 format */
var logHeaders = String.Join("\n", this.httpRequestMessage.Headers
.Concat(this.httpRequestMessage.Content?.Headers ?? Enumerable.Empty<KeyValuePair<String, IEnumerable<String>>>())
.Where(x => x.Key.StartsWith("x-log") || x.Key.StartsWith("x-acs"))
.Select(x => new KeyValuePair<String, String>(x.Key.ToLower(), x.Value.SingleOrDefault() /* Fault tolerance */))
.Where(x => x.Value.IsNotEmpty()) // Remove empty header
.OrderBy(x => x.Key)
.Select(x => $"{x.Key}:{x.Value}"));
var resource = this.httpRequestMessage.RequestUri.OriginalString;
String signSource;
if (this.query.IsEmpty())
{
signSource = String.Join("\n", verb, contentMd5 ?? String.Empty, contentType ?? String.Empty, date, logHeaders, resource);
} else
{
signSource = String.Join("\n", verb, contentMd5 ?? String.Empty, contentType ?? String.Empty, date, logHeaders, resource) + "?" +
String.Join("&", this.query
.OrderBy(x => x.Key)
.Select(x => $"{x.Key}={x.Value}"));
}
return signSource;
}
private Byte[] CalculateContentMd5()
{
using (var hasher = MD5.Create())
{
return hasher.ComputeHash(this.SerializedContent);
}
}
#endregion Signature
public HttpRequestMessage Build()
{
// Validate
Ensure.NotNull(this.credential, nameof(this.credential));
Ensure.NotEmpty(this.credential.AccessKeyId, nameof(this.credential.AccessKeyId));
Ensure.NotEmpty(this.credential.AccessKey, nameof(this.credential.AccessKey));
// Process sts-token.
var hasSecurityToken = this.httpRequestMessage.Headers.TryGetValues(LogHeaders.SecurityToken, out var securityTokens)
&& securityTokens.FirstOrDefault().IsNotEmpty();
if (!hasSecurityToken && this.credential.StsToken.IsNotEmpty())
{
this.httpRequestMessage.Headers.Add(LogHeaders.SecurityToken, this.credential.StsToken);
}
// NOTE: If x-log-bodyrawsize is empty, fill it with "0". Otherwise, some method call will be corrupted.
if (!this.httpRequestMessage.Headers.Contains(LogHeaders.BodyRawSize))
{
this.SetBodyRawSize(0);
}
// Build content if necessary
if (this.SerializedContent.IsNotEmpty())
{
this.httpRequestMessage.Content = new ByteArrayContent(this.SerializedContent);
this.contentHandler?.Invoke();
// Prepare header
this.ContentHeader(x =>
{
// Compute actual length
x.ContentLength = this.SerializedContent.Length;
// Compute actual MD5
this.contentMd5Hex = BitConverter.ToString(this.CalculateContentMd5()).Replace("-", String.Empty);
x.Add("Content-MD5", this.contentMd5Hex); // Non-standard header
});
} else if (this.httpRequestMessage.Method == HttpMethod.Post || this.httpRequestMessage.Method == HttpMethod.Put)
{
// When content is empty as well as method is `POST` or `PUT`, generate an empty content and corresponding headers.
this.httpRequestMessage.Content = new ByteArrayContent(EmptyByteArray);
// Don't invoke `contentHandler` here!
/*
* NOTE:
* Here is a annoying hack, the log service service cannot accept empty `Content-Type`
* header when POST or PUT methods. So, we have to force set some header value.
*/
this.ContentHeader(x =>
{
x.ContentType = new MediaTypeHeaderValue("application/json");
// For some reason, I think it is better to set `Content-Type` to `0` to prevent
// some unexpected behavior on server side.
x.ContentLength = 0;
});
}
// Do signature
var signature = Convert.ToBase64String(this.ComputeSignature());
this.httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("LOG", $"{this.credential.AccessKeyId}:{signature}");
// Rebuild the RequestUri
var queryString = String.Join("&", this.query
.OrderBy(x => x.Key)
.Select(x => $"{encodeUrl(x.Key)}={encodeUrl(x.Value)}"));
var pathAndQuery = queryString.IsNotEmpty() ? $"{this.path}?{queryString}" : this.path;
this.httpRequestMessage.RequestUri = new Uri(pathAndQuery, UriKind.Relative);
return this.httpRequestMessage;
}
private String encodeUrl(String value)
{
if (value == null)
{
return "";
}
string encoded = HttpUtility.UrlEncode(value, this.encoding);
return encoded.Replace("+", "%20").Replace("*", "%2A").Replace("~", "%7E").Replace("/", "%2F");
}
}
}
| |
// 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.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.EventHub
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for EventHubsOperations.
/// </summary>
public static partial class EventHubsOperationsExtensions
{
/// <summary>
/// Enumerates the Event Hubs in a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
public static IPage<EventHubResource> ListAll(this IEventHubsOperations operations, string resourceGroupName, string namespaceName)
{
return Task.Factory.StartNew(s => ((IEventHubsOperations)s).ListAllAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Enumerates the Event Hubs in a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<EventHubResource>> ListAllAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates/Updates a new Event Hub as a nested resource within a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The EventHub name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a EventHub Resource.
/// </param>
public static EventHubResource CreateOrUpdate(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, EventHubCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew(s => ((IEventHubsOperations)s).CreateOrUpdateAsync(resourceGroupName, namespaceName, eventHubName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates/Updates a new Event Hub as a nested resource within a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The EventHub name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a EventHub Resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EventHubResource> CreateOrUpdateAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, EventHubCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an Event hub from the specified namespace and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The EventHub name.
/// </param>
public static void Delete(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName)
{
Task.Factory.StartNew(s => ((IEventHubsOperations)s).DeleteAsync(resourceGroupName, namespaceName, eventHubName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an Event hub from the specified namespace and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The EventHub name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns an Event Hub description for the specified Event Hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The EventHub name.
/// </param>
public static EventHubResource Get(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName)
{
return Task.Factory.StartNew(s => ((IEventHubsOperations)s).GetAsync(resourceGroupName, namespaceName, eventHubName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns an Event Hub description for the specified Event Hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The EventHub name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EventHubResource> GetAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Authorization rules for a EventHub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The NameSpace name
/// </param>
/// <param name='eventHubName'>
/// The EventHub name.
/// </param>
public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName)
{
return Task.Factory.StartNew(s => ((IEventHubsOperations)s).ListAuthorizationRulesAsync(resourceGroupName, namespaceName, eventHubName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Authorization rules for a EventHub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The NameSpace name
/// </param>
/// <param name='eventHubName'>
/// The EventHub name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates an authorization rule for the specified Event Hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// Aauthorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew(s => ((IEventHubsOperations)s).CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates an authorization rule for the specified Event Hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// Aauthorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Authorization rule for a EventHub by name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization rule name.
/// </param>
public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName)
{
return Task.Factory.StartNew(s => ((IEventHubsOperations)s).GetAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Authorization rule for a EventHub by name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization rule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a EventHub authorization rule
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The Eventhub name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </param>
public static void DeleteAuthorizationRule(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName)
{
Task.Factory.StartNew(s => ((IEventHubsOperations)s).DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a EventHub authorization rule
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The Eventhub name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAuthorizationRuleAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns the ACS and SAS connection strings for the Event Hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The event hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the namespace for the specified authorizationRule.
/// </param>
public static ResourceListKeys ListKeys(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName)
{
return Task.Factory.StartNew(s => ((IEventHubsOperations)s).ListKeysAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the ACS and SAS connection strings for the Event Hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The event hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the namespace for the specified authorizationRule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceListKeys> ListKeysAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the ACS and SAS connection strings for the Event Hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The event hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the EventHub for the specified authorizationRule.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate Auth Rule.
/// </param>
public static ResourceListKeys RegenerateKeys(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, RegenerateKeysParameters parameters)
{
return Task.Factory.StartNew(s => ((IEventHubsOperations)s).RegenerateKeysAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the ACS and SAS connection strings for the Event Hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='eventHubName'>
/// The event hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the EventHub for the specified authorizationRule.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate Auth Rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceListKeys> RegenerateKeysAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, RegenerateKeysParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Enumerates the Event Hubs in a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<EventHubResource> ListAllNext(this IEventHubsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IEventHubsOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Enumerates the Event Hubs in a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<EventHubResource>> ListAllNextAsync(this IEventHubsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Authorization rules for a EventHub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this IEventHubsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IEventHubsOperations)s).ListAuthorizationRulesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Authorization rules for a EventHub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this IEventHubsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using XnaCards;
namespace ProgrammingAssignment6
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
// keep track of game state and current winner
static GameState gameState = GameState.Play;
Player currentWinner = Player.None;
// hands and battle piles for the players
WarHand player1Hand;
WarBattlePile player1BattlePile;
WarHand player2Hand;
WarBattlePile player2BattlePile;
// winner messages for players
WinnerMessage player1Message;
WinnerMessage player2Message;
// menu buttons
MenuButton flipButton;
MenuButton collectWinningsButton;
MenuButton quitButton;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
// make mouse visible and set resolution
graphics.PreferredBackBufferWidth = WINDOW_WIDTH;
graphics.PreferredBackBufferHeight = WINDOW_HEIGHT;
IsMouseVisible = true;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// create the deck object and shuffle
Deck deck = new Deck(Content, 0, 0);
deck.Shuffle();
// create the player hands and fully deal the deck into the hands
player1Hand = new WarHand(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 6);
player2Hand = new WarHand(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight * 5 / 6);
while (!deck.Empty)
{
player1Hand.AddCard(deck.TakeTopCard());
player2Hand.AddCard(deck.TakeTopCard());
}
// create the player battle piles
player1BattlePile = new WarBattlePile(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 3);
player2BattlePile = new WarBattlePile(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight * 2 / 3);
// create the player winner messages
player1Message = new WinnerMessage(Content, graphics.PreferredBackBufferWidth * 3 / 4,
graphics.PreferredBackBufferHeight / 6);
player2Message = new WinnerMessage(Content, graphics.PreferredBackBufferWidth * 3 / 4,
graphics.PreferredBackBufferHeight * 5 / 6);
// create the menu buttons
flipButton = new MenuButton(Content, "flipbutton", graphics.PreferredBackBufferWidth / 5,
graphics.PreferredBackBufferHeight / 4, GameState.Flip);
collectWinningsButton = new MenuButton(Content, "collectwinningsbutton", graphics.PreferredBackBufferWidth / 5,
graphics.PreferredBackBufferHeight / 2, GameState.Play);
collectWinningsButton.Visible = false;
quitButton = new MenuButton(Content, "quitbutton", graphics.PreferredBackBufferWidth / 5,
graphics.PreferredBackBufferHeight / 4 * 3, GameState.Quit);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// update the menu buttons
MouseState mouse = Mouse.GetState();
flipButton.Update(mouse);
collectWinningsButton.Update(mouse);
quitButton.Update(mouse);
// update based on game state
if (gameState == GameState.Flip)
{
// flip cards into battle piles
Card player1Card = player1Hand.TakeTopCard();
player1Card.FlipOver();
player1BattlePile.AddCard(player1Card);
Card player2Card = player2Hand.TakeTopCard();
player2Card.FlipOver();
player2BattlePile.AddCard(player2Card);
// figure out winner and show the message
if (player1Card.WarValue > player2Card.WarValue)
{
player1Message.Visible = true;
currentWinner = Player.Player1;
}
else if (player2Card.WarValue > player1Card.WarValue)
{
player2Message.Visible = true;
currentWinner = Player.Player2;
}
else
{
currentWinner = Player.None;
}
// adjust button visibility
flipButton.Visible = false;
collectWinningsButton.Visible = true;
// wait for players to collect winnings
gameState = GameState.CollectWinnings;
}
else if (gameState == GameState.Play)
{
// distribute battle piles into appropriate hands and hide message
if (currentWinner == Player.Player1)
{
player1Hand.AddCards(player1BattlePile);
player1Hand.AddCards(player2BattlePile);
player1Message.Visible = false;
}
else if (currentWinner == Player.Player2)
{
player2Hand.AddCards(player1BattlePile);
player2Hand.AddCards(player2BattlePile);
player2Message.Visible = false;
}
else
{
player1Hand.AddCards(player1BattlePile);
player2Hand.AddCards(player2BattlePile);
}
currentWinner = Player.None;
// set button visibility
flipButton.Visible = true;
collectWinningsButton.Visible = false;
// check for game over
if (player1Hand.Empty)
{
flipButton.Visible = false;
player2Message.Visible = true;
gameState = GameState.GameOver;
}
else if (player2Hand.Empty)
{
player2Message.Visible = true;
flipButton.Visible = false;
gameState = GameState.GameOver;
}
}
else if (gameState == GameState.Quit)
{
Exit();
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Goldenrod);
spriteBatch.Begin();
// draw the game objects
player1Hand.Draw(spriteBatch);
player1BattlePile.Draw(spriteBatch);
player2Hand.Draw(spriteBatch);
player2BattlePile.Draw(spriteBatch);
// draw the winner messages
player1Message.Draw(spriteBatch);
player2Message.Draw(spriteBatch);
// draw the menu buttons
flipButton.Draw(spriteBatch);
collectWinningsButton.Draw(spriteBatch);
quitButton.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
/// <summary>
/// Changes the state of the game
/// </summary>
/// <param name="newState">the new game state</param>
public static void ChangeState(GameState newState)
{
gameState = newState;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic{
/// <summary>
/// Strongly-typed collection for the VwAspnetWebPartStatePath class.
/// </summary>
[Serializable]
public partial class VwAspnetWebPartStatePathCollection : ReadOnlyList<VwAspnetWebPartStatePath, VwAspnetWebPartStatePathCollection>
{
public VwAspnetWebPartStatePathCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vw_aspnet_WebPartState_Paths view.
/// </summary>
[Serializable]
public partial class VwAspnetWebPartStatePath : ReadOnlyRecord<VwAspnetWebPartStatePath>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("vw_aspnet_WebPartState_Paths", TableType.View, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarApplicationId = new TableSchema.TableColumn(schema);
colvarApplicationId.ColumnName = "ApplicationId";
colvarApplicationId.DataType = DbType.Guid;
colvarApplicationId.MaxLength = 0;
colvarApplicationId.AutoIncrement = false;
colvarApplicationId.IsNullable = false;
colvarApplicationId.IsPrimaryKey = false;
colvarApplicationId.IsForeignKey = false;
colvarApplicationId.IsReadOnly = false;
schema.Columns.Add(colvarApplicationId);
TableSchema.TableColumn colvarPathId = new TableSchema.TableColumn(schema);
colvarPathId.ColumnName = "PathId";
colvarPathId.DataType = DbType.Guid;
colvarPathId.MaxLength = 0;
colvarPathId.AutoIncrement = false;
colvarPathId.IsNullable = false;
colvarPathId.IsPrimaryKey = false;
colvarPathId.IsForeignKey = false;
colvarPathId.IsReadOnly = false;
schema.Columns.Add(colvarPathId);
TableSchema.TableColumn colvarPath = new TableSchema.TableColumn(schema);
colvarPath.ColumnName = "Path";
colvarPath.DataType = DbType.String;
colvarPath.MaxLength = 256;
colvarPath.AutoIncrement = false;
colvarPath.IsNullable = false;
colvarPath.IsPrimaryKey = false;
colvarPath.IsForeignKey = false;
colvarPath.IsReadOnly = false;
schema.Columns.Add(colvarPath);
TableSchema.TableColumn colvarLoweredPath = new TableSchema.TableColumn(schema);
colvarLoweredPath.ColumnName = "LoweredPath";
colvarLoweredPath.DataType = DbType.String;
colvarLoweredPath.MaxLength = 256;
colvarLoweredPath.AutoIncrement = false;
colvarLoweredPath.IsNullable = false;
colvarLoweredPath.IsPrimaryKey = false;
colvarLoweredPath.IsForeignKey = false;
colvarLoweredPath.IsReadOnly = false;
schema.Columns.Add(colvarLoweredPath);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("vw_aspnet_WebPartState_Paths",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VwAspnetWebPartStatePath()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VwAspnetWebPartStatePath(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VwAspnetWebPartStatePath(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VwAspnetWebPartStatePath(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("ApplicationId")]
[Bindable(true)]
public Guid ApplicationId
{
get
{
return GetColumnValue<Guid>("ApplicationId");
}
set
{
SetColumnValue("ApplicationId", value);
}
}
[XmlAttribute("PathId")]
[Bindable(true)]
public Guid PathId
{
get
{
return GetColumnValue<Guid>("PathId");
}
set
{
SetColumnValue("PathId", value);
}
}
[XmlAttribute("Path")]
[Bindable(true)]
public string Path
{
get
{
return GetColumnValue<string>("Path");
}
set
{
SetColumnValue("Path", value);
}
}
[XmlAttribute("LoweredPath")]
[Bindable(true)]
public string LoweredPath
{
get
{
return GetColumnValue<string>("LoweredPath");
}
set
{
SetColumnValue("LoweredPath", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string ApplicationId = @"ApplicationId";
public static string PathId = @"PathId";
public static string Path = @"Path";
public static string LoweredPath = @"LoweredPath";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.