context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using FlatRedBall;
using FlatRedBall.Graphics;
#if FRB_MDX
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Direct3D=Microsoft.DirectX.Direct3D;
#else
#endif
namespace FlatRedBall.Gui
{
/// <summary>
/// Summary description for TextDisplay.
/// </summary>
public class TextDisplay : Window
{
#region Fields
string mText;
//TextField mTextField;
Text mTextObject;
#endregion
#region Properties
public override float ScaleX
{
get
{
return mScaleX;
}
set
{
mScaleX = value;
}
}
public override float ScaleY
{
get
{
return mScaleY;
}
set
{
mScaleY = value;
}
}
public string Text
{
get { return mText; }
set
{
mText = value;
if (mTextObject != null)
{
mTextObject.DisplayText = value;
}
}
}
public override bool Visible
{
get
{
return base.Visible;
}
set
{
base.Visible = value;
if (mTextObject != null)
{
mTextObject.Visible = value;
}
}
}
public float Width
{
get { return TextManager.GetWidth(this.Text, GuiManager.TextSpacing); }
}
#endregion
#region Methods
#region Constructor
public TextDisplay(Cursor cursor) : base(cursor)
{
}
#endregion
public override bool IsPointOnWindow(float cameraRelativeX, float cameraRelativeY)
{
return (cameraRelativeY > mWorldUnitY - GuiManager.TextHeight/2.0f &&
cameraRelativeY < mWorldUnitY + GuiManager.TextHeight / 2.0f &&
cameraRelativeX > mWorldUnitX &&
cameraRelativeX < mWorldUnitX + Width + 1);
}
public override void SetSkin(GuiSkin guiSkin)
{
//base.SetSkin(guiSkin);
if (mTextObject == null)
{
mTextObject = TextManager.AddText(mText);
GuiManagerDrawn = false;
}
}
public override string ToString()
{
return Text;
}
public void Wrap(float width)
{
mText =
TextManager.InsertNewLines(mText, GuiManager.TextSpacing, width, TextManager.DefaultFont);
}
#region Internal Methods
public override void Activity(Camera camera)
{
base.Activity(camera);
if (mTextObject != null)
{
mTextObject.X = this.X;
mTextObject.Y = this.Y;
}
}
internal override void DrawSelfAndChildren(Camera camera)
{
if (Visible == false)
return;
#if false // this is marked as if (false) so we must not be using it anymore? Not sure, but taking it out to eliminate warnings.
if (false)//mTextField != null)
{
TextManager.mRedForVertexBuffer = TextManager.mGreenForVertexBuffer = TextManager.mBlueForVertexBuffer = 20;
TextManager.mScaleForVertexBuffer = GuiManager.TextHeight / 2.0f;
TextManager.mSpacingForVertexBuffer = GuiManager.TextSpacing;
if (Enabled)
TextManager.mAlphaForVertexBuffer = 255;
else
TextManager.mAlphaForVertexBuffer = 115;
//TextManager.Draw(mTextField);
}
else
#endif
{
TextManager.mMaxWidthForVertexBuffer = float.PositiveInfinity;
TextManager.mAlignmentForVertexBuffer = HorizontalAlignment.Left;
TextManager.mXForVertexBuffer = mWorldUnitX + 1;
TextManager.mYForVertexBuffer = mWorldUnitY;
#if FRB_MDX
TextManager.mZForVertexBuffer = camera.Z + 100;
#else
TextManager.mZForVertexBuffer = camera.Z - 100;
#endif
TextManager.mScaleForVertexBuffer = GuiManager.TextHeight / 2.0f;
TextManager.mSpacingForVertexBuffer = GuiManager.TextSpacing;
TextManager.mRedForVertexBuffer = TextManager.mGreenForVertexBuffer = TextManager.mBlueForVertexBuffer = 20;
if (Enabled)
TextManager.mAlphaForVertexBuffer = 255;
else
TextManager.mAlphaForVertexBuffer = 115;
TextManager.Draw(ref mText);
}
}
internal override int GetNumberOfVerticesToDraw()
{
//if (false)//mTextField != null)
//{
// if (mTextField.DisplayText == null)
// return 0;
// else
// return mTextField.DisplayText.Replace(" ", "").Length * 6;
//}
//else
//{
if (Text == null)
return 0;
else
return Text.Replace(" ", "").Length * 6;
//}
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SslSecuredWebApplicationSample.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* FCKeditor - The text editor for internet
* Copyright (C) 2003-2004 Frederico Caldeira Knabben
*
* Licensed under the terms of the GNU Lesser General Public License:
* http://www.opensource.org/licenses/lgpl-license.php
*
* For further information visit:
* http://www.fckeditor.net/
*
* File Name: FileBrowserConnector.cs
* This is the code behind of the connector.aspx page used by the
* File Browser.
*
* Version: 2.1
* Modified: 2005-02-02 12:19:55
*
* File Authors:
* Frederico Caldeira Knabben (fredck@fckeditor.net)
*/
using System ;
using System.Globalization ;
using System.Xml ;
using System.Web ;
namespace FredCK.FCKeditorV2
{
public class FileBrowserConnector : System.Web.UI.Page
{
private const string DEFAULT_USER_FILES_PATH = "/UserFiles/" ;
private string sUserFilesPath ;
private string sUserFilesDirectory ;
protected override void OnLoad(EventArgs e)
{
// Get the main request informaiton.
string sCommand = Request.QueryString["Command"] ;
if ( sCommand == null ) return ;
string sResourceType = Request.QueryString["Type"] ;
if ( sResourceType == null ) return ;
string sCurrentFolder = Request.QueryString["CurrentFolder"] ;
if ( sCurrentFolder == null ) return ;
// Check the current folder syntax (must begin and start with a slash).
if ( ! sCurrentFolder.EndsWith( "/" ) )
sCurrentFolder += "/" ;
if ( ! sCurrentFolder.StartsWith( "/" ) )
sCurrentFolder = "/" + sCurrentFolder ;
// File Upload doesn't have to return XML, so it must be intercepted before anything.
if ( sCommand == "FileUpload" )
{
this.FileUpload( sResourceType, sCurrentFolder ) ;
return ;
}
// Cleans the response buffer.
Response.ClearHeaders() ;
Response.Clear() ;
// Prevent the browser from caching the result.
Response.CacheControl = "no-cache" ;
// Set the response format.
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8 ;
Response.ContentType = "text/xml" ;
XmlDocument oXML = new XmlDocument() ;
XmlNode oConnectorNode = CreateBaseXml( oXML, sCommand, sResourceType, sCurrentFolder ) ;
// Execute the required command.
switch( sCommand )
{
case "GetFolders" :
this.GetFolders( oConnectorNode, sResourceType, sCurrentFolder ) ;
break ;
case "GetFoldersAndFiles" :
this.GetFolders( oConnectorNode, sResourceType, sCurrentFolder ) ;
this.GetFiles( oConnectorNode, sResourceType, sCurrentFolder ) ;
break ;
case "CreateFolder" :
this.CreateFolder( oConnectorNode, sResourceType, sCurrentFolder ) ;
break ;
}
// Output the resulting XML.
Response.Write( oXML.OuterXml ) ;
Response.End() ;
}
#region Base XML Creation
private XmlNode CreateBaseXml( XmlDocument xml, string command, string resourceType, string currentFolder )
{
// Create the XML document header.
xml.AppendChild( xml.CreateXmlDeclaration( "1.0", "utf-8", null ) ) ;
// Create the main "Connector" node.
XmlNode oConnectorNode = XmlUtil.AppendElement( xml, "Connector" ) ;
XmlUtil.SetAttribute( oConnectorNode, "command", command ) ;
XmlUtil.SetAttribute( oConnectorNode, "resourceType", resourceType ) ;
// Add the current folder node.
XmlNode oCurrentNode = XmlUtil.AppendElement( oConnectorNode, "CurrentFolder" ) ;
XmlUtil.SetAttribute( oCurrentNode, "path", currentFolder ) ;
XmlUtil.SetAttribute( oCurrentNode, "url", GetUrlFromPath( resourceType, currentFolder) ) ;
return oConnectorNode ;
}
#endregion
#region Command Handlers
private void GetFolders( XmlNode connectorNode, string resourceType, string currentFolder )
{
// Map the virtual path to the local server path.
string sServerDir = this.ServerMapFolder( resourceType, currentFolder ) ;
// Create the "Folders" node.
XmlNode oFoldersNode = XmlUtil.AppendElement( connectorNode, "Folders" ) ;
System.IO.DirectoryInfo oDir = new System.IO.DirectoryInfo( sServerDir ) ;
System.IO.DirectoryInfo[] aSubDirs = oDir.GetDirectories() ;
for ( int i = 0 ; i < aSubDirs.Length ; i++ )
{
// Create the "Folders" node.
XmlNode oFolderNode = XmlUtil.AppendElement( oFoldersNode, "Folder" ) ;
XmlUtil.SetAttribute( oFolderNode, "name", aSubDirs[i].Name ) ;
}
}
private void GetFiles( XmlNode connectorNode, string resourceType, string currentFolder )
{
// Map the virtual path to the local server path.
string sServerDir = this.ServerMapFolder( resourceType, currentFolder ) ;
// Create the "Files" node.
XmlNode oFilesNode = XmlUtil.AppendElement( connectorNode, "Files" ) ;
System.IO.DirectoryInfo oDir = new System.IO.DirectoryInfo( sServerDir ) ;
System.IO.FileInfo[] aFiles = oDir.GetFiles() ;
for ( int i = 0 ; i < aFiles.Length ; i++ )
{
Decimal iFileSize = Math.Round( (Decimal)aFiles[i].Length / 1024 ) ;
if ( iFileSize < 1 && aFiles[i].Length != 0 ) iFileSize = 1 ;
// Create the "File" node.
XmlNode oFileNode = XmlUtil.AppendElement( oFilesNode, "File" ) ;
XmlUtil.SetAttribute( oFileNode, "name", aFiles[i].Name ) ;
XmlUtil.SetAttribute( oFileNode, "size", iFileSize.ToString( CultureInfo.InvariantCulture ) ) ;
}
}
private void CreateFolder( XmlNode connectorNode, string resourceType, string currentFolder )
{
string sErrorNumber = "0" ;
string sNewFolderName = Request.QueryString["NewFolderName"] ;
if ( sNewFolderName == null || sNewFolderName.Length == 0 )
sErrorNumber = "102" ;
else
{
// Map the virtual path to the local server path of the current folder.
string sServerDir = this.ServerMapFolder( resourceType, currentFolder ) ;
try
{
Util.CreateDirectory( System.IO.Path.Combine( sServerDir, sNewFolderName )) ;
}
catch ( ArgumentException )
{
sErrorNumber = "102" ;
}
catch ( System.IO.PathTooLongException )
{
sErrorNumber = "102" ;
}
catch ( System.IO.IOException )
{
sErrorNumber = "101" ;
}
catch ( System.Security.SecurityException )
{
sErrorNumber = "103" ;
}
catch ( Exception )
{
sErrorNumber = "110" ;
}
}
// Create the "Error" node.
XmlNode oErrorNode = XmlUtil.AppendElement( connectorNode, "Error" ) ;
XmlUtil.SetAttribute( oErrorNode, "number", sErrorNumber ) ;
}
private void FileUpload( string resourceType, string currentFolder )
{
HttpPostedFile oFile = Request.Files["NewFile"] ;
string sErrorNumber = "0" ;
string sFileName = "" ;
if ( oFile != null )
{
// Map the virtual path to the local server path.
string sServerDir = this.ServerMapFolder( resourceType, currentFolder ) ;
// Get the uploaded file name.
sFileName = System.IO.Path.GetFileName( oFile.FileName ) ;
int iCounter = 0 ;
while ( true )
{
string sFilePath = System.IO.Path.Combine( sServerDir, sFileName ) ;
if ( System.IO.File.Exists( sFilePath ) )
{
iCounter++ ;
sFileName =
System.IO.Path.GetFileNameWithoutExtension( oFile.FileName ) +
"(" + iCounter + ")" +
System.IO.Path.GetExtension( oFile.FileName ) ;
sErrorNumber = "201" ;
}
else
{
oFile.SaveAs( sFilePath ) ;
break ;
}
}
}
else
sErrorNumber = "202" ;
Response.Clear() ;
Response.Write( "<script type=\"text/javascript\">" ) ;
Response.Write( "window.parent.frames['frmUpload'].OnUploadCompleted(" + sErrorNumber + ",'" + sFileName.Replace( "'", "\\'" ) + "') ;" ) ;
Response.Write( "</script>" ) ;
Response.End() ;
}
#endregion
#region Directory Mapping
private string ServerMapFolder( string resourceType, string folderPath )
{
// Get the resource type directory.
string sResourceTypePath = System.IO.Path.Combine( this.UserFilesDirectory, resourceType ) ;
// Ensure that the directory exists.
Util.CreateDirectory( sResourceTypePath ) ;
// Return the resource type directory combined with the required path.
return System.IO.Path.Combine( sResourceTypePath, folderPath.TrimStart('/') ) ;
}
private string GetUrlFromPath( string resourceType, string folderPath )
{
if ( resourceType == null || resourceType.Length == 0 )
return this.UserFilesPath.TrimEnd('/') + folderPath ;
else
return this.UserFilesPath + resourceType + folderPath ;
}
private string UserFilesPath
{
get
{
if ( sUserFilesPath == null )
{
// Try to get from the "Application".
sUserFilesPath = (string)Application["FCKeditor:UserFilesPath"] ;
// Try to get from the "Session".
if ( sUserFilesPath == null || sUserFilesPath.Length == 0 )
{
sUserFilesPath = (string)Session["FCKeditor:UserFilesPath"] ;
// Try to get from the Web.config file.
if ( sUserFilesPath == null || sUserFilesPath.Length == 0 )
{
sUserFilesPath = System.Configuration.ConfigurationSettings.AppSettings["FCKeditor:UserFilesPath"] ;
// Try to get from the URL.
if ( sUserFilesPath == null || sUserFilesPath.Length == 0 )
{
sUserFilesPath = Request.QueryString["ServerPath"] ;
// Otherwise use the default value.
if ( sUserFilesPath == null || sUserFilesPath.Length == 0 )
sUserFilesPath = DEFAULT_USER_FILES_PATH ;
}
}
}
// Check that the user path ends with slash ("/")
if ( ! sUserFilesPath.EndsWith("/") )
sUserFilesPath += "/" ;
}
return sUserFilesPath ;
}
}
private string UserFilesDirectory
{
get
{
if ( sUserFilesDirectory == null )
{
// Get the local (server) directory path translation.
sUserFilesDirectory = Server.MapPath( this.UserFilesPath ) ;
}
return sUserFilesDirectory ;
}
}
#endregion
}
}
| |
using System;
using Shouldly;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// The Numerics class contains common operations on numeric values.
/// </summary>
internal static class Numerics
{
/// <summary>
/// Checks the type of the object, returning true if
/// the object is a numeric type.
/// </summary>
/// <param name="obj">The object to check</param>
/// <returns>true if the object is a numeric type</returns>
public static bool IsNumericType(Object obj)
{
return IsFloatingPointNumeric(obj) || IsFixedPointNumeric(obj);
}
/// <summary>
/// Checks the type of the object, returning true if
/// the object is a floating point numeric type.
/// </summary>
/// <param name="obj">The object to check</param>
/// <returns>true if the object is a floating point numeric type</returns>
public static bool IsFloatingPointNumeric(Object obj)
{
if (null != obj)
{
if (obj is Double) return true;
if (obj is Single) return true;
}
return false;
}
/// <summary>
/// Checks the type of the object, returning true if
/// the object is a fixed point numeric type.
/// </summary>
/// <param name="obj">The object to check</param>
/// <returns>true if the object is a fixed point numeric type</returns>
public static bool IsFixedPointNumeric(Object obj)
{
if (null != obj)
{
if (obj is Byte) return true;
if (obj is SByte) return true;
if (obj is Decimal) return true;
if (obj is Int32) return true;
if (obj is UInt32) return true;
if (obj is Int64) return true;
if (obj is UInt64) return true;
if (obj is Int16) return true;
if (obj is UInt16) return true;
}
return false;
}
/// <summary>
/// Test two numeric values for equality, performing the usual numeric
/// conversions and using a provided or default tolerance. If the tolerance
/// provided is Empty, this method may set it to a default tolerance.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
/// <param name="tolerance">A reference to the tolerance in effect</param>
/// <returns>True if the values are equal</returns>
public static bool AreEqual(object expected, object actual, ref Tolerance tolerance)
{
if (expected is double || actual is double)
return AreEqual(Convert.ToDouble(expected), Convert.ToDouble(actual), ref tolerance);
if (expected is float || actual is float)
return AreEqual(Convert.ToSingle(expected), Convert.ToSingle(actual), ref tolerance);
if (tolerance.Mode == ToleranceMode.Ulps)
throw new InvalidOperationException("Ulps may only be specified for floating point arguments");
if (expected is decimal || actual is decimal)
return AreEqual(Convert.ToDecimal(expected), Convert.ToDecimal(actual), tolerance);
if (expected is ulong || actual is ulong)
return AreEqual(Convert.ToUInt64(expected), Convert.ToUInt64(actual), tolerance);
if (expected is long || actual is long)
return AreEqual(Convert.ToInt64(expected), Convert.ToInt64(actual), tolerance);
if (expected is uint || actual is uint)
return AreEqual(Convert.ToUInt32(expected), Convert.ToUInt32(actual), tolerance);
return AreEqual(Convert.ToInt32(expected), Convert.ToInt32(actual), tolerance);
}
private static bool AreEqual(double expected, double actual, ref Tolerance tolerance)
{
if (double.IsNaN(expected) && double.IsNaN(actual))
return true;
// Handle infinity specially since subtracting two infinite values gives
// NaN and the following test fails. mono also needs NaN to be handled
// specially although ms.net could use either method. Also, handle
// situation where no tolerance is used.
if (double.IsInfinity(expected) || double.IsNaN(expected) || double.IsNaN(actual))
{
return expected.Equals(actual);
}
if (tolerance.IsEmpty && ShouldlyConfiguration.DefaultFloatingPointTolerance > 0.0d)
tolerance = new Tolerance(ShouldlyConfiguration.DefaultFloatingPointTolerance);
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value);
case ToleranceMode.Percent:
if (expected == 0.0)
return expected.Equals(actual);
double relativeError = Math.Abs((expected - actual)/expected);
return (relativeError <= Convert.ToDouble(tolerance.Value)/100.0);
case ToleranceMode.Ulps:
return FloatingPointNumerics.AreAlmostEqualUlps(
expected, actual, Convert.ToInt64(tolerance.Value));
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual(float expected, float actual, ref Tolerance tolerance)
{
if (float.IsNaN(expected) && float.IsNaN(actual))
return true;
// handle infinity specially since subtracting two infinite values gives
// NaN and the following test fails. mono also needs NaN to be handled
// specially although ms.net could use either method.
if (float.IsInfinity(expected) || float.IsNaN(expected) || float.IsNaN(actual))
{
return expected.Equals(actual);
}
if (tolerance.IsEmpty && ShouldlyConfiguration.DefaultFloatingPointTolerance > 0.0d)
tolerance = new Tolerance(ShouldlyConfiguration.DefaultFloatingPointTolerance);
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value);
case ToleranceMode.Percent:
if (expected == 0.0f)
return expected.Equals(actual);
float relativeError = Math.Abs((expected - actual)/expected);
return (relativeError <= Convert.ToSingle(tolerance.Value)/100.0f);
case ToleranceMode.Ulps:
return FloatingPointNumerics.AreAlmostEqualUlps(
expected, actual, Convert.ToInt32(tolerance.Value));
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual(decimal expected, decimal actual, Tolerance tolerance)
{
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
decimal decimalTolerance = Convert.ToDecimal(tolerance.Value);
if (decimalTolerance > 0m)
return Math.Abs(expected - actual) <= decimalTolerance;
return expected.Equals(actual);
case ToleranceMode.Percent:
if (expected == 0m)
return expected.Equals(actual);
double relativeError = Math.Abs(
(double) (expected - actual)/(double) expected);
return (relativeError <= Convert.ToDouble(tolerance.Value)/100.0);
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual(ulong expected, ulong actual, Tolerance tolerance)
{
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
ulong ulongTolerance = Convert.ToUInt64(tolerance.Value);
if (ulongTolerance > 0ul)
{
ulong diff = expected >= actual ? expected - actual : actual - expected;
return diff <= ulongTolerance;
}
return expected.Equals(actual);
case ToleranceMode.Percent:
if (expected == 0ul)
return expected.Equals(actual);
// Can't do a simple Math.Abs() here since it's unsigned
ulong difference = Math.Max(expected, actual) - Math.Min(expected, actual);
double relativeError = Math.Abs(difference/(double) expected);
return (relativeError <= Convert.ToDouble(tolerance.Value)/100.0);
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual(long expected, long actual, Tolerance tolerance)
{
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
long longTolerance = Convert.ToInt64(tolerance.Value);
if (longTolerance > 0L)
return Math.Abs(expected - actual) <= longTolerance;
return expected.Equals(actual);
case ToleranceMode.Percent:
if (expected == 0L)
return expected.Equals(actual);
double relativeError = Math.Abs(
(expected - actual)/(double) expected);
return (relativeError <= Convert.ToDouble(tolerance.Value)/100.0);
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual(uint expected, uint actual, Tolerance tolerance)
{
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
uint uintTolerance = Convert.ToUInt32(tolerance.Value);
if (uintTolerance > 0)
{
uint diff = expected >= actual ? expected - actual : actual - expected;
return diff <= uintTolerance;
}
return expected.Equals(actual);
case ToleranceMode.Percent:
if (expected == 0u)
return expected.Equals(actual);
// Can't do a simple Math.Abs() here since it's unsigned
uint difference = Math.Max(expected, actual) - Math.Min(expected, actual);
double relativeError = Math.Abs(difference/(double) expected);
return (relativeError <= Convert.ToDouble(tolerance.Value)/100.0);
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual(int expected, int actual, Tolerance tolerance)
{
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
int intTolerance = Convert.ToInt32(tolerance.Value);
if (intTolerance > 0)
return Math.Abs(expected - actual) <= intTolerance;
return expected.Equals(actual);
case ToleranceMode.Percent:
if (expected == 0)
return expected.Equals(actual);
double relativeError = Math.Abs(
(expected - actual)/(double) expected);
return (relativeError <= Convert.ToDouble(tolerance.Value)/100.0);
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
/// <summary>
/// Compare two numeric values, performing the usual numeric conversions.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
/// <returns>The relationship of the values to each other</returns>
public static int Compare(object expected, object actual)
{
if (!IsNumericType(expected) || !IsNumericType(actual))
throw new ArgumentException("Both arguments must be numeric");
if (IsFloatingPointNumeric(expected) || IsFloatingPointNumeric(actual))
return Convert.ToDouble(expected).CompareTo(Convert.ToDouble(actual));
if (expected is decimal || actual is decimal)
return Convert.ToDecimal(expected).CompareTo(Convert.ToDecimal(actual));
if (expected is ulong || actual is ulong)
return Convert.ToUInt64(expected).CompareTo(Convert.ToUInt64(actual));
if (expected is long || actual is long)
return Convert.ToInt64(expected).CompareTo(Convert.ToInt64(actual));
if (expected is uint || actual is uint)
return Convert.ToUInt32(expected).CompareTo(Convert.ToUInt32(actual));
return Convert.ToInt32(expected).CompareTo(Convert.ToInt32(actual));
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/16/2009 5:25:17 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Xml.Serialization;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// LegendItem
/// </summary>
[Serializable]
public class LegendItem : Descriptor, ILegendItem
{
#region Events
/// <summary>
/// Occurs whenever the symbol content has been updated
/// </summary>
public event EventHandler ItemChanged;
/// <summary>
/// Occurs whenever the item should be removed from the parent collection
/// </summary>
public event EventHandler RemoveItem;
#endregion
#region Private Variables
// Legend Item properties
//private IChangeEventList<ILegendItem> _legendItems; // not used by mapwindow, but can be used by developers
private bool _changeOccured;
private bool _checked;
private bool _isDragable;
private bool _isExpanded;
private bool _isLegendGroup;
private bool _isSelected;
private int _itemChangedSuspend;
private bool _legendItemVisible;
private SymbolMode _legendSymbolMode;
private Size _legendSymbolSize;
private string _legendText;
private LegendType _legendType;
private List<SymbologyMenuItem> _menuItems;
private ILegendItem _parentLegendItem;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of the legend item
/// </summary>
public LegendItem()
{
Configure();
}
/// <summary>
/// Configures the default settings of the legend item
/// </summary>
private void Configure()
{
_legendItemVisible = true;
_isSelected = false;
_isExpanded = false;
_legendSymbolMode = SymbolMode.Symbol;
_legendSymbolSize = new Size(16, 16);
_isDragable = false;
_legendType = LegendType.Symbol;
}
#endregion
#region Methods
/// <summary>
/// Returns a boolean indicating whether or not this item can have other items dropped on it.
/// By default this is false. This can be overridden for more customized behaviors.
/// </summary>
/// <param name="item">The item to test for dropping.</param>
/// <returns></returns>
public virtual bool CanReceiveItem(ILegendItem item)
{
if (LegendType == LegendType.Scheme)
{
if (item.LegendType == LegendType.Symbol) return true;
return false;
}
if (LegendType == LegendType.Group)
{
if (item.LegendType == LegendType.Symbol) return false;
if (item.LegendType == LegendType.Scheme) return false;
return true;
}
if (LegendType == LegendType.Layer)
{
if (item.LegendType == LegendType.Symbol) return true;
if (item.LegendType == LegendType.Scheme) return true;
return false;
}
if (LegendType == LegendType.Symbol)
{
return false;
}
return false;
}
/// <summary>
/// Draws the symbol for this specific category to the legend
/// </summary>
/// <param name="g"></param>
/// <param name="box"></param>
public virtual void LegendSymbol_Painted(Graphics g, Rectangle box)
{
// throw new NotImplementedException("This should be implemented in a sub-class");
}
/// <summary>
/// Prints the formal legend content without any resize boxes or other notations.
/// </summary>
/// <param name="g">The graphics object to print to</param>
/// <param name="font">The system.Drawing.Font to use for the lettering</param>
/// <param name="fontColor">The color of the font</param>
/// <param name="maxExtent">Assuming 0, 0 is the top left, this is the maximum extent</param>
public void PrintLegendItem(Graphics g, Font font, Color fontColor, SizeF maxExtent)
{
string text = LegendText;
if (text == null)
{
ILegendItem parent = GetParentItem();
if (parent != null)
{
if (parent.LegendItems.Count() == 1)
{
// go ahead and use the layer name, but only if this is the only category and the legend text is null
text = parent.LegendText;
}
}
}
// if LegendText is null, the measure string helpfully chooses a height that is 0, so use a fake text for height calc
SizeF emptyString = g.MeasureString("Sample text", font);
float h = emptyString.Height;
float x = 0;
bool drawBox = false;
if (LegendSymbolMode == SymbolMode.Symbol)
{
drawBox = true;
x = h * 2 + 4;
}
Brush b = new SolidBrush(fontColor);
StringFormat frmt = new StringFormat
{
Alignment = StringAlignment.Near,
Trimming = StringTrimming.EllipsisCharacter
};
float w = maxExtent.Width - x;
g.DrawString(text, font, b, new RectangleF(x, 2, w, h), frmt);
if (drawBox) LegendSymbol_Painted(g, new Rectangle(2, 2, (int)x - 4, (int)h));
b.Dispose();
}
/// <summary>
/// Handles updating event handlers during a copy process
/// </summary>
/// <param name="copy"></param>
protected override void OnCopy(Descriptor copy)
{
LegendItem myCopy = copy as LegendItem;
if (myCopy != null && myCopy.ItemChanged != null)
{
foreach (Delegate handler in myCopy.ItemChanged.GetInvocationList())
{
myCopy.ItemChanged -= (EventHandler)handler;
}
}
if (myCopy != null && myCopy.RemoveItem != null)
{
foreach (Delegate handler in myCopy.RemoveItem.GetInvocationList())
{
myCopy.RemoveItem -= (EventHandler)handler;
}
}
base.OnCopy(copy);
}
/// <summary>
/// Allows the ItemChanged event to fire in response to individual changes again.
/// This will also fire the event once if there were any changes that warent it
/// that were made while the event was suspended.
/// </summary>
public void ResumeChangeEvent()
{
_itemChangedSuspend -= 1;
if (_itemChangedSuspend == 0)
{
if (_changeOccured)
{
#if DEBUG
var sw = new Stopwatch();
sw.Start();
#endif
OnItemChanged();
#if DEBUG
sw.Stop();
Debug.WriteLine("OnItemChanged time:" + sw.ElapsedMilliseconds);
#endif
}
}
// Prevent forcing extra negatives.
if (_itemChangedSuspend < 0) _itemChangedSuspend = 0;
}
/// <summary>
/// Each suspend call increments an integer, essentially keeping track of the depth of
/// suspension. When the same number of ResumeChangeEvents methods have been called
/// as SuspendChangeEvents have been called, the suspension is aborted and the
/// legend item is allowed to broadcast its changes.
/// </summary>
public void SuspendChangeEvent()
{
if (_itemChangedSuspend == 0)
{
_changeOccured = false;
}
_itemChangedSuspend += 1;
}
#endregion
#region Properties
/// <summary>
/// Boolean, true if changes are suspended
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
XmlIgnore]
public bool ChangesSuspended
{
get { return (_itemChangedSuspend > 0); }
}
/// <summary>
/// Gets or sets a boolean that indicates whether or not this legend item can be dragged to a new position in the legend.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsDragable
{
get { return _isDragable; }
set { _isDragable = value; }
}
/// <summary>
/// Gets or sets a boolean, that if false will prevent this item, or any of its child items
/// from appearing in the legend when the legend is drawn.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool LegendItemVisible
{
get { return _legendItemVisible; }
set { _legendItemVisible = value; }
}
/// <summary>
/// Because these are in symbol mode, this is not used.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool Checked
{
get
{
return _checked;
}
set
{
_checked = value;
}
}
/// <summary>
/// Gets the MenuItems that should appear in the context menu of the legend for this category
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
XmlIgnore]
public virtual List<SymbologyMenuItem> ContextMenuItems
{
get { return _menuItems; }
set { _menuItems = value; }
}
/// <summary>
/// Gets or sets a boolean that indicates whether or not the legend should draw the child LegendItems for this category.
/// </summary>
[Serialize("IsExpanded")]
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool IsExpanded
{
get
{
return _isExpanded;
}
set
{
_isExpanded = value;
}
}
/// <summary>
/// Gets or sets whether this legend item has been selected in the legend
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool IsSelected
{
get
{
return _isSelected;
}
set
{
_isSelected = value;
}
}
/// <summary>
/// Gets whatever the child collection is and returns it as an IEnumerable set of legend items
/// in order to make it easier to cycle through those values. This defaults to null and must
/// be overridden in specific cases where child legend items exist.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual IEnumerable<ILegendItem> LegendItems
{
get { return null; }
}
/// <summary>
/// Gets or sets the symbol mode for the legend. By default this should be "Symbol", but this can be overridden
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual SymbolMode LegendSymbolMode
{
get { return _legendSymbolMode; }
protected set { _legendSymbolMode = value; }
}
/// <summary>
/// Gets or sets the size of the symbol to be drawn to the legend
/// </summary>
public virtual Size GetLegendSymbolSize()
{
return _legendSymbolSize;
}
/// <summary>
/// Gets or sets the text for this category to appear in the legend. This might be a category name,
/// or a range of values.
/// </summary>
[Description("Gets or sets the text for this category to appear in the legend.")]
[Serialize("LegendText")]
public virtual string LegendText
{
get
{
return _legendText;
}
set
{
if (value == _legendText) return;
_legendText = value;
OnItemChanged(this);
}
}
/// <summary>
/// Gets or sets a pre-defined behavior in the legend when referring to drag and drop functionality.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public LegendType LegendType
{
get { return _legendType; }
protected set { _legendType = value; }
}
/// <summary>
/// Gets the Parent Legend item for this category. This should probably be the appropriate layer item.
/// </summary>
public ILegendItem GetParentItem()
{
return _parentLegendItem;
}
/// <summary>
/// Sets the parent legend item for this category.
/// </summary>
/// <param name="value"></param>
public void SetParentItem(ILegendItem value)
{
OnSetParentItem(value);
}
/// <summary>
/// Allows for the set behavior for the parent item to be overridden in child classes
/// </summary>
/// <param name="value"></param>
protected virtual void OnSetParentItem(ILegendItem value)
{
_parentLegendItem = value;
}
#endregion
#region Protected Methods
/// <summary>
/// If this is true, then "can receive
/// </summary>
[Serialize("IsLegendGroup")]
protected bool IsLegendGroup
{
get { return _isLegendGroup; }
set { _isLegendGroup = value; }
}
/// <summary>
/// Fires the ItemChanged event
/// </summary>
protected virtual void OnItemChanged()
{
OnItemChanged(this);
}
/// <summary>
/// Fires the ItemChanged event, optionally specifying a different
/// sender
/// </summary>
protected virtual void OnItemChanged(object sender)
{
if (_itemChangedSuspend > 0)
{
_changeOccured = true;
return;
}
if (ItemChanged == null) return;
ItemChanged(sender, EventArgs.Empty);
}
/// <summary>
/// Instructs the parent legend item to remove this item from the list of legend items.
/// </summary>
protected virtual void OnRemoveItem()
{
if (RemoveItem != null) RemoveItem(this, EventArgs.Empty);
// Maybe we don't need RemoveItem event. We could just invoke a method on the parent.
// One less thing to wire. But we currently need to wire parents.
}
#endregion
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.IO;
namespace Google.ProtocolBuffers
{
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract partial class AbstractBuilderLite<TMessage, TBuilder> : IBuilderLite<TMessage, TBuilder>
where TMessage : AbstractMessageLite<TMessage, TBuilder>
where TBuilder : AbstractBuilderLite<TMessage, TBuilder>
{
protected abstract TBuilder ThisBuilder { get; }
public abstract bool IsInitialized { get; }
public abstract TBuilder Clear();
public abstract TBuilder Clone();
public abstract TMessage Build();
public abstract TMessage BuildPartial();
public abstract TBuilder MergeFrom(IMessageLite other);
public abstract TBuilder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry);
public abstract TMessage DefaultInstanceForType { get; }
#region IBuilderLite<TMessage,TBuilder> Members
public virtual TBuilder MergeFrom(ICodedInputStream input)
{
return MergeFrom(input, ExtensionRegistry.CreateInstance());
}
public TBuilder MergeDelimitedFrom(Stream input)
{
return MergeDelimitedFrom(input, ExtensionRegistry.CreateInstance());
}
public TBuilder MergeDelimitedFrom(Stream input, ExtensionRegistry extensionRegistry)
{
int size = (int) CodedInputStream.ReadRawVarint32(input);
Stream limitedStream = new LimitedInputStream(input, size);
return MergeFrom(limitedStream, extensionRegistry);
}
public TBuilder MergeFrom(ByteString data)
{
return MergeFrom(data, ExtensionRegistry.CreateInstance());
}
public TBuilder MergeFrom(ByteString data, ExtensionRegistry extensionRegistry)
{
CodedInputStream input = data.CreateCodedInput();
MergeFrom(input, extensionRegistry);
input.CheckLastTagWas(0);
return ThisBuilder;
}
public TBuilder MergeFrom(byte[] data)
{
CodedInputStream input = CodedInputStream.CreateInstance(data);
MergeFrom(input);
input.CheckLastTagWas(0);
return ThisBuilder;
}
public TBuilder MergeFrom(byte[] data, ExtensionRegistry extensionRegistry)
{
CodedInputStream input = CodedInputStream.CreateInstance(data);
MergeFrom(input, extensionRegistry);
input.CheckLastTagWas(0);
return ThisBuilder;
}
public TBuilder MergeFrom(Stream input)
{
CodedInputStream codedInput = CodedInputStream.CreateInstance(input);
MergeFrom(codedInput);
codedInput.CheckLastTagWas(0);
return ThisBuilder;
}
public TBuilder MergeFrom(Stream input, ExtensionRegistry extensionRegistry)
{
CodedInputStream codedInput = CodedInputStream.CreateInstance(input);
MergeFrom(codedInput, extensionRegistry);
codedInput.CheckLastTagWas(0);
return ThisBuilder;
}
#endregion
#region Explicit definitions
IBuilderLite IBuilderLite.WeakClear()
{
return Clear();
}
IBuilderLite IBuilderLite.WeakMergeFrom(IMessageLite message)
{
return MergeFrom(message);
}
IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data)
{
return MergeFrom(data);
}
IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data, ExtensionRegistry registry)
{
return MergeFrom(data, registry);
}
IBuilderLite IBuilderLite.WeakMergeFrom(ICodedInputStream input)
{
return MergeFrom(input);
}
IBuilderLite IBuilderLite.WeakMergeFrom(ICodedInputStream input, ExtensionRegistry registry)
{
return MergeFrom(input, registry);
}
IMessageLite IBuilderLite.WeakBuild()
{
return Build();
}
IMessageLite IBuilderLite.WeakBuildPartial()
{
return BuildPartial();
}
IBuilderLite IBuilderLite.WeakClone()
{
return Clone();
}
IMessageLite IBuilderLite.WeakDefaultInstanceForType
{
get { return DefaultInstanceForType; }
}
#endregion
#region LimitedInputStream
/// <summary>
/// Stream implementation which proxies another stream, only allowing a certain amount
/// of data to be read. Note that this is only used to read delimited streams, so it
/// doesn't attempt to implement everything.
/// </summary>
private class LimitedInputStream : Stream
{
private readonly Stream proxied;
private int bytesLeft;
internal LimitedInputStream(Stream proxied, int size)
{
this.proxied = proxied;
bytesLeft = size;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override int Read(byte[] buffer, int offset, int count)
{
if (bytesLeft > 0)
{
int bytesRead = proxied.Read(buffer, offset, Math.Min(bytesLeft, count));
bytesLeft -= bytesRead;
return bytesRead;
}
return 0;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
#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.Buffers;
using System.IO;
namespace System.Security.Cryptography
{
public abstract partial class DSA : AsymmetricAlgorithm
{
public abstract DSAParameters ExportParameters(bool includePrivateParameters);
public abstract void ImportParameters(DSAParameters parameters);
protected DSA() { }
public static new DSA Create(string algName)
{
return (DSA)CryptoConfig.CreateFromName(algName);
}
public static DSA Create(int keySizeInBits)
{
DSA dsa = Create();
try
{
dsa.KeySize = keySizeInBits;
return dsa;
}
catch
{
dsa.Dispose();
throw;
}
}
public static DSA Create(DSAParameters parameters)
{
DSA dsa = Create();
try
{
dsa.ImportParameters(parameters);
return dsa;
}
catch
{
dsa.Dispose();
throw;
}
}
// DSA does not encode the algorithm identifier into the signature blob, therefore CreateSignature and
// VerifySignature do not need the HashAlgorithmName value, only SignData and VerifyData do.
abstract public byte[] CreateSignature(byte[] rgbHash);
abstract public bool VerifySignature(byte[] rgbHash, byte[] rgbSignature);
protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
throw DerivedClassMustOverride();
}
protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
throw DerivedClassMustOverride();
}
public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
return SignData(data, 0, data.Length, hashAlgorithm);
}
public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
if (data == null) { throw new ArgumentNullException(nameof(data)); }
if (offset < 0 || offset > data.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); }
if (count < 0 || count > data.Length - offset) { throw new ArgumentOutOfRangeException(nameof(count)); }
if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); }
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return CreateSignature(hash);
}
public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm)
{
if (data == null) { throw new ArgumentNullException(nameof(data)); }
if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); }
byte[] hash = HashData(data, hashAlgorithm);
return CreateSignature(hash);
}
public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
return VerifyData(data, 0, data.Length, signature, hashAlgorithm);
}
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null) { throw new ArgumentNullException(nameof(data)); }
if (offset < 0 || offset > data.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); }
if (count < 0 || count > data.Length - offset) { throw new ArgumentOutOfRangeException(nameof(count)); }
if (signature == null) { throw new ArgumentNullException(nameof(signature)); }
if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); }
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return VerifySignature(hash, signature);
}
public virtual bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null) { throw new ArgumentNullException(nameof(data)); }
if (signature == null) { throw new ArgumentNullException(nameof(signature)); }
if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); }
byte[] hash = HashData(data, hashAlgorithm);
return VerifySignature(hash, signature);
}
public virtual bool TryCreateSignature(ReadOnlySpan<byte> hash, Span<byte> destination, out int bytesWritten)
{
byte[] sig = CreateSignature(hash.ToArray());
if (sig.Length <= destination.Length)
{
new ReadOnlySpan<byte>(sig).CopyTo(destination);
bytesWritten = sig.Length;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
protected virtual bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
{
byte[] array = ArrayPool<byte>.Shared.Rent(data.Length);
try
{
data.CopyTo(array);
byte[] hash = HashData(array, 0, data.Length, hashAlgorithm);
if (destination.Length >= hash.Length)
{
new ReadOnlySpan<byte>(hash).CopyTo(destination);
bytesWritten = hash.Length;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
finally
{
Array.Clear(array, 0, data.Length);
ArrayPool<byte>.Shared.Return(array);
}
}
public virtual bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw HashAlgorithmNameNullOrEmpty();
}
if (TryHashData(data, destination, hashAlgorithm, out int hashLength) &&
TryCreateSignature(destination.Slice(0, hashLength), destination, out bytesWritten))
{
return true;
}
bytesWritten = 0;
return false;
}
public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw HashAlgorithmNameNullOrEmpty();
}
for (int i = 256; ; i = checked(i * 2))
{
int hashLength = 0;
byte[] hash = ArrayPool<byte>.Shared.Rent(i);
try
{
if (TryHashData(data, hash, hashAlgorithm, out hashLength))
{
return VerifySignature(new ReadOnlySpan<byte>(hash, 0, hashLength), signature);
}
}
finally
{
Array.Clear(hash, 0, hashLength);
ArrayPool<byte>.Shared.Return(hash);
}
}
}
public virtual bool VerifySignature(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature) =>
VerifySignature(hash.ToArray(), signature.ToArray());
private static Exception DerivedClassMustOverride() =>
new NotImplementedException(SR.NotSupported_SubclassOverride);
internal static Exception HashAlgorithmNameNullOrEmpty() =>
new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// 5.2.3: location of the radiating portion of the antenna, specified in world coordinates and entity coordinates.
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(Vector3Double))]
[XmlInclude(typeof(Vector3Float))]
public partial class AntennaLocation
{
/// <summary>
/// Location of the radiating portion of the antenna in world coordinates
/// </summary>
private Vector3Double _antennaLocation = new Vector3Double();
/// <summary>
/// Location of the radiating portion of the antenna in entity coordinates
/// </summary>
private Vector3Float _relativeAntennaLocation = new Vector3Float();
/// <summary>
/// Initializes a new instance of the <see cref="AntennaLocation"/> class.
/// </summary>
public AntennaLocation()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(AntennaLocation left, AntennaLocation right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(AntennaLocation left, AntennaLocation right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += this._antennaLocation.GetMarshalledSize(); // this._antennaLocation
marshalSize += this._relativeAntennaLocation.GetMarshalledSize(); // this._relativeAntennaLocation
return marshalSize;
}
/// <summary>
/// Gets or sets the Location of the radiating portion of the antenna in world coordinates
/// </summary>
[XmlElement(Type = typeof(Vector3Double), ElementName = "antennaLocation")]
public Vector3Double AntennaLocation_
{
get
{
return this._antennaLocation;
}
set
{
this._antennaLocation = value;
}
}
/// <summary>
/// Gets or sets the Location of the radiating portion of the antenna in entity coordinates
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "relativeAntennaLocation")]
public Vector3Float RelativeAntennaLocation
{
get
{
return this._relativeAntennaLocation;
}
set
{
this._relativeAntennaLocation = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
this._antennaLocation.Marshal(dos);
this._relativeAntennaLocation.Marshal(dos);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._antennaLocation.Unmarshal(dis);
this._relativeAntennaLocation.Unmarshal(dis);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<AntennaLocation>");
try
{
sb.AppendLine("<antennaLocation>");
this._antennaLocation.Reflection(sb);
sb.AppendLine("</antennaLocation>");
sb.AppendLine("<relativeAntennaLocation>");
this._relativeAntennaLocation.Reflection(sb);
sb.AppendLine("</relativeAntennaLocation>");
sb.AppendLine("</AntennaLocation>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as AntennaLocation;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(AntennaLocation obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (!this._antennaLocation.Equals(obj._antennaLocation))
{
ivarsEqual = false;
}
if (!this._relativeAntennaLocation.Equals(obj._relativeAntennaLocation))
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._antennaLocation.GetHashCode();
result = GenerateHash(result) ^ this._relativeAntennaLocation.GetHashCode();
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Flame.Attributes;
using Flame.Build;
using Flame.Compiler;
using Flame.Compiler.Build;
using Flame.Compiler.Expressions;
using Flame.Compiler.Statements;
using Flame.Compiler.Variables;
using Flame.LLVM.Codegen;
using LLVMSharp;
using static LLVMSharp.LLVM;
namespace Flame.LLVM
{
/// <summary>
/// A base class for type members that create symbols.
/// </summary>
public abstract class LLVMSymbolTypeMember : ITypeMember
{
public LLVMSymbolTypeMember(LLVMType DeclaringType)
{
this.ParentType = DeclaringType;
this.abiVal = new Lazy<LLVMAbi>(PickLLVMAbi);
}
public LLVMSymbolTypeMember(LLVMType DeclaringType, LLVMAbi Abi)
{
this.ParentType = DeclaringType;
this.abiVal = Abi.AsLazyAbi();
}
/// <summary>
/// Gets this symbol type member's declaring type as an LLVM type.
/// </summary>
/// <returns>The declaring type.</returns>
public LLVMType ParentType { get; private set; }
/// <summary>
/// Tests if this member is defined externally and only imported.
/// </summary>
/// <returns>
/// <c>true</c> if this member is defined externally;
/// <c>false</c> if it is defined internally.
/// </returns>
public bool IsImport => IsImportedMember(this);
private Lazy<LLVMAbi> abiVal;
private LLVMAbi PickLLVMAbi()
{
return PickLLVMAbi(this, ParentType.Namespace.Assembly);
}
private static bool IsImportedMember(ITypeMember Member)
{
return Member.HasAttribute(PrimitiveAttributes.Instance.ImportAttribute.AttributeType);
}
private static LLVMAbi PickLLVMAbi(ITypeMember Member, LLVMAssembly DeclaringAssembly)
{
var abiName = LLVMAttributes.GetAbiName(Member);
if (abiName != null)
{
switch (abiName.ToLowerInvariant())
{
case "c":
return DeclaringAssembly.ExternalAbi;
case "c++":
case "c#":
return DeclaringAssembly.Abi;
default:
throw new InvalidDataException(
LLVMAttributes.AbiAttributeName + " specified unknown ABI '" + abiName + "'");
}
}
else if (Member.IsStatic && IsImportedMember(Member))
{
return DeclaringAssembly.ExternalAbi;
}
else
{
return DeclaringAssembly.Abi;
}
}
/// <summary>
/// Gets the ABI for the given member.
/// </summary>
/// <param name="Member">The member for which an ABI is to be found.</param>
/// <param name="DeclaringAssembly">The assembly that is examined for candidate ABIs.</param>
/// <returns>The right ABI for the given member.</returns>
public static LLVMAbi GetLLVMAbi(ITypeMember Member, LLVMAssembly DeclaringAssembly)
{
if (Member is LLVMMethod)
return ((LLVMMethod)Member).Abi;
else if (Member is LLVMField)
return ((LLVMField)Member).Abi;
else
return PickLLVMAbi(Member, DeclaringAssembly);
}
/// <summary>
/// Gets the ABI for this method.
/// </summary>
public LLVMAbi Abi => abiVal.Value;
public abstract bool IsStatic { get; }
public IType DeclaringType => ParentType;
public abstract AttributeMap Attributes { get; }
public abstract UnqualifiedName Name { get; }
public QualifiedName FullName => Name.Qualify(DeclaringType.FullName);
/// <summary>
/// Gets the linkage for this symbol.
/// </summary>
/// <returns>The linkage.</returns>
public LLVMLinkage Linkage
{
get
{
var linkageAttr = this.GetAttribute(LLVMLinkageAttribute.LinkageAttributeType);
if (linkageAttr != null)
{
return ((LLVMLinkageAttribute)linkageAttr).Linkage;
}
if (this.HasAttribute(
PrimitiveAttributes.Instance.ImportAttribute.AttributeType))
{
return LLVMLinkage.LLVMExternalLinkage;
}
var access = this.GetAccess();
switch (access)
{
case AccessModifier.Private:
case AccessModifier.Assembly:
case AccessModifier.ProtectedAndAssembly:
return LLVMLinkage.LLVMInternalLinkage;
default:
return ParentType.Namespace.Assembly.IsWholeProgram
? LLVMLinkage.LLVMInternalLinkage
: LLVMLinkage.LLVMExternalLinkage;
}
}
}
}
/// <summary>
/// A method builder for LLVM assemblies.
/// </summary>
public class LLVMMethod : LLVMSymbolTypeMember, IMethodBuilder
{
public LLVMMethod(LLVMType DeclaringType, IMethodSignatureTemplate Template)
: base(DeclaringType)
{
this.templateInstance = new MethodSignatureInstance(Template, this);
this.allInterfaceImpls = new Lazy<HashSet<LLVMMethod>>(LookupAllInterfaceImpls);
}
public LLVMMethod(LLVMType DeclaringType, IMethodSignatureTemplate Template, LLVMAbi Abi)
: base(DeclaringType, Abi)
{
this.templateInstance = new MethodSignatureInstance(Template, this);
this.allInterfaceImpls = new Lazy<HashSet<LLVMMethod>>(LookupAllInterfaceImpls);
}
private LLVMCodeGenerator codeGenerator;
private CodeBlock body;
private Lazy<HashSet<LLVMMethod>> allInterfaceImpls;
private MethodSignatureInstance templateInstance;
public IEnumerable<IMethod> BaseMethods => templateInstance.BaseMethods.Value;
public bool IsConstructor => templateInstance.IsConstructor;
public IEnumerable<IParameter> Parameters => templateInstance.Parameters.Value;
public IType ReturnType => templateInstance.ReturnType.Value;
public override bool IsStatic => templateInstance.Template.IsStatic;
public IEnumerable<IGenericParameter> GenericParameters => Enumerable.Empty<IGenericParameter>();
public override AttributeMap Attributes => templateInstance.Attributes.Value;
public override UnqualifiedName Name => templateInstance.Name;
/// <summary>
/// Gets this method's parent method: a method defined in a base class
/// which is overriden by this method.
/// </summary>
/// <returns>The parent method.</returns>
public LLVMMethod ParentMethod { get; private set; }
public IMethod Build()
{
return this;
}
public ICodeGenerator GetBodyGenerator()
{
return codeGenerator;
}
public void Initialize()
{
this.codeGenerator = new LLVMCodeGenerator(this);
ParentMethod = GetParentMethod(this);
if (ParentMethod == this
&& this.GetIsVirtual()
&& !DeclaringType.GetIsInterface())
{
ParentType.RelativeVTable.CreateRelativeSlot(this);
}
}
public void SetMethodBody(ICodeBlock Body)
{
this.body = (CodeBlock)Body;
}
/// <summary>
/// Writes this method definitions to the given module.
/// </summary>
/// <param name="Module">The module to populate.</param>
public void Emit(LLVMModuleBuilder Module)
{
if (this.GetRecursiveGenericParameters().Any<IType>())
{
throw new NotSupportedException("LLVM methods do not support generic parameters");
}
if (!DeclaringType.GetIsInterface()
&& !this.GetIsAbstract())
{
var func = Module.Declare(this);
func.SetLinkage(Linkage);
var methodBody = this.body;
if (methodBody == null
&& this.HasAttribute(
PrimitiveAttributes.Instance.RuntimeImplementedAttribute.AttributeType))
{
// Auto-implement runtime-implemented methods here.
methodBody = (CodeBlock)AutoImplement().Emit(codeGenerator);
}
if (methodBody != null)
{
// Generate the method body.
var bodyBuilder = new FunctionBodyBuilder(Module, func);
var entryPointBuilder = bodyBuilder.AppendBasicBlock("entry");
entryPointBuilder = codeGenerator.Prologue.Emit(entryPointBuilder);
var codeGen = methodBody.Emit(entryPointBuilder);
BuildUnreachable(codeGen.BasicBlock.Builder);
}
}
foreach (var iface in allInterfaceImpls.Value)
{
Module.GetInterfaceStub(iface).Implement(ParentType, this);
}
}
/// <summary>
/// Auto-implements this method.
/// </summary>
private IStatement AutoImplement()
{
var delegateAttribute = ParentType.GetAttribute(
MethodType.DelegateAttributeType) as IntrinsicAttribute;
string methodName = PreMangledName.Unmangle(Name).ToString();
var parameters = this.GetParameters();
if (delegateAttribute != null
&& delegateAttribute.Arguments[0].GetValue<string>() == methodName)
{
// Implement this method using a simple invocation expression.
var args = new IExpression[parameters.Length];
for (int i = 0; i < args.Length; i++)
{
args[i] = new ArgumentVariable(parameters[i], i).CreateGetExpression();
}
return new ReturnStatement(
new InvocationExpression(
new ReinterpretCastExpression(
new ThisVariable(DeclaringType).CreateGetExpression(),
MethodType.Create(this)),
args));
}
else if (methodName == "LoadDelegateHasContextInternal"
&& IsStatic
&& ReturnType == PrimitiveTypes.Boolean
&& parameters.Length == 1)
{
return new ReturnStatement(
LLVMCodeGenerator.ToExpression(
new UnaryBlock(
codeGenerator,
(CodeBlock)new ArgumentVariable(parameters[0], 0)
.CreateGetExpression()
.Emit(codeGenerator),
PrimitiveTypes.Boolean,
DelegateBlock.BuildLoadHasContext)));
}
else if (methodName == "LoadDelegateFunctionPointerInternal"
&& IsStatic
&& ReturnType.GetIsPointer()
&& parameters.Length == 1)
{
return new ReturnStatement(
LLVMCodeGenerator.ToExpression(
new UnaryBlock(
codeGenerator,
(CodeBlock)new ArgumentVariable(parameters[0], 0)
.CreateGetExpression()
.Emit(codeGenerator),
ReturnType,
DelegateBlock.BuildLoadFunctionPointer)));
}
else if (methodName == "CompareExchange"
&& IsStatic
&& parameters.Length == 3)
{
return new ReturnStatement(
LLVMCodeGenerator.ToExpression(
new CompareExchangeBlock(
(CodeBlock)new ArgumentVariable(parameters[0], 0)
.CreateGetExpression()
.Emit(codeGenerator),
(CodeBlock)new ArgumentVariable(parameters[1], 1)
.CreateGetExpression()
.Emit(codeGenerator),
(CodeBlock)new ArgumentVariable(parameters[2], 2)
.CreateGetExpression()
.Emit(codeGenerator),
codeGenerator)));
}
else if (methodName.StartsWith("AtomicRMW")
&& IsStatic
&& parameters.Length == 2)
{
return new ReturnStatement(
LLVMCodeGenerator.ToExpression(
new ReadModifyWriteBlock(
(CodeBlock)new ArgumentVariable(parameters[0], 0)
.CreateGetExpression()
.Emit(codeGenerator),
(CodeBlock)new ArgumentVariable(parameters[1], 1)
.CreateGetExpression()
.Emit(codeGenerator),
ReadModifyWriteBlock.ParseOperator(
methodName.Substring("AtomicRMW".Length)),
codeGenerator)));
}
else
{
throw new NotSupportedException(
"Runtime doesn't know how to implement method '" +
this.FullName.ToString() + "'.");
}
}
private HashSet<LLVMMethod> LookupAllInterfaceImpls()
{
var results = new HashSet<LLVMMethod>();
foreach (var baseMethod in BaseMethods)
{
if (baseMethod is LLVMMethod)
{
if (baseMethod.DeclaringType.GetIsInterface())
{
results.Add((LLVMMethod)baseMethod);
}
else
{
results.UnionWith(((LLVMMethod)baseMethod).allInterfaceImpls.Value);
}
}
}
return results;
}
private static LLVMMethod GetParentMethod(LLVMMethod Method)
{
var result = Method;
foreach (var baseMethod in Method.BaseMethods)
{
if (baseMethod is LLVMMethod && !baseMethod.DeclaringType.GetIsInterface())
{
result = (LLVMMethod)baseMethod;
break;
}
}
return result;
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="DependencyObject.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Avalonia
{
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Data;
using Avalonia.Media;
using Avalonia.Threading;
public class DependencyObject : DispatcherObject, IObservableDependencyObject
{
private static Dictionary<Type, Dictionary<string, DependencyProperty>> propertyDeclarations =
new Dictionary<Type, Dictionary<string, DependencyProperty>>();
private Dictionary<DependencyProperty, object> properties =
new Dictionary<DependencyProperty, object>();
private Dictionary<DependencyProperty, BindingExpressionBase> propertyBindings =
new Dictionary<DependencyProperty, BindingExpressionBase>();
private Dictionary<string, List<DependencyPropertyChangedEventHandler>> propertyChangedHandlers =
new Dictionary<string, List<DependencyPropertyChangedEventHandler>>();
private DependencyObject dependencyParent;
public bool IsSealed
{
get { return false; }
}
public DependencyObjectType DependencyObjectType
{
get { return DependencyObjectType.FromSystemType(this.GetType()); }
}
internal DependencyObject DependencyParent
{
get
{
return this.dependencyParent;
}
set
{
if (this.dependencyParent != value)
{
DependencyProperty[] inheriting = this.GetInheritingProperties().ToArray();
Dictionary<DependencyProperty, object> oldValues = new Dictionary<DependencyProperty, object>();
foreach (DependencyProperty dp in inheriting)
{
oldValues[dp] = this.GetValue(dp);
}
this.dependencyParent = value;
foreach (DependencyProperty dp in inheriting)
{
object oldValue = oldValues[dp];
object newValue = this.GetValue(dp);
if (!this.AreEqual(oldValues[dp], newValue))
{
DependencyPropertyChangedEventArgs e = new DependencyPropertyChangedEventArgs(
dp,
oldValue,
newValue);
this.OnPropertyChanged(e);
}
}
}
}
}
void IObservableDependencyObject.AttachPropertyChangedHandler(
string propertyName,
DependencyPropertyChangedEventHandler handler)
{
List<DependencyPropertyChangedEventHandler> handlers;
if (!this.propertyChangedHandlers.TryGetValue(propertyName, out handlers))
{
handlers = new List<DependencyPropertyChangedEventHandler>();
this.propertyChangedHandlers.Add(propertyName, handlers);
}
handlers.Add(handler);
}
void IObservableDependencyObject.RemovePropertyChangedHandler(
string propertyName,
DependencyPropertyChangedEventHandler handler)
{
List<DependencyPropertyChangedEventHandler> handlers;
if (this.propertyChangedHandlers.TryGetValue(propertyName, out handlers))
{
handlers.Remove(handler);
}
}
public void ClearValue(DependencyProperty dp)
{
if (this.IsSealed)
{
throw new InvalidOperationException("Cannot manipulate property values on a sealed DependencyObject");
}
this.properties.Remove(dp);
}
public void ClearValue(DependencyPropertyKey key)
{
this.ClearValue(key.DependencyProperty);
}
public void CoerceValue(DependencyProperty dp)
{
PropertyMetadata pm = dp.GetMetadata(this);
if (pm.CoerceValueCallback != null)
{
pm.CoerceValueCallback(this, this.GetValue(dp));
}
}
public LocalValueEnumerator GetLocalValueEnumerator()
{
return new LocalValueEnumerator(this.properties);
}
public object GetValue(DependencyProperty dp)
{
object val;
if (!this.properties.TryGetValue(dp, out val))
{
val = this.GetDefaultValue(dp);
if (val == null && dp.PropertyType.IsValueType)
{
val = Activator.CreateInstance(dp.PropertyType);
}
}
return val;
}
public void InvalidateProperty(DependencyProperty dp)
{
BindingExpressionBase binding;
if (this.propertyBindings.TryGetValue(dp, out binding))
{
object oldValue = this.GetValue(dp);
object newValue = binding.GetValue();
this.SetValueInternal(dp, oldValue, newValue);
}
}
public object ReadLocalValue(DependencyProperty dp)
{
object val = this.properties[dp];
return val == null ? DependencyProperty.UnsetValue : val;
}
public void SetBinding(DependencyProperty dp, string path)
{
this.SetBinding(dp, new Binding(path));
}
public void SetBinding(DependencyProperty dp, BindingBase binding)
{
Binding b = binding as Binding;
if (b == null)
{
throw new NotSupportedException("Unsupported binding type.");
}
this.SetBinding(dp, b);
}
[AvaloniaSpecific]
public BindingExpression SetBinding(DependencyProperty dp, Binding binding)
{
PropertyPathParser pathParser = new PropertyPathParser();
BindingExpression expression = new BindingExpression(pathParser, this, dp, binding);
object oldValue = this.GetValue(dp);
object newValue = expression.GetValue();
this.propertyBindings.Add(dp, expression);
this.SetValueInternal(dp, oldValue, newValue);
return expression;
}
public void SetValue(DependencyProperty dp, object value)
{
if (this.IsSealed)
{
throw new InvalidOperationException("Cannot manipulate property values on a sealed DependencyObject.");
}
if (value != DependencyProperty.UnsetValue && !dp.IsValidType(value))
{
throw new ArgumentException("Value is not of the correct type for this DependencyProperty.");
}
if (dp.ValidateValueCallback != null && !dp.ValidateValueCallback(value))
{
throw new Exception("Value does not validate.");
}
object oldValue = this.GetValue(dp);
this.propertyBindings.Remove(dp);
this.SetValueInternal(dp, oldValue, value);
}
public void SetValue(DependencyPropertyKey key, object value)
{
this.SetValue(key.DependencyProperty, value);
}
internal static IEnumerable<DependencyProperty> GetAllProperties(Type type)
{
Type t = type;
while (t != null)
{
Dictionary<string, DependencyProperty> list;
if (propertyDeclarations.TryGetValue(t, out list))
{
foreach (DependencyProperty dp in list.Values)
{
yield return dp;
}
}
t = t.BaseType;
}
}
internal static DependencyProperty GetPropertyFromName(Type type, string name)
{
Dictionary<string, DependencyProperty> list;
DependencyProperty result;
Type t = type;
while (t != null)
{
if (propertyDeclarations.TryGetValue(t, out list))
{
if (list.TryGetValue(name, out result))
{
return result;
}
}
t = t.BaseType;
}
throw new KeyNotFoundException(string.Format(
"Dependency property '{0}' could not be found on type '{1}'.",
name,
type.FullName));
}
internal static void Register(Type t, DependencyProperty dp)
{
Dictionary<string, DependencyProperty> typeDeclarations;
if (!propertyDeclarations.TryGetValue(t, out typeDeclarations))
{
typeDeclarations = new Dictionary<string, DependencyProperty>();
propertyDeclarations.Add(t, typeDeclarations);
}
if (!typeDeclarations.ContainsKey(dp.Name))
{
typeDeclarations[dp.Name] = dp;
}
else
{
throw new ArgumentException("A property named " + dp.Name + " already exists on " + t.Name);
}
}
internal bool IsRegistered(Type t, DependencyProperty dp)
{
return GetAllProperties(t).Contains(dp);
}
internal bool IsUnset(DependencyProperty dependencyProperty)
{
return !this.properties.ContainsKey(dependencyProperty);
}
protected virtual void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
PropertyMetadata pm = e.Property.GetMetadata(this);
if (pm != null)
{
if (pm.PropertyChangedCallback != null)
{
pm.PropertyChangedCallback(this, e);
}
}
List<DependencyPropertyChangedEventHandler> handlers;
if (this.propertyChangedHandlers.TryGetValue(e.Property.Name, out handlers))
{
foreach (var handler in handlers.ToArray())
{
handler(this, e);
}
}
FrameworkPropertyMetadata metadata = e.Property.GetMetadata(this) as FrameworkPropertyMetadata;
UIElement uiElement = this as UIElement;
if (metadata != null && uiElement != null)
{
if (metadata.AffectsArrange)
{
uiElement.InvalidateArrange();
}
if (metadata.AffectsMeasure)
{
uiElement.InvalidateMeasure();
}
if (metadata.AffectsRender)
{
uiElement.InvalidateVisual();
}
if (metadata.Inherits)
{
foreach (DependencyObject child in VisualTreeHelper.GetChildren(this))
{
child.InheritedValueChanged(e);
}
}
}
}
protected virtual bool ShouldSerializeProperty(DependencyProperty dp)
{
throw new NotImplementedException();
}
private bool AreEqual(object a, object b)
{
return object.Equals(a, b);
}
private object GetDefaultValue(DependencyProperty dp)
{
PropertyMetadata metadata = dp.GetMetadata(this);
FrameworkPropertyMetadata frameworkMetadata = metadata as FrameworkPropertyMetadata;
object result = metadata.DefaultValue;
if (frameworkMetadata != null && frameworkMetadata.Inherits)
{
if (this.dependencyParent != null)
{
result = this.dependencyParent.GetValue(dp);
}
}
return result;
}
private IEnumerable<DependencyProperty> GetInheritingProperties()
{
foreach (DependencyProperty dp in GetAllProperties(this.GetType()))
{
FrameworkPropertyMetadata metadata =
dp.GetMetadata(this.GetType()) as FrameworkPropertyMetadata;
if (metadata != null && metadata.Inherits)
{
yield return dp;
}
}
}
private void InheritedValueChanged(DependencyPropertyChangedEventArgs e)
{
if (this.IsRegistered(this.GetType(), e.Property) && !this.properties.ContainsKey(e.Property))
{
this.OnPropertyChanged(e);
}
else
{
foreach (DependencyObject child in VisualTreeHelper.GetChildren(this))
{
child.InheritedValueChanged(e);
}
}
}
private void SetValueInternal(DependencyProperty dp, object oldValue, object newValue)
{
PropertyMetadata metadata = dp.GetMetadata(this);
if (metadata.CoerceValueCallback != null)
{
newValue = metadata.CoerceValueCallback(this, newValue);
}
if (newValue != DependencyProperty.UnsetValue && dp.IsValidValue(newValue))
{
this.properties[dp] = newValue;
}
else
{
this.properties.Remove(dp);
newValue = this.GetValue(dp);
}
if (!this.AreEqual(oldValue, newValue))
{
this.OnPropertyChanged(new DependencyPropertyChangedEventArgs(dp, oldValue, newValue));
}
}
}
}
| |
//
// Literal.cs
//
// Author:
// Gabriel Burt <gabriel.burt@gmail.com>
// Stephane Delcroix <stephane@delcroix.org>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2013 Stephen Shaw
// Copyright (C) 2007-2009 Novell, Inc.
// Copyright (C) 2007 Gabriel Burt
// Copyright (C) 2007-2009 Stephane Delcroix
//
// 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.
//
// This has to do with Finding photos based on tags
// http://mail.gnome.org/archives/f-spot-list/2005-November/msg00053.html
// http://bugzilla-attachments.gnome.org/attachment.cgi?id=54566
using System;
using System.Collections.Generic;
using System.Text;
using Mono.Unix;
using Gtk;
using Gdk;
using FSpot.Core;
namespace FSpot.Query
{
// TODO rename to TagLiteral?
public class Literal : AbstractLiteral
{
public Literal (Tag tag) : this (null, tag, null)
{
}
public Literal (Term parent, Tag tag, Literal after) : base (parent, after)
{
Tag = tag;
}
static Literal ()
{
FocusedLiterals = new List<Literal> ();
}
#region Properties
public static List<Literal> FocusedLiterals { get; set; }
public Tag Tag { get; private set; }
public override bool IsNegated {
get {
return is_negated;
}
set {
if (is_negated == value)
return;
is_negated = value;
NormalIcon = null;
NegatedIcon = null;
Update ();
if (NegatedToggled != null)
NegatedToggled (this);
}
}
Pixbuf NegatedIcon {
get {
if (negated_icon != null)
return negated_icon;
if (NormalIcon == null)
return null;
negated_icon = NormalIcon.Copy ();
int offset = ICON_SIZE - overlay_size;
NegatedOverlay.Composite (negated_icon, offset, 0, overlay_size, overlay_size, offset, 0, 1.0, 1.0, InterpType.Bilinear, 200);
return negated_icon;
}
set {
negated_icon = null;
}
}
public Widget Widget {
get {
if (widget != null)
return widget;
container = new EventBox ();
box = new HBox ();
handle_box = new LiteralBox ();
handle_box.BorderWidth = 1;
label = new Label (System.Web.HttpUtility.HtmlEncode (Tag.Name));
label.UseMarkup = true;
image = new Gtk.Image (NormalIcon);
container.CanFocus = true;
container.KeyPressEvent += KeyHandler;
container.ButtonPressEvent += HandleButtonPress;
container.ButtonReleaseEvent += HandleButtonRelease;
container.EnterNotifyEvent += HandleMouseIn;
container.LeaveNotifyEvent += HandleMouseOut;
//new PopupManager (new LiteralPopup (container, this));
// Setup this widget as a drag source (so tags can be moved after being placed)
container.DragDataGet += HandleDragDataGet;
container.DragBegin += HandleDragBegin;
container.DragEnd += HandleDragEnd;
Gtk.Drag.SourceSet (container, Gdk.ModifierType.Button1Mask | Gdk.ModifierType.Button3Mask,
tag_target_table, DragAction.Copy | DragAction.Move);
// Setup this widget as a drag destination (so tags can be added to our parent's Term)
container.DragDataReceived += HandleDragDataReceived;
container.DragMotion += HandleDragMotion;
container.DragLeave += HandleDragLeave;
Gtk.Drag.DestSet (container, DestDefaults.All, tag_dest_target_table,
DragAction.Copy | DragAction.Move);
container.TooltipText = Tag.Name;
label.Show ();
image.Show ();
if (Tag.Icon == null)
handle_box.Add (label);
else
handle_box.Add (image);
handle_box.Show ();
box.Add (handle_box);
box.Show ();
container.Add (box);
widget = container;
return widget;
}
}
Pixbuf NormalIcon {
get {
if (normal_icon != null)
return normal_icon;
Pixbuf scaled = null;
scaled = Tag.Icon;
for (Category category = Tag.Category; category != null && scaled == null; category = category.Category) {
scaled = category.Icon;
}
if (scaled == null)
return null;
if (scaled.Width != ICON_SIZE)
scaled = scaled.ScaleSimple (ICON_SIZE, ICON_SIZE, InterpType.Bilinear);
normal_icon = scaled;
return normal_icon;
}
set {
normal_icon = null;
}
}
#endregion
#region Methods
public void Update ()
{
// Clear out the old icons
normal_icon = null;
negated_icon = null;
if (IsNegated) {
widget.TooltipText = String.Format (Catalog.GetString ("Not {0}"), Tag.Name);
label.Text = "<s>" + System.Web.HttpUtility.HtmlEncode (Tag.Name) + "</s>";
image.Pixbuf = NegatedIcon;
} else {
widget.TooltipText = Tag.Name;
label.Text = System.Web.HttpUtility.HtmlEncode (Tag.Name);
image.Pixbuf = NormalIcon;
}
label.UseMarkup = true;
// Show the icon unless it's null
if (Tag.Icon == null && container.Children [0] == image) {
container.Remove (image);
container.Add (label);
} else if (Tag.Icon != null && container.Children [0] == label) {
container.Remove (label);
container.Add (image);
}
if (isHoveredOver && image.Pixbuf != null) {
// Brighten the image slightly
Pixbuf brightened = image.Pixbuf.Copy ();
image.Pixbuf.SaturateAndPixelate (brightened, 1.85f, false);
//Pixbuf brightened = PixbufUtils.Glow (image.Pixbuf, .6f);
image.Pixbuf = brightened;
}
}
public void RemoveSelf ()
{
if (Removing != null)
Removing (this);
if (Parent != null)
Parent.Remove (this);
if (Removed != null)
Removed (this);
}
public override string SqlCondition ()
{
var ids = new StringBuilder (Tag.Id.ToString ());
var category = Tag as Category;
if (category != null) {
var tags = new List<Tag> ();
category.AddDescendentsTo (tags);
foreach (var t in tags)
{
ids.Append (", " + t.Id);
}
}
return String.Format (
"id {0}IN (SELECT photo_id FROM photo_tags WHERE tag_id IN ({1}))",
(IsNegated ? "NOT " : String.Empty), ids);
}
public override Gtk.Widget SeparatorWidget ()
{
return new Label ("ERR");
}
static Pixbuf NegatedOverlay {
get {
if (negated_overlay == null) {
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetCallingAssembly ();
negated_overlay = new Pixbuf (assembly.GetManifestResourceStream ("f-spot-not.png"));
negated_overlay = negated_overlay.ScaleSimple (overlay_size, overlay_size, InterpType.Bilinear);
}
return negated_overlay;
}
}
public static void RemoveFocusedLiterals ()
{
if (focusedLiterals != null)
foreach (Literal literal in focusedLiterals) {
literal.RemoveSelf ();
}
}
#endregion
#region Handlers
void KeyHandler (object o, KeyPressEventArgs args)
{
args.RetVal = false;
switch (args.Event.Key) {
case Gdk.Key.Delete:
RemoveFocusedLiterals ();
args.RetVal = true;
return;
}
}
void HandleButtonPress (object o, ButtonPressEventArgs args)
{
args.RetVal = true;
switch (args.Event.Type) {
case EventType.TwoButtonPress:
if (args.Event.Button == 1)
IsNegated = !IsNegated;
else
args.RetVal = false;
return;
case EventType.ButtonPress:
Widget.GrabFocus ();
if (args.Event.Button == 1) {
// TODO allow multiple selection of literals so they can be deleted, modified all at once
//if ((args.Event.State & ModifierType.ControlMask) != 0) {
//}
} else if (args.Event.Button == 3) {
var popup = new LiteralPopup ();
popup.Activate (args.Event, this);
}
return;
default:
args.RetVal = false;
return;
}
}
void HandleButtonRelease (object o, ButtonReleaseEventArgs args)
{
args.RetVal = true;
switch (args.Event.Type) {
case EventType.TwoButtonPress:
args.RetVal = false;
return;
case EventType.ButtonPress:
if (args.Event.Button == 1) {
}
return;
default:
args.RetVal = false;
return;
}
}
void HandleMouseIn (object o, EnterNotifyEventArgs args)
{
isHoveredOver = true;
Update ();
}
void HandleMouseOut (object o, LeaveNotifyEventArgs args)
{
isHoveredOver = false;
Update ();
}
void HandleDragDataGet (object sender, DragDataGetArgs args)
{
args.RetVal = true;
if (args.Info == DragDropTargets.TagListEntry.Info || args.Info == DragDropTargets.TagQueryEntry.Info) {
// FIXME: do really write data
Byte [] data = Encoding.UTF8.GetBytes (String.Empty);
Atom [] targets = args.Context.Targets;
args.SelectionData.Set (targets [0], 8, data, data.Length);
return;
}
// Drop cancelled
args.RetVal = false;
foreach (Widget w in hiddenWidgets) {
w.Visible = true;
}
focusedLiterals = null;
}
void HandleDragBegin (object sender, DragBeginArgs args)
{
Gtk.Drag.SetIconPixbuf (args.Context, image.Pixbuf, 0, 0);
focusedLiterals.Add (this);
// Hide the tag and any separators that only exist because of it
container.Visible = false;
hiddenWidgets.Add (container);
foreach (Widget w in LogicWidget.Box.HangersOn (this)) {
hiddenWidgets.Add (w);
w.Visible = false;
}
}
void HandleDragEnd (object sender, DragEndArgs args)
{
// Remove any literals still marked as focused, because
// the user is throwing them away.
RemoveFocusedLiterals ();
focusedLiterals = new List<Literal> ();
args.RetVal = true;
}
void HandleDragDataReceived (object o, DragDataReceivedArgs args)
{
args.RetVal = true;
if (args.Info == DragDropTargets.TagListEntry.Info) {
if (TagsAdded != null)
TagsAdded (args.SelectionData.GetTagsData (), Parent, this);
return;
}
if (args.Info == DragDropTargets.TagQueryEntry.Info) {
if (! focusedLiterals.Contains (this))
if (LiteralsMoved != null)
LiteralsMoved (focusedLiterals, Parent, this);
// Unmark the literals as focused so they don't get nixed
focusedLiterals = null;
}
}
bool preview = false;
Gtk.Widget preview_widget;
void HandleDragMotion (object o, DragMotionArgs args)
{
if (preview)
return;
if (preview_widget == null) {
preview_widget = new Gtk.Label (" | ");
box.Add (preview_widget);
}
preview_widget.Show ();
}
void HandleDragLeave (object o, EventArgs args)
{
preview = false;
preview_widget.Hide ();
}
public void HandleToggleNegatedCommand (object o, EventArgs args)
{
IsNegated = !IsNegated;
}
public void HandleRemoveCommand (object o, EventArgs args)
{
RemoveSelf ();
}
public void HandleAttachTagCommand (Tag t)
{
if (AttachTag != null)
AttachTag (t, Parent, this);
}
public void HandleRequireTag (object sender, EventArgs args)
{
if (RequireTag != null)
RequireTag (new[] {this.Tag});
}
public void HandleUnRequireTag (object sender, EventArgs args)
{
if (UnRequireTag != null)
UnRequireTag (new[] {this.Tag});
}
const int ICON_SIZE = 24;
const int overlay_size = (int)(.40 * ICON_SIZE);
static readonly TargetEntry[] tag_target_table =
{ DragDropTargets.TagQueryEntry };
static readonly TargetEntry[] tag_dest_target_table =
{
DragDropTargets.TagListEntry,
DragDropTargets.TagQueryEntry
};
static List<Literal> focusedLiterals = new List<Literal> ();
static readonly List<Widget> hiddenWidgets = new List<Widget> ();
Gtk.Container container;
LiteralBox handle_box;
Gtk.Box box;
Gtk.Image image;
Gtk.Label label;
Pixbuf normal_icon;
//EventBox widget;
Widget widget;
Pixbuf negated_icon;
static Pixbuf negated_overlay;
bool isHoveredOver = false;
public delegate void NegatedToggleHandler (Literal group);
public event NegatedToggleHandler NegatedToggled;
public delegate void RemovingHandler (Literal group);
public event RemovingHandler Removing;
public delegate void RemovedHandler (Literal group);
public event RemovedHandler Removed;
public delegate void TagsAddedHandler (Tag[] tags,Term parent,Literal after);
public event TagsAddedHandler TagsAdded;
public delegate void AttachTagHandler (Tag tag,Term parent,Literal after);
public event AttachTagHandler AttachTag;
public delegate void TagRequiredHandler (Tag[] tags);
public event TagRequiredHandler RequireTag;
public delegate void TagUnRequiredHandler (Tag[] tags);
public event TagUnRequiredHandler UnRequireTag;
public delegate void LiteralsMovedHandler (List<Literal> literals,Term parent,Literal after);
public event LiteralsMovedHandler LiteralsMoved;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
// Copyright (c) 2006, 2007 by Hugh Pyle, inguzaudio.com
// WAV file reader based originally on Garbe.Sound
namespace DSPUtil
{
public enum WaveFormat
{
// The only types of data we understand are...
ANY = 0, // Pseudo-type, means we don't know
PCM = 1,
ADPCM = 2,
IEEE_FLOAT = 3,
EXTENSIBLE = 65534,
INTERNAL_DOUBLE = 65533 // Our invention, 64-bit doubles
}
public enum SpeakerChannelMask
{
none = 0,
stereo = 0x3,
itu51 = 0x3F,
FRONT_LEFT = 0x1,
FRONT_RIGHT = 0x2,
FRONT_CENTER = 0x4,
LOW_FREQUENCY = 0x8,
BACK_LEFT = 0x10,
BACK_RIGHT = 0x20,
FRONT_LEFT_OF_CENTER = 0x40,
FRONT_RIGHT_OF_CENTER = 0x80,
BACK_CENTER = 0x100,
SIDE_LEFT = 0x200,
SIDE_RIGHT = 0x400,
TOP_CENTER = 0x800,
TOP_FRONT_LEFT = 0x1000,
TOP_FRONT_CENTER = 0x2000,
TOP_FRONT_RIGHT = 0x4000,
TOP_BACK_LEFT = 0x8000,
TOP_BACK_CENTER = 0x10000,
TOP_BACK_RIGHT = 0x20000,
/*RESERVED = 0x80000000*/
}
public class WaveFormatEx
{
public static WaveFormatEx PCM = new WaveFormatEx("00000001-0000-0010-8000-00aa00389b71");
public static WaveFormatEx IEEE_FLOAT = new WaveFormatEx("00000003-0000-0010-8000-00aa00389b71");
public static WaveFormatEx AMBISONIC_B_FORMAT_PCM = new WaveFormatEx("00000001-0721-11d3-8644-C8C1CA000000");
public static WaveFormatEx AMBISONIC_B_FORMAT_IEEE_FLOAT = new WaveFormatEx("00000003-0721-11d3-8644-C8C1CA000000");
public Guid guid;
public WaveFormatEx(Guid g)
{
guid = g;
}
public WaveFormatEx(byte[] g)
{
guid = new Guid(g);
}
public WaveFormatEx(String g)
{
guid = new Guid(g);
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
return (((WaveFormatEx)obj).guid.Equals(guid));
}
public override int GetHashCode()
{
return guid.GetHashCode();
}
public override string ToString()
{
return guid.ToString();
}
}
/// <summary> Read a wave file </summary>
[Serializable]
public sealed class WaveReader : SoundObj /*, ISampleBuffer */
{
private bool _ok;
private FileStream fs;
private BinaryReader _rdr;
private Stream bs;
private string _filename;
private string _riff;
private uint _length;
private string _wave;
private string _format;
private uint _size;
private WaveFormat _audioFormat;
private WaveFormatEx _formatEx;
private uint _byteRate;
private ushort _blockAlign;
private ushort _bitsPerSample;
private bool _bigEndian = false;
private bool _isSPDIF = false;
private string _data;
private uint _dataSize;
private uint _channelMask = 0x3; // default to stereo, unless WAVEFORMATEXTENSIBLE says otherwise
private long _pos; // position relative to start of data
private long _max; // maximum position (number of samples in stream), or uint.MaxValue for an endless stream
private long _seekpos; // byte position of the first data
private ISample _first;
private bool _moreThanFirst;
private ISample _current;
// Buffers for ISampleBuffer
/*
private ISample[] _buff;
private int _bufflen;
private Complex[][] _cbuff;
private int _cbufflen;
*/
private const double _scale8 = 1 / 128f;
private const double _scale16 = 1 / 32768f;
private const double _scale24 = 1 / 8388608f;
private const double _scale32 = 1 / 2147483648f;
#region Constructors
/// <summary> Read a wave file </summary>
/// <param name="fileName">Name of the wave file</param>
public WaveReader(string fileName)
{
OpenFile(fileName);
ReadWaveHeader(WaveFormat.ANY, true);
ReadSPDIF();
}
public WaveReader(string fileName, TimeSpan startTime)
{
OpenFile(fileName);
ReadWaveHeader(WaveFormat.ANY, true);
ReadSPDIF();
SkipToStart(startTime);
}
public WaveReader(string fileName, WaveFormat format)
{
OpenFile(fileName);
_audioFormat = format;
ReadWaveHeader(format, true);
ReadSPDIF();
}
public WaveReader(string fileName, WaveFormat format, ushort bitsPerSample, ushort numChannels)
{
// To read raw
OpenFile(fileName);
_audioFormat = format;
ReadWaveHeader(format, false);
NumChannels = numChannels;
_bitsPerSample = bitsPerSample;
ReadSPDIF();
}
public WaveReader(string fileName, WaveFormat format, ushort bitsPerSample, ushort numChannels, TimeSpan startTime)
{
// To read raw
OpenFile(fileName);
_audioFormat = format;
ReadWaveHeader(format, false);
NumChannels = numChannels;
_bitsPerSample = bitsPerSample;
ReadSPDIF();
SkipToStart(startTime);
}
public WaveReader(Stream input)
{
//fs = null;
//bs = null;
_rdr = new BinaryReader(input);
ReadWaveHeader(WaveFormat.ANY, true);
ReadSPDIF();
}
public WaveReader(Stream input, WaveFormat format)
{
_audioFormat = format;
//fs = null;
//bs = null;
_rdr = new BinaryReader(input);
ReadWaveHeader(format, true);
ReadSPDIF();
}
private void OpenFile(string fileName)
{
_filename = fileName;
if (fileName == null || fileName=="-")
{
// use stdin
//fs = null;
//bs = null;
// Trace.WriteLine("Read stdin");
Stream stdin = System.Console.OpenStandardInput();
bs = new BufferedStream(stdin);
_rdr = new BinaryReader(bs);
}
else if (File.Exists(fileName))
{
// Trace.WriteLine("Read {0}", fileName);
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, true);
bs = new BufferedStream(fs);
_rdr = new BinaryReader(bs);
}
else
{
throw (new FileNotFoundException("File " + fileName + " not found"));
}
}
private void ReadWaveHeader(WaveFormat format, bool expectHeader)
{
_ok = false;
_pos = 0;
// Trace.WriteLine("ReadWaveHeader {0}", format);
if (!expectHeader)
{
// Input file is raw data
_riff = "(no header)";
_length = 0;
_wave = "(no header)";
_format = "(no header)";
_size = 16;
_data = "data";
_dataSize = 0;
_max = uint.MaxValue;
_audioFormat = format;
// Assume defaults, they can be overridden later
NumChannels = 2;
SampleRate = 44100;
if (format == WaveFormat.PCM || format == WaveFormat.EXTENSIBLE)
{
// Raw PCM, assume 16 bit 44k1 stereo PCM
_bitsPerSample = 16;
_ok = true;
}
else if (format == WaveFormat.IEEE_FLOAT)
{
// IEEE Float; assume 32 bit 44k1 stereo IEEE_FLOAT
_bitsPerSample = 32;
_ok = true;
}
else if (format == WaveFormat.INTERNAL_DOUBLE)
{
// our 64 bit 44k1 stereo 'double-precision'
_bitsPerSample = 32;
_ok = true;
}
_blockAlign = (ushort)((NumChannels * _bitsPerSample) >> 3);
_byteRate = (uint)(_blockAlign * SampleRate);
return;
}
// Read 'RIFF' (WAV) or 'FORM' (AIFF) tag ///////////////////////////////////////////////
char[] hdr = _rdr.ReadChars(4);
_riff = new string(hdr);
if (_riff != "RIFF" && _riff != "FORM")
{
if (hdr.Length == 0)
{
throw (new Exception("File could not be read: no data."));
}
string x = "";
for (int j = 0; j < hdr.Length; j++)
{
x += String.Format("{0:X} ", (int)hdr[j]);
}
throw (new Exception(String.Format("File is not WAV: no 'RIFF' tag found, instead '{0}'.", x)));
}
// File length
int fileLen = _rdr.ReadInt32();
_length = (uint)fileLen;
// Read Wave //////////////////////////////////////////////
_wave = new string(_rdr.ReadChars(4));
if (_wave != "WAVE" && _wave != "AIFF")
throw (new Exception(String.Format("File is not WAV: no 'WAVE' tag found, instead {0}", _wave)));
if (_wave == "AIFF")
{
// The whole file is big-endian, including lengths in the header
BigEndian = true;
_length = (uint)System.Net.IPAddress.NetworkToHostOrder(fileLen);
}
// Read Format ////////////////////////////////////////////
_format = new string(_rdr.ReadChars(4));
// WMP11-ripped WAV files begin with 'LIST' metadata - even before the format tag.
// AIFF files could have this too (haven't seen it yet).
// Skip any chunks up to the format header.
while (_format.Length > 0 && _format != "fmt " && _format != "COMM")
{
int chunkSize = _rdr.ReadInt32();
if (BigEndian)
chunkSize = System.Net.IPAddress.NetworkToHostOrder(chunkSize);
Trace.WriteLine("Skipping {0} ({1} bytes)", _format, chunkSize);
_rdr.ReadBytes(chunkSize);
_format = new string(_rdr.ReadChars(4));
}
if (_format == "fmt ")
{
// WAV file-format chunk
_size = _rdr.ReadUInt32();
if (_size < 16)
throw (new Exception("File could not be read: don't know how to read 'fmt' size " + _size));
_audioFormat = (WaveFormat)_rdr.ReadUInt16();
if (_audioFormat == WaveFormat.PCM ||
_audioFormat == WaveFormat.ADPCM ||
_audioFormat == WaveFormat.IEEE_FLOAT ||
_audioFormat == WaveFormat.INTERNAL_DOUBLE ||
_audioFormat == WaveFormat.EXTENSIBLE)
{
// // WAVEFORMATEX wFormatTag 2 bytes
NumChannels = _rdr.ReadUInt16(); // WAVEFORMATEX nChannels 2
SampleRate = _rdr.ReadUInt32(); // WAVEFORMATEX nSamplesPerSec 4
_byteRate = _rdr.ReadUInt32(); // WAVEFORMATEX nAvgBytesPerSec 4
_blockAlign = _rdr.ReadUInt16(); // WAVEFORMATEX nBlockAlign 2 (channels * bitspersample / 8)
_bitsPerSample = _rdr.ReadUInt16(); // WAVEFORMATEX wBitsPerSample 2 (the *container* size)
if (_size > 16)
{
uint skip = 16;
if (_audioFormat == WaveFormat.EXTENSIBLE)
{
UInt16 kip = _rdr.ReadUInt16();
UInt16 union = _rdr.ReadUInt16(); // the Samples union, wdc
_channelMask = _rdr.ReadUInt32(); // channel mask
// then the GUID, 16 bytes
_formatEx = new WaveFormatEx(_rdr.ReadBytes(16));
skip = 40;
if (_formatEx.Equals(WaveFormatEx.PCM) || _formatEx.Equals(WaveFormatEx.AMBISONIC_B_FORMAT_PCM))
{
_audioFormat = WaveFormat.PCM;
}
else if (_formatEx.Equals(WaveFormatEx.IEEE_FLOAT) || _formatEx.Equals(WaveFormatEx.AMBISONIC_B_FORMAT_IEEE_FLOAT))
{
_audioFormat = WaveFormat.IEEE_FLOAT;
}
}
// Read and discard the rest of the 'fmt' structure
_rdr.ReadBytes((int)(_size - skip));
}
}
else
{
throw (new Exception("File could not be read: don't know how to read audio format " + _audioFormat));
}
}
else if (_format == "COMM")
{
// AIFF file-format chunk
_size = (uint)System.Net.IPAddress.NetworkToHostOrder(_rdr.ReadInt32());
if (_size < 18)
throw (new Exception("File could not be read: don't know how to read 'COMM' size " + _size));
_audioFormat = WaveFormat.PCM;
NumChannels = (ushort)System.Net.IPAddress.NetworkToHostOrder(_rdr.ReadInt16());
uint numFrames = (uint)System.Net.IPAddress.NetworkToHostOrder(_rdr.ReadInt32()); // number of sample frames
_bitsPerSample = (ushort)System.Net.IPAddress.NetworkToHostOrder(_rdr.ReadInt16());
// SampleRate is 10-byte IEEE_extended format. Don't bother converting that
// properly, just check for good known values (yuk!)
byte[] ext = _rdr.ReadBytes(10);
if (ext[0] == 64 && ext[1] == 14 && ext[2] == 172 && ext[3] == 68)
{
SampleRate = 44100;
}
else if (ext[0] == 64 && ext[1] == 14 && ext[2] == 187 && ext[3] == 128)
{
SampleRate = 48000;
}
else if (ext[0] == 64 && ext[1] == 15 && ext[2] == 187 && ext[3] == 128)
{
SampleRate = 96000;
}
else
{
throw (new Exception("File could not be read: don't know how to interpret sample rate."));
}
_blockAlign = (ushort)((NumChannels * _bitsPerSample) / 8);
_byteRate = (uint)(_blockAlign * SampleRate);
if (_size > 18)
{
// Read and discard the rest of the 'fmt' structure
_rdr.ReadBytes((int)(_size - 18));
}
}
else
{
throw (new Exception(String.Format("File could not be read: no 'fmt' tag found, instead {0}", _format)));
}
// Read Data ///////////////////////////////////////////////
_data = new string(_rdr.ReadChars(4));
while (_data.Length > 0 && _data != "data" && _data != "SSND")
{
// Not a data chunk, ignore
int miscSize = _rdr.ReadInt32();
if (BigEndian)
miscSize = System.Net.IPAddress.NetworkToHostOrder(miscSize);
_rdr.ReadBytes(miscSize);
_data = new string(_rdr.ReadChars(4));
}
// Read the data size
if (BigEndian)
{
_dataSize = (uint)System.Net.IPAddress.NetworkToHostOrder(_rdr.ReadInt32());
}
else
{
_dataSize = _rdr.ReadUInt32();
}
// See if we can read this
if (NumChannels > 0)
{
switch (_audioFormat)
{
case WaveFormat.PCM:
case WaveFormat.EXTENSIBLE:
switch (_bitsPerSample)
{
case 8:
case 16:
case 24:
case 32:
_ok = true;
break;
default:
break;
}
break;
case WaveFormat.IEEE_FLOAT:
switch (_bitsPerSample)
{
case 32:
case 64:
_ok = true;
break;
}
break;
case WaveFormat.INTERNAL_DOUBLE:
switch (_bitsPerSample)
{
case 64:
_ok = true;
break;
}
break;
default:
break;
}
}
if (_ok)
{
_max = (uint)((_dataSize / (_bitsPerSample / 8)) / NumChannels);
if (_dataSize==4294967292)
{
Trace.WriteLine("Wave file: unknown size from header");
_max = uint.MaxValue;
}
if (_max == 0)
{
Trace.WriteLine("Wave file: zero size from header");
_max = uint.MaxValue;
}
}
}
private void ReadSPDIF()
{
if (_ok)
{
byte[] spdif = { 0x72, 0xf8, 0x1f, 0x4e };
if (_rdr.BaseStream.CanSeek)
{
_seekpos = _rdr.BaseStream.Position;
}
// Read the first sample "manually"
// so we can check whether there's a SPDIF or other magic number
// at the beginning of the stream.
int nFirst = (_nc * _bitsPerSample / 8);
byte[] firstBytes = _rdr.ReadBytes(nFirst);
MemoryStream ms = new MemoryStream(firstBytes);
BinaryReader mr = new BinaryReader(ms);
// Save the sample for later use
_first = Next(mr, out _moreThanFirst);
if (firstBytes.Length >= nFirst)
{
// Check whether it's SPDIF-wrapped
_isSPDIF = true;
for (int b = 0; _isSPDIF && b < spdif.Length && b < nFirst; b++)
{
_isSPDIF &= (spdif[b] == firstBytes[b]);
}
}
}
}
private void SkipToStart(TimeSpan ts)
{
if (_ok)
{
// Number of samples = seconds * samplerate
long pos = (long)(ts.TotalSeconds * _sr);
if (pos > 0)
{
if (_rdr.BaseStream.CanSeek)
{
Trace.WriteLine("Skip to time {0} (sample {1})", ts, pos);
_rdr.BaseStream.Seek(_seekpos + (pos * _nc * (_bitsPerSample / 8)), SeekOrigin.Begin);
// remember our new base-position, so Seek() works relative to this
_seekpos = _rdr.BaseStream.Position;
// Read the first sample again (see ReadSPDIF)
int nFirst = (_nc * _bitsPerSample / 8);
byte[] firstBytes = _rdr.ReadBytes(nFirst);
MemoryStream ms = new MemoryStream(firstBytes);
BinaryReader mr = new BinaryReader(ms);
_first = Next(mr, out _moreThanFirst);
}
else
{
// Laboriously skip samples until we reach the right place?
// Bah. TODO. For now we only care about file-input sources, which are seekable.
}
}
}
}
#endregion
// public override void Reset()
// {
// Seek(1);
// }
/// <summary>
/// Seek to position in the data stream
/// </summary>
/// <param name="pos">Sample position, 0-based</param>
private void Seek(long pos)
{
if (_pos != pos)
{
if (!_rdr.BaseStream.CanSeek)
{
string msg = String.Format("Cannot rewind this input stream (from {0} to {1}).", _pos, pos);
throw new NotSupportedException(msg);
}
_rdr.BaseStream.Seek(_seekpos + (pos * _nc * (_bitsPerSample / 8)), SeekOrigin.Begin);
_pos = pos;
}
}
private double NextDouble(BinaryReader rdr)
{
double val = 0;
if (_bigEndian)
{
// For now only handle 16-bit big-endian data
if (_bitsPerSample == 16)
{
short beword = rdr.ReadInt16();
beword = System.Net.IPAddress.NetworkToHostOrder(beword);
val = ((double)beword * _scale16);
}
}
else
{
switch (_bitsPerSample)
{
case 16:
val = ((double)rdr.ReadInt16() * _scale16);
break;
case 8:
val = ((double)rdr.ReadByte() - 128) * _scale8; // 8-bit PCM uses unsigned bytes
break;
case 24:
// Little-endian, signed 24-bit
int a = (int)rdr.ReadUInt16();
int b = (int)rdr.ReadSByte();
int c = (b << 16) + a;
val = ((double)c) * _scale24;
break;
case 32:
if (_audioFormat == WaveFormat.IEEE_FLOAT)
{
val = (double)rdr.ReadSingle();
}
else
{
val = ((double)rdr.ReadInt32()) * _scale32;
}
break;
case 64:
if ((_audioFormat == WaveFormat.IEEE_FLOAT) || (_audioFormat == WaveFormat.INTERNAL_DOUBLE))
{
val = rdr.ReadDouble();
}
else
{
// throw new Exception("64-bit PCM not handled");
val = 0;
}
break;
}
}
return val;
}
private ISample First(out bool more)
{
// Looking for spdif, we cached the first sample (and whether there were more samples after that)
more = _moreThanFirst;
return _first;
}
private ISample This(out bool more)
{
// The current sample
more = (_current != null);
return _current;
}
private ISample Next(BinaryReader rdr, out bool more)
{
try
{
if (_nc == 2)
{
if (_pos < _max)
{
_pos++;
double a = NextDouble(rdr);
double b = NextDouble(rdr);
more = true;
_current = new Sample2(a, b);
}
else
{
more = false;
_current = null;
}
}
else
{
if (_pos < _max)
{
_pos++;
ISample sample = new Sample(_nc);
for (int n = 0; n < _nc; n++)
{
sample[n] = NextDouble(rdr);
}
more = true;
_current = sample;
}
else
{
more = false;
_current = null;
}
}
}
catch (EndOfStreamException)
{
Trace.WriteLine("End of input ({0}) at {1}.", streamName, _pos);
more = false;
_current = null;
}
catch (IOException e)
{
Trace.WriteLine("IO error ({0}) at {1}: {2}", streamName, _pos, e.Message);
more = false;
_current = null;
}
return _current;
}
private string streamName
{
get
{
if (String.IsNullOrEmpty(_filename))
{
return "stream";
}
return Path.GetFileName(_filename);
}
}
/// <summary>
/// Get an iterator for samples
/// </summary>
public override IEnumerator<ISample> Samples
{
get
{
if (!_ok)
{
Trace.WriteLine("WaveReader: Cannot process");
yield break;
}
// Reset();
bool more = true;
long pos = 0;
ISample s = First(out more);
if (s!=null)
{
pos++;
yield return s;
}
while (more)
{
if (_pos != pos)
{
// Someone else moved the stream forward!
// Seek to the right place, please
if (_pos == pos + 1)
{
s = This(out more);
}
else
{
Seek(pos);
s = Next(_rdr, out more);
}
}
else
{
s = Next(_rdr, out more);
}
if (s != null)
{
pos++;
yield return s;
}
}
yield break;
}
}
#region ISampleBuffer implementation
/*
public void Skip(int n, out int nn, out bool moreSamples)
{
Read(n, out nn, out moreSamples);
}
public ISample[] Read(int n, out int nn, out bool moreSamples)
{
moreSamples = true;
int j;
if (_buff == null || _bufflen < n)
{
_buff = new ISample[n];
_bufflen = n;
}
for (j = 0; j < n && moreSamples; j++)
{
_buff[j] = Next(_rdr, out moreSamples);
}
nn = moreSamples ? j : (j - 1);
return _buff;
}
/// <summary>
/// Read, into an array of Complex.
/// Unused elements in the array are guaranteed null.
/// </summary>
/// <param name="n"></param>
/// <param name="nn"></param>
/// <param name="moreSamples"></param>
/// <returns></returns>
public Complex[][] ReadComplex(int n, out int nn, out bool moreSamples)
{
moreSamples = true;
int j = 0;
ushort nc = NumChannels;
if (_cbuff == null || _cbufflen < n)
{
_cbuff = new Complex[nc][];
for (ushort c = 0; c < nc; c++)
{
_cbuff[c] = new Complex[n];
}
_cbufflen = n;
}
else
{
for (ushort c = 0; c < _nc; c++)
{
Array.Clear(_cbuff[c], 0, n);
}
}
for (j = 0; j < n && moreSamples; j++)
{
ISample s = Next(_rdr, out moreSamples);
if (s != null)
{
for (ushort c = 0; c < nc; c++)
{
_cbuff[c][j].Re = s[c];
}
}
}
nn = moreSamples ? j : (j - 1);
return _cbuff;
}
*/
#endregion
/// <summary> Number of iterations expected to do the signal processing == number of samples </summary>
public override int Iterations
{
get { return ((int)_max); }
}
#region Methods
/// <summary> Gets the number of bits per sample of the signal </summary>
public ushort BitsPerSample
{
get { return _bitsPerSample; }
}
/// <summary> Close the wave file </summary>
public void Close()
{
if (_rdr != null) { _rdr.Close(); }
if (bs != null) { bs.Close(); bs = null; }
if (fs != null) { fs.Close(); fs = null; }
}
#endregion
#region Miscellaneous Properties
public bool IsSPDIF
{
get { return _isSPDIF; }
}
// Set big-endian-ness (only useful for raw, since we always read the header as little-endian)
public bool BigEndian
{
set { _bigEndian = value; }
get { return _bigEndian; }
}
/// <summary> Get the RIFF tag </summary>
public string RiffTag
{
get { return _riff; }
}
/// <summary> Get the length tag </summary>
public uint RiffLength
{
get { return _length; }
}
/// <summary> Get the Wave tag </summary>
public string WaveTag
{
get
{ return _wave; }
}
/// <summary> Get the Format tag </summary>
public string FormatTag
{
get
{ return _format; }
}
/// <summary> Get the Size tag </summary>
public uint FormatSize
{
get { return _size; }
}
/// <summary> Get the Audio Format tag </summary>
public WaveFormat Format
{
get { return _audioFormat; }
}
/// <summary> Get the extensible Wave subtype </summary>
public WaveFormatEx FormatEx
{
get { return _formatEx; }
}
/// <summary> Get the Byte Rate tag </summary>
public uint ByteRate
{
get { return _byteRate; }
}
/// <summary> Get the Block Align tag </summary>
public ushort BlockAlign
{
get { return _blockAlign; }
}
/// <summary> Get the Data tag </summary>
public string Data
{
get { return _data; }
}
/// <summary> Get the Data Size tag </summary>
public uint DataSize
{
get { return _dataSize; }
}
/// <summary> Get the channel mask (default to stereo) </summary>
public uint ChannelMask
{
get { return _channelMask; }
}
#endregion
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Linq;
using System.Text;
using Encog.Util;
namespace Encog.ML.Bayesian.Query.Sample
{
/// <summary>
/// A sampling query allows probabilistic queries on a Bayesian network. Sampling
/// works by actually simulating the probabilities using a random number
/// generator. A sample size must be specified. The higher the sample size, the
/// more accurate the probability will be. However, the higher the sampling size,
/// the longer it takes to run the query.
///
/// An enumeration query is more precise than the sampling query. However, the
/// enumeration query will become slow as the size of the Bayesian network grows.
/// Sampling can often be used for a quick estimation of a probability.
/// </summary>
[Serializable]
public class SamplingQuery : BasicQuery
{
/// <summary>
/// The default sample size.
/// </summary>
public const int DefaultSampleSize = 100000;
/// <summary>
/// The number of samples that matched the result the query is looking for.
/// </summary>
private int _goodSamples;
/// <summary>
/// The total number of samples generated. This should match sampleSize at
/// the end of a query.
/// </summary>
private int _totalSamples;
/// <summary>
/// The number of usable samples. This is the set size for the average
/// probability.
/// </summary>
private int _usableSamples;
/// <summary>
/// Construct a sampling query.
/// </summary>
/// <param name="theNetwork">The network that will be queried.</param>
public SamplingQuery(BayesianNetwork theNetwork)
: base(theNetwork)
{
SampleSize = DefaultSampleSize;
}
/// <summary>
/// The sample size.
/// </summary>
public int SampleSize { get; set; }
/// <inheritdoc/>
public override double Probability
{
get { return _goodSamples/(double) _usableSamples; }
}
/// <summary>
/// Obtain the arguments for an event.
/// </summary>
/// <param name="e">The event.</param>
/// <returns>The arguments for that event, based on the other event values.</returns>
private int[] ObtainArgs(BayesianEvent e)
{
var result = new int[e.Parents.Count];
int index = 0;
foreach (BayesianEvent parentEvent in e.Parents)
{
EventState state = GetEventState(parentEvent);
if (!state.IsCalculated)
return null;
result[index++] = state.Value;
}
return result;
}
/// <summary>
/// Set all events to random values, based on their probabilities.
/// </summary>
/// <param name="eventState">The event state.</param>
private void RandomizeEvents(EventState eventState)
{
// first, has this event already been randomized
if (!eventState.IsCalculated)
{
// next, see if we can randomize the event passed
int[] args = ObtainArgs(eventState.Event);
if (args != null)
{
eventState.Randomize(args);
}
}
// randomize children
foreach (BayesianEvent childEvent in eventState.Event.Children)
{
RandomizeEvents(GetEventState(childEvent));
}
}
/// <summary>
/// The number of events that are still uncalculated.
/// </summary>
/// <returns>The uncalculated count.</returns>
private int CountUnCalculated()
{
return Events.Values.Count(state => !state.IsCalculated);
}
/// <inheritdoc/>
public override void Execute()
{
LocateEventTypes();
_usableSamples = 0;
_goodSamples = 0;
_totalSamples = 0;
for (int i = 0; i < SampleSize; i++)
{
Reset();
int lastUncalculated = int.MaxValue;
int uncalculated;
do
{
foreach (EventState state in Events.Values)
{
RandomizeEvents(state);
}
uncalculated = CountUnCalculated();
if (uncalculated == lastUncalculated)
{
throw new BayesianError(
"Unable to calculate all nodes in the graph.");
}
lastUncalculated = uncalculated;
} while (uncalculated > 0);
// System.out.println("Sample:\n" + this.dumpCurrentState());
_totalSamples++;
if (IsNeededEvidence)
{
_usableSamples++;
if (SatisfiesDesiredOutcome)
{
_goodSamples++;
}
}
}
}
/// <summary>
/// The current state as a string.
/// </summary>
/// <returns>The state.</returns>
public String DumpCurrentState()
{
var result = new StringBuilder();
foreach (EventState state in Events.Values)
{
result.Append(state.ToString());
result.Append("\n");
}
return result.ToString();
}
/// <summary>
/// Clone the object.
/// </summary>
/// <returns></returns>
public override IBayesianQuery Clone()
{
return new SamplingQuery(Network);
}
/// <inheritdoc/>
public override String ToString()
{
var result = new StringBuilder();
result.Append("[SamplingQuery: ");
result.Append(Problem);
result.Append("=");
result.Append(Format.FormatPercent(Probability));
result.Append(" ;good/usable=");
result.Append(Format.FormatInteger(_goodSamples));
result.Append("/");
result.Append(Format.FormatInteger(_usableSamples));
result.Append(";totalSamples=");
result.Append(Format.FormatInteger(_totalSamples));
return result.ToString();
}
}
}
| |
using System;
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
[AddComponentMenu("UI/Scroll Rect", 37)]
[SelectionBase]
[ExecuteInEditMode]
[DisallowMultipleComponent]
[RequireComponent(typeof(RectTransform))]
public class ScrollRect : UIBehaviour, IInitializePotentialDragHandler, IBeginDragHandler, IEndDragHandler, IDragHandler, IScrollHandler, ICanvasElement, ILayoutElement, ILayoutGroup
{
public enum MovementType
{
Unrestricted, // Unrestricted movement -- can scroll forever
Elastic, // Restricted but flexible -- can go past the edges, but springs back in place
Clamped, // Restricted movement where it's not possible to go past the edges
}
public enum ScrollbarVisibility
{
Permanent,
AutoHide,
AutoHideAndExpandViewport,
}
[Serializable]
public class ScrollRectEvent : UnityEvent<Vector2> {}
[SerializeField]
private RectTransform m_Content;
public RectTransform content { get { return m_Content; } set { m_Content = value; } }
[SerializeField]
private bool m_Horizontal = true;
public bool horizontal { get { return m_Horizontal; } set { m_Horizontal = value; } }
[SerializeField]
private bool m_Vertical = true;
public bool vertical { get { return m_Vertical; } set { m_Vertical = value; } }
[SerializeField]
private MovementType m_MovementType = MovementType.Elastic;
public MovementType movementType { get { return m_MovementType; } set { m_MovementType = value; } }
[SerializeField]
private float m_Elasticity = 0.1f; // Only used for MovementType.Elastic
public float elasticity { get { return m_Elasticity; } set { m_Elasticity = value; } }
[SerializeField]
private bool m_Inertia = true;
public bool inertia { get { return m_Inertia; } set { m_Inertia = value; } }
[SerializeField]
private float m_DecelerationRate = 0.135f; // Only used when inertia is enabled
public float decelerationRate { get { return m_DecelerationRate; } set { m_DecelerationRate = value; } }
[SerializeField]
private float m_ScrollSensitivity = 1.0f;
public float scrollSensitivity { get { return m_ScrollSensitivity; } set { m_ScrollSensitivity = value; } }
[SerializeField]
private RectTransform m_Viewport;
public RectTransform viewport { get { return m_Viewport; } set { m_Viewport = value; SetDirtyCaching(); } }
[SerializeField]
private Scrollbar m_HorizontalScrollbar;
public Scrollbar horizontalScrollbar
{
get
{
return m_HorizontalScrollbar;
}
set
{
if (m_HorizontalScrollbar)
m_HorizontalScrollbar.onValueChanged.RemoveListener(SetHorizontalNormalizedPosition);
m_HorizontalScrollbar = value;
if (m_HorizontalScrollbar)
m_HorizontalScrollbar.onValueChanged.AddListener(SetHorizontalNormalizedPosition);
SetDirtyCaching();
}
}
[SerializeField]
private Scrollbar m_VerticalScrollbar;
public Scrollbar verticalScrollbar
{
get
{
return m_VerticalScrollbar;
}
set
{
if (m_VerticalScrollbar)
m_VerticalScrollbar.onValueChanged.RemoveListener(SetVerticalNormalizedPosition);
m_VerticalScrollbar = value;
if (m_VerticalScrollbar)
m_VerticalScrollbar.onValueChanged.AddListener(SetVerticalNormalizedPosition);
SetDirtyCaching();
}
}
[SerializeField]
private ScrollbarVisibility m_HorizontalScrollbarVisibility;
public ScrollbarVisibility horizontalScrollbarVisibility { get { return m_HorizontalScrollbarVisibility; } set { m_HorizontalScrollbarVisibility = value; SetDirtyCaching(); } }
[SerializeField]
private ScrollbarVisibility m_VerticalScrollbarVisibility;
public ScrollbarVisibility verticalScrollbarVisibility { get { return m_VerticalScrollbarVisibility; } set { m_VerticalScrollbarVisibility = value; SetDirtyCaching(); } }
[SerializeField]
private float m_HorizontalScrollbarSpacing;
public float horizontalScrollbarSpacing { get { return m_HorizontalScrollbarSpacing; } set { m_HorizontalScrollbarSpacing = value; SetDirty(); } }
[SerializeField]
private float m_VerticalScrollbarSpacing;
public float verticalScrollbarSpacing { get { return m_VerticalScrollbarSpacing; } set { m_VerticalScrollbarSpacing = value; SetDirty(); } }
[SerializeField]
private ScrollRectEvent m_OnValueChanged = new ScrollRectEvent();
public ScrollRectEvent onValueChanged { get { return m_OnValueChanged; } set { m_OnValueChanged = value; } }
// The offset from handle position to mouse down position
private Vector2 m_PointerStartLocalCursor = Vector2.zero;
private Vector2 m_ContentStartPosition = Vector2.zero;
private RectTransform m_ViewRect;
protected RectTransform viewRect
{
get
{
if (m_ViewRect == null)
m_ViewRect = m_Viewport;
if (m_ViewRect == null)
m_ViewRect = (RectTransform)transform;
return m_ViewRect;
}
}
private Bounds m_ContentBounds;
private Bounds m_ViewBounds;
private Vector2 m_Velocity;
public Vector2 velocity { get { return m_Velocity; } set { m_Velocity = value; } }
private bool m_Dragging;
private Vector2 m_PrevPosition = Vector2.zero;
private Bounds m_PrevContentBounds;
private Bounds m_PrevViewBounds;
[NonSerialized]
private bool m_HasRebuiltLayout = false;
private bool m_HSliderExpand;
private bool m_VSliderExpand;
private float m_HSliderHeight;
private float m_VSliderWidth;
[System.NonSerialized] private RectTransform m_Rect;
private RectTransform rectTransform
{
get
{
if (m_Rect == null)
m_Rect = GetComponent<RectTransform>();
return m_Rect;
}
}
private RectTransform m_HorizontalScrollbarRect;
private RectTransform m_VerticalScrollbarRect;
private DrivenRectTransformTracker m_Tracker;
protected ScrollRect()
{
flexibleWidth = -1;
}
public virtual void Rebuild(CanvasUpdate executing)
{
if (executing == CanvasUpdate.Prelayout)
{
UpdateCachedData();
}
if (executing == CanvasUpdate.PostLayout)
{
UpdateBounds();
UpdateScrollbars(Vector2.zero);
UpdatePrevData();
m_HasRebuiltLayout = true;
}
}
public virtual void LayoutComplete()
{}
public virtual void GraphicUpdateComplete()
{}
void UpdateCachedData()
{
Transform transform = this.transform;
m_HorizontalScrollbarRect = m_HorizontalScrollbar == null ? null : m_HorizontalScrollbar.transform as RectTransform;
m_VerticalScrollbarRect = m_VerticalScrollbar == null ? null : m_VerticalScrollbar.transform as RectTransform;
// These are true if either the elements are children, or they don't exist at all.
bool viewIsChild = (viewRect.parent == transform);
bool hScrollbarIsChild = (!m_HorizontalScrollbarRect || m_HorizontalScrollbarRect.parent == transform);
bool vScrollbarIsChild = (!m_VerticalScrollbarRect || m_VerticalScrollbarRect.parent == transform);
bool allAreChildren = (viewIsChild && hScrollbarIsChild && vScrollbarIsChild);
m_HSliderExpand = allAreChildren && m_HorizontalScrollbarRect && horizontalScrollbarVisibility == ScrollbarVisibility.AutoHideAndExpandViewport;
m_VSliderExpand = allAreChildren && m_VerticalScrollbarRect && verticalScrollbarVisibility == ScrollbarVisibility.AutoHideAndExpandViewport;
m_HSliderHeight = (m_HorizontalScrollbarRect == null ? 0 : m_HorizontalScrollbarRect.rect.height);
m_VSliderWidth = (m_VerticalScrollbarRect == null ? 0 : m_VerticalScrollbarRect.rect.width);
}
protected override void OnEnable()
{
base.OnEnable();
if (m_HorizontalScrollbar)
m_HorizontalScrollbar.onValueChanged.AddListener(SetHorizontalNormalizedPosition);
if (m_VerticalScrollbar)
m_VerticalScrollbar.onValueChanged.AddListener(SetVerticalNormalizedPosition);
CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
}
protected override void OnDisable()
{
CanvasUpdateRegistry.UnRegisterCanvasElementForRebuild(this);
if (m_HorizontalScrollbar)
m_HorizontalScrollbar.onValueChanged.RemoveListener(SetHorizontalNormalizedPosition);
if (m_VerticalScrollbar)
m_VerticalScrollbar.onValueChanged.RemoveListener(SetVerticalNormalizedPosition);
m_HasRebuiltLayout = false;
m_Tracker.Clear();
m_Velocity = Vector2.zero;
LayoutRebuilder.MarkLayoutForRebuild(rectTransform);
base.OnDisable();
}
public override bool IsActive()
{
return base.IsActive() && m_Content != null;
}
private void EnsureLayoutHasRebuilt()
{
if (!m_HasRebuiltLayout && !CanvasUpdateRegistry.IsRebuildingLayout())
Canvas.ForceUpdateCanvases();
}
public virtual void StopMovement()
{
m_Velocity = Vector2.zero;
}
public virtual void OnScroll(PointerEventData data)
{
if (!IsActive())
return;
EnsureLayoutHasRebuilt();
UpdateBounds();
Vector2 delta = data.scrollDelta;
// Down is positive for scroll events, while in UI system up is positive.
delta.y *= -1;
if (vertical && !horizontal)
{
if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
delta.y = delta.x;
delta.x = 0;
}
if (horizontal && !vertical)
{
if (Mathf.Abs(delta.y) > Mathf.Abs(delta.x))
delta.x = delta.y;
delta.y = 0;
}
Vector2 position = m_Content.anchoredPosition;
position += delta * m_ScrollSensitivity;
if (m_MovementType == MovementType.Clamped)
position += CalculateOffset(position - m_Content.anchoredPosition);
SetContentAnchoredPosition(position);
UpdateBounds();
}
public virtual void OnInitializePotentialDrag(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
m_Velocity = Vector2.zero;
}
public virtual void OnBeginDrag(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
if (!IsActive())
return;
UpdateBounds();
m_PointerStartLocalCursor = Vector2.zero;
RectTransformUtility.ScreenPointToLocalPointInRectangle(viewRect, eventData.position, eventData.pressEventCamera, out m_PointerStartLocalCursor);
m_ContentStartPosition = m_Content.anchoredPosition;
m_Dragging = true;
}
public virtual void OnEndDrag(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
m_Dragging = false;
}
public virtual void OnDrag(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
if (!IsActive())
return;
Vector2 localCursor;
if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(viewRect, eventData.position, eventData.pressEventCamera, out localCursor))
return;
UpdateBounds();
var pointerDelta = localCursor - m_PointerStartLocalCursor;
Vector2 position = m_ContentStartPosition + pointerDelta;
// Offset to get content into place in the view.
Vector2 offset = CalculateOffset(position - m_Content.anchoredPosition);
position += offset;
if (m_MovementType == MovementType.Elastic)
{
if (offset.x != 0)
position.x = position.x - RubberDelta(offset.x, m_ViewBounds.size.x);
if (offset.y != 0)
position.y = position.y - RubberDelta(offset.y, m_ViewBounds.size.y);
}
SetContentAnchoredPosition(position);
}
protected virtual void SetContentAnchoredPosition(Vector2 position)
{
if (!m_Horizontal)
position.x = m_Content.anchoredPosition.x;
if (!m_Vertical)
position.y = m_Content.anchoredPosition.y;
if (position != m_Content.anchoredPosition)
{
m_Content.anchoredPosition = position;
UpdateBounds();
}
}
protected virtual void LateUpdate()
{
if (!m_Content)
return;
EnsureLayoutHasRebuilt();
UpdateScrollbarVisibility();
UpdateBounds();
float deltaTime = Time.unscaledDeltaTime;
Vector2 offset = CalculateOffset(Vector2.zero);
if (!m_Dragging && (offset != Vector2.zero || m_Velocity != Vector2.zero))
{
Vector2 position = m_Content.anchoredPosition;
for (int axis = 0; axis < 2; axis++)
{
// Apply spring physics if movement is elastic and content has an offset from the view.
if (m_MovementType == MovementType.Elastic && offset[axis] != 0)
{
float speed = m_Velocity[axis];
position[axis] = Mathf.SmoothDamp(m_Content.anchoredPosition[axis], m_Content.anchoredPosition[axis] + offset[axis], ref speed, m_Elasticity, Mathf.Infinity, deltaTime);
m_Velocity[axis] = speed;
}
// Else move content according to velocity with deceleration applied.
else if (m_Inertia)
{
m_Velocity[axis] *= Mathf.Pow(m_DecelerationRate, deltaTime);
if (Mathf.Abs(m_Velocity[axis]) < 1)
m_Velocity[axis] = 0;
position[axis] += m_Velocity[axis] * deltaTime;
}
// If we have neither elaticity or friction, there shouldn't be any velocity.
else
{
m_Velocity[axis] = 0;
}
}
if (m_Velocity != Vector2.zero)
{
if (m_MovementType == MovementType.Clamped)
{
offset = CalculateOffset(position - m_Content.anchoredPosition);
position += offset;
}
SetContentAnchoredPosition(position);
}
}
if (m_Dragging && m_Inertia)
{
Vector3 newVelocity = (m_Content.anchoredPosition - m_PrevPosition) / deltaTime;
m_Velocity = Vector3.Lerp(m_Velocity, newVelocity, deltaTime * 10);
}
if (m_ViewBounds != m_PrevViewBounds || m_ContentBounds != m_PrevContentBounds || m_Content.anchoredPosition != m_PrevPosition)
{
UpdateScrollbars(offset);
m_OnValueChanged.Invoke(normalizedPosition);
UpdatePrevData();
}
}
private void UpdatePrevData()
{
if (m_Content == null)
m_PrevPosition = Vector2.zero;
else
m_PrevPosition = m_Content.anchoredPosition;
m_PrevViewBounds = m_ViewBounds;
m_PrevContentBounds = m_ContentBounds;
}
private void UpdateScrollbars(Vector2 offset)
{
if (m_HorizontalScrollbar)
{
if (m_ContentBounds.size.x > 0)
m_HorizontalScrollbar.size = Mathf.Clamp01((m_ViewBounds.size.x - Mathf.Abs(offset.x)) / m_ContentBounds.size.x);
else
m_HorizontalScrollbar.size = 1;
m_HorizontalScrollbar.value = horizontalNormalizedPosition;
}
if (m_VerticalScrollbar)
{
if (m_ContentBounds.size.y > 0)
m_VerticalScrollbar.size = Mathf.Clamp01((m_ViewBounds.size.y - Mathf.Abs(offset.y)) / m_ContentBounds.size.y);
else
m_VerticalScrollbar.size = 1;
m_VerticalScrollbar.value = verticalNormalizedPosition;
}
}
public Vector2 normalizedPosition
{
get
{
return new Vector2(horizontalNormalizedPosition, verticalNormalizedPosition);
}
set
{
SetNormalizedPosition(value.x, 0);
SetNormalizedPosition(value.y, 1);
}
}
public float horizontalNormalizedPosition
{
get
{
UpdateBounds();
if (m_ContentBounds.size.x <= m_ViewBounds.size.x)
return (m_ViewBounds.min.x > m_ContentBounds.min.x) ? 1 : 0;
return (m_ViewBounds.min.x - m_ContentBounds.min.x) / (m_ContentBounds.size.x - m_ViewBounds.size.x);
}
set
{
SetNormalizedPosition(value, 0);
}
}
public float verticalNormalizedPosition
{
get
{
UpdateBounds();
if (m_ContentBounds.size.y <= m_ViewBounds.size.y)
return (m_ViewBounds.min.y > m_ContentBounds.min.y) ? 1 : 0;
;
return (m_ViewBounds.min.y - m_ContentBounds.min.y) / (m_ContentBounds.size.y - m_ViewBounds.size.y);
}
set
{
SetNormalizedPosition(value, 1);
}
}
private void SetHorizontalNormalizedPosition(float value) { SetNormalizedPosition(value, 0); }
private void SetVerticalNormalizedPosition(float value) { SetNormalizedPosition(value, 1); }
private void SetNormalizedPosition(float value, int axis)
{
EnsureLayoutHasRebuilt();
UpdateBounds();
// How much the content is larger than the view.
float hiddenLength = m_ContentBounds.size[axis] - m_ViewBounds.size[axis];
// Where the position of the lower left corner of the content bounds should be, in the space of the view.
float contentBoundsMinPosition = m_ViewBounds.min[axis] - value * hiddenLength;
// The new content localPosition, in the space of the view.
float newLocalPosition = m_Content.localPosition[axis] + contentBoundsMinPosition - m_ContentBounds.min[axis];
Vector3 localPosition = m_Content.localPosition;
if (Mathf.Abs(localPosition[axis] - newLocalPosition) > 0.01f)
{
localPosition[axis] = newLocalPosition;
m_Content.localPosition = localPosition;
m_Velocity[axis] = 0;
UpdateBounds();
}
}
private static float RubberDelta(float overStretching, float viewSize)
{
return (1 - (1 / ((Mathf.Abs(overStretching) * 0.55f / viewSize) + 1))) * viewSize * Mathf.Sign(overStretching);
}
protected override void OnRectTransformDimensionsChange()
{
SetDirty();
}
private bool hScrollingNeeded
{
get
{
if (Application.isPlaying)
return m_ContentBounds.size.x > m_ViewBounds.size.x + 0.01f;
return true;
}
}
private bool vScrollingNeeded
{
get
{
if (Application.isPlaying)
return m_ContentBounds.size.y > m_ViewBounds.size.y + 0.01f;
return true;
}
}
public virtual void CalculateLayoutInputHorizontal() {}
public virtual void CalculateLayoutInputVertical() {}
public virtual float minWidth { get { return -1; } }
public virtual float preferredWidth { get { return -1; } }
public virtual float flexibleWidth { get; private set; }
public virtual float minHeight { get { return -1; } }
public virtual float preferredHeight { get { return -1; } }
public virtual float flexibleHeight { get { return -1; } }
public virtual int layoutPriority { get { return -1; } }
public virtual void SetLayoutHorizontal()
{
m_Tracker.Clear();
if (m_HSliderExpand || m_VSliderExpand)
{
m_Tracker.Add(this, viewRect,
DrivenTransformProperties.Anchors |
DrivenTransformProperties.SizeDelta |
DrivenTransformProperties.AnchoredPosition);
// Make view full size to see if content fits.
viewRect.anchorMin = Vector2.zero;
viewRect.anchorMax = Vector2.one;
viewRect.sizeDelta = Vector2.zero;
viewRect.anchoredPosition = Vector2.zero;
// Recalculate content layout with this size to see if it fits when there are no scrollbars.
LayoutRebuilder.ForceRebuildLayoutImmediate(content);
m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
m_ContentBounds = GetBounds();
}
// If it doesn't fit vertically, enable vertical scrollbar and shrink view horizontally to make room for it.
if (m_VSliderExpand && vScrollingNeeded)
{
viewRect.sizeDelta = new Vector2(-(m_VSliderWidth + m_VerticalScrollbarSpacing), viewRect.sizeDelta.y);
// Recalculate content layout with this size to see if it fits vertically
// when there is a vertical scrollbar (which may reflowed the content to make it taller).
LayoutRebuilder.ForceRebuildLayoutImmediate(content);
m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
m_ContentBounds = GetBounds();
}
// If it doesn't fit horizontally, enable horizontal scrollbar and shrink view vertically to make room for it.
if (m_HSliderExpand && hScrollingNeeded)
{
viewRect.sizeDelta = new Vector2(viewRect.sizeDelta.x, -(m_HSliderHeight + m_HorizontalScrollbarSpacing));
m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
m_ContentBounds = GetBounds();
}
// If the vertical slider didn't kick in the first time, and the horizontal one did,
// we need to check again if the vertical slider now needs to kick in.
// If it doesn't fit vertically, enable vertical scrollbar and shrink view horizontally to make room for it.
if (m_VSliderExpand && vScrollingNeeded && viewRect.sizeDelta.x == 0 && viewRect.sizeDelta.y < 0)
{
viewRect.sizeDelta = new Vector2(-(m_VSliderWidth + m_VerticalScrollbarSpacing), viewRect.sizeDelta.y);
}
}
public virtual void SetLayoutVertical()
{
UpdateScrollbarLayout();
m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
m_ContentBounds = GetBounds();
}
void UpdateScrollbarVisibility()
{
if (m_VerticalScrollbar && m_VerticalScrollbarVisibility != ScrollbarVisibility.Permanent && m_VerticalScrollbar.gameObject.activeSelf != vScrollingNeeded)
m_VerticalScrollbar.gameObject.SetActive(vScrollingNeeded);
if (m_HorizontalScrollbar && m_HorizontalScrollbarVisibility != ScrollbarVisibility.Permanent && m_HorizontalScrollbar.gameObject.activeSelf != hScrollingNeeded)
m_HorizontalScrollbar.gameObject.SetActive(hScrollingNeeded);
}
void UpdateScrollbarLayout()
{
if (m_VSliderExpand && m_HorizontalScrollbar)
{
m_Tracker.Add(this, m_HorizontalScrollbarRect,
DrivenTransformProperties.AnchorMinX |
DrivenTransformProperties.AnchorMaxX |
DrivenTransformProperties.SizeDeltaX |
DrivenTransformProperties.AnchoredPositionX);
m_HorizontalScrollbarRect.anchorMin = new Vector2(0, m_HorizontalScrollbarRect.anchorMin.y);
m_HorizontalScrollbarRect.anchorMax = new Vector2(1, m_HorizontalScrollbarRect.anchorMax.y);
m_HorizontalScrollbarRect.anchoredPosition = new Vector2(0, m_HorizontalScrollbarRect.anchoredPosition.y);
if (vScrollingNeeded)
m_HorizontalScrollbarRect.sizeDelta = new Vector2(-(m_VSliderWidth + m_VerticalScrollbarSpacing), m_HorizontalScrollbarRect.sizeDelta.y);
else
m_HorizontalScrollbarRect.sizeDelta = new Vector2(0, m_HorizontalScrollbarRect.sizeDelta.y);
}
if (m_HSliderExpand && m_VerticalScrollbar)
{
m_Tracker.Add(this, m_VerticalScrollbarRect,
DrivenTransformProperties.AnchorMinY |
DrivenTransformProperties.AnchorMaxY |
DrivenTransformProperties.SizeDeltaY |
DrivenTransformProperties.AnchoredPositionY);
m_VerticalScrollbarRect.anchorMin = new Vector2(m_VerticalScrollbarRect.anchorMin.x, 0);
m_VerticalScrollbarRect.anchorMax = new Vector2(m_VerticalScrollbarRect.anchorMax.x, 1);
m_VerticalScrollbarRect.anchoredPosition = new Vector2(m_VerticalScrollbarRect.anchoredPosition.x, 0);
if (hScrollingNeeded)
m_VerticalScrollbarRect.sizeDelta = new Vector2(m_VerticalScrollbarRect.sizeDelta.x, -(m_HSliderHeight + m_HorizontalScrollbarSpacing));
else
m_VerticalScrollbarRect.sizeDelta = new Vector2(m_VerticalScrollbarRect.sizeDelta.x, 0);
}
}
private void UpdateBounds()
{
m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
m_ContentBounds = GetBounds();
if (m_Content == null)
return;
// Make sure content bounds are at least as large as view by adding padding if not.
// One might think at first that if the content is smaller than the view, scrolling should be allowed.
// However, that's not how scroll views normally work.
// Scrolling is *only* possible when content is *larger* than view.
// We use the pivot of the content rect to decide in which directions the content bounds should be expanded.
// E.g. if pivot is at top, bounds are expanded downwards.
// This also works nicely when ContentSizeFitter is used on the content.
Vector3 contentSize = m_ContentBounds.size;
Vector3 contentPos = m_ContentBounds.center;
Vector3 excess = m_ViewBounds.size - contentSize;
if (excess.x > 0)
{
contentPos.x -= excess.x * (m_Content.pivot.x - 0.5f);
contentSize.x = m_ViewBounds.size.x;
}
if (excess.y > 0)
{
contentPos.y -= excess.y * (m_Content.pivot.y - 0.5f);
contentSize.y = m_ViewBounds.size.y;
}
m_ContentBounds.size = contentSize;
m_ContentBounds.center = contentPos;
}
private readonly Vector3[] m_Corners = new Vector3[4];
private Bounds GetBounds()
{
if (m_Content == null)
return new Bounds();
var vMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
var vMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
var toLocal = viewRect.worldToLocalMatrix;
m_Content.GetWorldCorners(m_Corners);
for (int j = 0; j < 4; j++)
{
Vector3 v = toLocal.MultiplyPoint3x4(m_Corners[j]);
vMin = Vector3.Min(v, vMin);
vMax = Vector3.Max(v, vMax);
}
var bounds = new Bounds(vMin, Vector3.zero);
bounds.Encapsulate(vMax);
return bounds;
}
private Vector2 CalculateOffset(Vector2 delta)
{
Vector2 offset = Vector2.zero;
if (m_MovementType == MovementType.Unrestricted)
return offset;
Vector2 min = m_ContentBounds.min;
Vector2 max = m_ContentBounds.max;
if (m_Horizontal)
{
min.x += delta.x;
max.x += delta.x;
if (min.x > m_ViewBounds.min.x)
offset.x = m_ViewBounds.min.x - min.x;
else if (max.x < m_ViewBounds.max.x)
offset.x = m_ViewBounds.max.x - max.x;
}
if (m_Vertical)
{
min.y += delta.y;
max.y += delta.y;
if (max.y < m_ViewBounds.max.y)
offset.y = m_ViewBounds.max.y - max.y;
else if (min.y > m_ViewBounds.min.y)
offset.y = m_ViewBounds.min.y - min.y;
}
return offset;
}
protected void SetDirty()
{
if (!IsActive())
return;
LayoutRebuilder.MarkLayoutForRebuild(rectTransform);
}
protected void SetDirtyCaching()
{
if (!IsActive())
return;
CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
LayoutRebuilder.MarkLayoutForRebuild(rectTransform);
}
#if UNITY_EDITOR
protected override void OnValidate()
{
SetDirtyCaching();
}
#endif
}
}
| |
namespace Fonet.Render.Pdf.Fonts {
internal class TimesBold : Base14Font {
private static readonly int[] CodePointWidths;
private static readonly CodePointMapping DefaultMapping
= CodePointMapping.GetMapping("WinAnsiEncoding");
public TimesBold()
: base("Times-Bold", "WinAnsiEncoding", 676, 676, -205, 32, 255, CodePointWidths, DefaultMapping) {}
static TimesBold() {
CodePointWidths = new int[256];
CodePointWidths[0x0041] = 722;
CodePointWidths[0x00C6] = 1000;
CodePointWidths[0x00C1] = 722;
CodePointWidths[0x00C2] = 722;
CodePointWidths[0x00C4] = 722;
CodePointWidths[0x00C0] = 722;
CodePointWidths[0x00C5] = 722;
CodePointWidths[0x00C3] = 722;
CodePointWidths[0x0042] = 667;
CodePointWidths[0x0043] = 722;
CodePointWidths[0x00C7] = 722;
CodePointWidths[0x0044] = 722;
CodePointWidths[0x0045] = 667;
CodePointWidths[0x00C9] = 667;
CodePointWidths[0x00CA] = 667;
CodePointWidths[0x00CB] = 667;
CodePointWidths[0x00C8] = 667;
CodePointWidths[0x00D0] = 722;
CodePointWidths[0x0080] = 500;
CodePointWidths[0x0046] = 611;
CodePointWidths[0x0047] = 778;
CodePointWidths[0x0048] = 778;
CodePointWidths[0x0049] = 389;
CodePointWidths[0x00CD] = 389;
CodePointWidths[0x00CE] = 389;
CodePointWidths[0x00CF] = 389;
CodePointWidths[0x00CC] = 389;
CodePointWidths[0x004A] = 500;
CodePointWidths[0x004B] = 778;
CodePointWidths[0x004C] = 667;
CodePointWidths[0x004D] = 944;
CodePointWidths[0x004E] = 722;
CodePointWidths[0x00D1] = 722;
CodePointWidths[0x004F] = 778;
CodePointWidths[0x008C] = 1000;
CodePointWidths[0x00D3] = 778;
CodePointWidths[0x00D4] = 778;
CodePointWidths[0x00D6] = 778;
CodePointWidths[0x00D2] = 778;
CodePointWidths[0x00D8] = 778;
CodePointWidths[0x00D5] = 778;
CodePointWidths[0x0050] = 611;
CodePointWidths[0x0051] = 778;
CodePointWidths[0x0052] = 722;
CodePointWidths[0x0053] = 556;
CodePointWidths[0x008A] = 556;
CodePointWidths[0x0054] = 667;
CodePointWidths[0x00DE] = 611;
CodePointWidths[0x0055] = 722;
CodePointWidths[0x00DA] = 722;
CodePointWidths[0x00DB] = 722;
CodePointWidths[0x00DC] = 722;
CodePointWidths[0x00D9] = 722;
CodePointWidths[0x0056] = 722;
CodePointWidths[0x0057] = 1000;
CodePointWidths[0x0058] = 722;
CodePointWidths[0x0059] = 722;
CodePointWidths[0x00DD] = 722;
CodePointWidths[0x009F] = 722;
CodePointWidths[0x005A] = 667;
CodePointWidths[0x0061] = 500;
CodePointWidths[0x00E1] = 500;
CodePointWidths[0x00E2] = 500;
CodePointWidths[0x00B4] = 333;
CodePointWidths[0x00E4] = 500;
CodePointWidths[0x00E6] = 722;
CodePointWidths[0x00E0] = 500;
CodePointWidths[0x0026] = 833;
CodePointWidths[0x00E5] = 500;
CodePointWidths[0x005E] = 581;
CodePointWidths[0x007E] = 520;
CodePointWidths[0x002A] = 500;
CodePointWidths[0x0040] = 930;
CodePointWidths[0x00E3] = 500;
CodePointWidths[0x0062] = 556;
CodePointWidths[0x005C] = 278;
CodePointWidths[0x007C] = 220;
CodePointWidths[0x007B] = 394;
CodePointWidths[0x007D] = 394;
CodePointWidths[0x005B] = 333;
CodePointWidths[0x005D] = 333;
CodePointWidths[0x00A6] = 220;
CodePointWidths[0x0095] = 350;
CodePointWidths[0x0063] = 444;
CodePointWidths[0x00E7] = 444;
CodePointWidths[0x00B8] = 333;
CodePointWidths[0x00A2] = 500;
CodePointWidths[0x0088] = 333;
CodePointWidths[0x003A] = 333;
CodePointWidths[0x002C] = 250;
CodePointWidths[0x00A9] = 747;
CodePointWidths[0x00A4] = 500;
CodePointWidths[0x0064] = 556;
CodePointWidths[0x0086] = 500;
CodePointWidths[0x0087] = 500;
CodePointWidths[0x00B0] = 400;
CodePointWidths[0x00A8] = 333;
CodePointWidths[0x00F7] = 570;
CodePointWidths[0x0024] = 500;
CodePointWidths[0x0065] = 444;
CodePointWidths[0x00E9] = 444;
CodePointWidths[0x00EA] = 444;
CodePointWidths[0x00EB] = 444;
CodePointWidths[0x00E8] = 444;
CodePointWidths[0x0038] = 500;
CodePointWidths[0x0085] = 1000;
CodePointWidths[0x0097] = 1000;
CodePointWidths[0x0096] = 500;
CodePointWidths[0x003D] = 570;
CodePointWidths[0x00F0] = 500;
CodePointWidths[0x0021] = 333;
CodePointWidths[0x00A1] = 333;
CodePointWidths[0x0066] = 333;
CodePointWidths[0x0035] = 500;
CodePointWidths[0x0083] = 500;
CodePointWidths[0x0034] = 500;
CodePointWidths[0xA4] = 167;
CodePointWidths[0x0067] = 500;
CodePointWidths[0x00DF] = 556;
CodePointWidths[0x0060] = 333;
CodePointWidths[0x003E] = 570;
CodePointWidths[0x00AB] = 500;
CodePointWidths[0x00BB] = 500;
CodePointWidths[0x008B] = 333;
CodePointWidths[0x009B] = 333;
CodePointWidths[0x0068] = 556;
CodePointWidths[0x002D] = 333;
CodePointWidths[0x0069] = 278;
CodePointWidths[0x00ED] = 278;
CodePointWidths[0x00EE] = 278;
CodePointWidths[0x00EF] = 278;
CodePointWidths[0x00EC] = 278;
CodePointWidths[0x006A] = 333;
CodePointWidths[0x006B] = 556;
CodePointWidths[0x006C] = 278;
CodePointWidths[0x003C] = 570;
CodePointWidths[0x00AC] = 570;
CodePointWidths[0x006D] = 833;
CodePointWidths[0x00AF] = 333;
CodePointWidths[0x2D] = 324;
CodePointWidths[0x00B5] = 556;
CodePointWidths[0x00D7] = 570;
CodePointWidths[0x006E] = 556;
CodePointWidths[0x0039] = 500;
CodePointWidths[0x00F1] = 556;
CodePointWidths[0x0023] = 500;
CodePointWidths[0x006F] = 500;
CodePointWidths[0x00F3] = 500;
CodePointWidths[0x00F4] = 500;
CodePointWidths[0x00F6] = 500;
CodePointWidths[0x009C] = 722;
CodePointWidths[0x00F2] = 500;
CodePointWidths[0x0031] = 500;
CodePointWidths[0x00BD] = 750;
CodePointWidths[0x00BC] = 750;
CodePointWidths[0x00B9] = 300;
CodePointWidths[0x00AA] = 300;
CodePointWidths[0x00BA] = 330;
CodePointWidths[0x00F8] = 500;
CodePointWidths[0x00F5] = 500;
CodePointWidths[0x0070] = 556;
CodePointWidths[0x00B6] = 540;
CodePointWidths[0x0028] = 333;
CodePointWidths[0x0029] = 333;
CodePointWidths[0x0025] = 1000;
CodePointWidths[0x002E] = 250;
CodePointWidths[0x00B7] = 250;
CodePointWidths[0x0089] = 1000;
CodePointWidths[0x002B] = 570;
CodePointWidths[0x00B1] = 570;
CodePointWidths[0x0071] = 556;
CodePointWidths[0x003F] = 500;
CodePointWidths[0x00BF] = 500;
CodePointWidths[0x0022] = 555;
CodePointWidths[0x0084] = 500;
CodePointWidths[0x0093] = 500;
CodePointWidths[0x0094] = 500;
CodePointWidths[0x0091] = 333;
CodePointWidths[0x0092] = 333;
CodePointWidths[0x0082] = 333;
CodePointWidths[0x0027] = 278;
CodePointWidths[0x0072] = 444;
CodePointWidths[0x00AE] = 747;
CodePointWidths[0x0073] = 389;
CodePointWidths[0x009A] = 389;
CodePointWidths[0x00A7] = 500;
CodePointWidths[0x003B] = 333;
CodePointWidths[0x0037] = 500;
CodePointWidths[0x0036] = 500;
CodePointWidths[0x002F] = 278;
CodePointWidths[0x0020] = 250;
CodePointWidths[0x00A0] = 250;
CodePointWidths[0x00A3] = 500;
CodePointWidths[0x0074] = 333;
CodePointWidths[0x00FE] = 556;
CodePointWidths[0x0033] = 500;
CodePointWidths[0x00BE] = 750;
CodePointWidths[0x00B3] = 300;
CodePointWidths[0x0098] = 333;
CodePointWidths[0x0099] = 1000;
CodePointWidths[0x0032] = 500;
CodePointWidths[0x00B2] = 300;
CodePointWidths[0x0075] = 556;
CodePointWidths[0x00FA] = 556;
CodePointWidths[0x00FB] = 556;
CodePointWidths[0x00FC] = 556;
CodePointWidths[0x00F9] = 556;
CodePointWidths[0x005F] = 500;
CodePointWidths[0x0076] = 500;
CodePointWidths[0x0077] = 722;
CodePointWidths[0x0078] = 500;
CodePointWidths[0x0079] = 500;
CodePointWidths[0x00FD] = 500;
CodePointWidths[0x00FF] = 500;
CodePointWidths[0x00A5] = 500;
CodePointWidths[0x007A] = 444;
CodePointWidths[0x0030] = 500;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowIteratorSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowIteratorSpec : AbstractFlowIteratorSpec
{
public FlowIteratorSpec(ITestOutputHelper helper) : base(helper)
{
}
protected override Source<int, NotUsed> CreateSource(int elements)
=> Source.FromEnumerator(() => Enumerable.Range(1, elements).GetEnumerator());
}
public class FlowIterableSpec : AbstractFlowIteratorSpec
{
public FlowIterableSpec(ITestOutputHelper helper) : base(helper)
{
}
protected override Source<int, NotUsed> CreateSource(int elements)
=> Source.From(Enumerable.Range(1, elements));
[Fact]
public void A_Flow_based_on_an_iterable_must_produce_OnError_when_iterator_throws()
{
var iterable = Enumerable.Range(1, 3).Select(x =>
{
if (x == 2)
throw new IllegalStateException("not two");
return x;
});
var p = Source.From(iterable).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
var sub = c.ExpectSubscription();
sub.Request(1);
c.ExpectNext(1);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
EventFilter.Exception<IllegalStateException>("not two").ExpectOne(() => sub.Request(2));
c.ExpectError().Message.Should().Be("not two");
sub.Request(2);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}
[Fact]
public void A_Flow_based_on_an_iterable_must_produce_OnError_when_Source_construction_throws()
{
var p = Source.From(new ThrowEnumerable()).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
c.ExpectSubscriptionAndError().Message.Should().Be("no good iterator");
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}
[Fact]
public void A_Flow_based_on_an_iterable_must_produce_OnError_when_MoveNext_throws()
{
var p = Source.From(new ThrowEnumerable(false)).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
c.ExpectSubscriptionAndError().Message.Should().Be("no next");
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}
private sealed class ThrowEnumerable : IEnumerable<int>
{
private readonly bool _throwOnGetEnumerator;
public ThrowEnumerable(bool throwOnGetEnumerator = true)
{
_throwOnGetEnumerator = throwOnGetEnumerator;
}
public IEnumerator<int> GetEnumerator()
{
if(_throwOnGetEnumerator)
throw new IllegalStateException("no good iterator");
return new ThrowEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
private sealed class ThrowEnumerator : IEnumerator<int>
{
public void Dispose()
{
throw new NotImplementedException();
}
public bool MoveNext()
{
throw new IllegalStateException("no next");
}
public void Reset()
{
throw new NotImplementedException();
}
public int Current { get; } = -1;
object IEnumerator.Current => Current;
}
}
public abstract class AbstractFlowIteratorSpec : AkkaSpec
{
protected ActorMaterializer Materializer { get; }
protected AbstractFlowIteratorSpec(ITestOutputHelper helper) : base(helper)
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 2);
Materializer = ActorMaterializer.Create(Sys, settings);
}
protected abstract Source<int, NotUsed> CreateSource(int elements);
[Fact]
public void A_Flow_based_on_an_iterable_must_produce_elements()
{
this.AssertAllStagesStopped(() =>
{
var p = CreateSource(3).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
var sub = c.ExpectSubscription();
sub.Request(1);
c.ExpectNext(1);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
sub.Request(3);
c.ExpectNext(2)
.ExpectNext(3)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Flow_based_on_an_iterable_must_complete_empty()
{
this.AssertAllStagesStopped(() =>
{
var p = CreateSource(0).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
c.ExpectSubscriptionAndComplete();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}, Materializer);
}
[Fact]
public void A_Flow_based_on_an_iterable_must_produce_elements_with_multiple_subscribers()
{
this.AssertAllStagesStopped(() =>
{
var p = CreateSource(3).RunWith(Sink.AsPublisher<int>(true), Materializer);
var c1 = this.CreateManualSubscriberProbe<int>();
var c2 = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c1);
p.Subscribe(c2);
var sub1 = c1.ExpectSubscription();
var sub2 = c2.ExpectSubscription();
sub1.Request(1);
sub2.Request(2);
c1.ExpectNext(1);
c2.ExpectNext(1);
c2.ExpectNext(2);
c1.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
c2.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
sub1.Request(2);
sub2.Request(2);
c1.ExpectNext(2);
c1.ExpectNext(3);
c2.ExpectNext(3);
c1.ExpectComplete();
c2.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Flow_based_on_an_iterable_must_produce_elements_to_later_subscriber()
{
this.AssertAllStagesStopped(() =>
{
var p = CreateSource(3).RunWith(Sink.AsPublisher<int>(true), Materializer);
var c1 = this.CreateManualSubscriberProbe<int>();
var c2 = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c1);
var sub1 = c1.ExpectSubscription();
sub1.Request(1);
c1.ExpectNext(1, TimeSpan.FromSeconds(60));
c1.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
p.Subscribe(c2);
var sub2 = c2.ExpectSubscription();
sub2.Request(3);
//element 1 is already gone
c2.ExpectNext(2)
.ExpectNext(3)
.ExpectComplete();
sub1.Request(3);
c1.ExpectNext(2)
.ExpectNext(3)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Flow_based_on_an_iterable_must_produce_elements_with_one_transformation_step()
{
this.AssertAllStagesStopped(() =>
{
var p = CreateSource(3)
.Select(x => x*2)
.RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
var sub = c.ExpectSubscription();
sub.Request(10);
c.ExpectNext(2)
.ExpectNext(4)
.ExpectNext(6)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Flow_based_on_an_iterable_must_produce_elements_with_two_transformation_steps()
{
this.AssertAllStagesStopped(() =>
{
var p = CreateSource(4)
.Where(x => x%2 == 0)
.Select(x => x*2)
.RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
var sub = c.ExpectSubscription();
sub.Request(10);
c.ExpectNext(4)
.ExpectNext(8)
.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Flow_based_on_an_iterable_must_not_produce_after_cancel()
{
this.AssertAllStagesStopped(() =>
{
var p = CreateSource(3).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
var sub = c.ExpectSubscription();
sub.Request(1);
c.ExpectNext(1);
sub.Cancel();
sub.Request(2);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}, Materializer);
}
}
}
| |
// Copyright (c) 2007-2008, Gaudenz Alder
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace com.mxgraph
{
/// <summary>
/// Static class that acts as a global registry for codecs. See mxCodec for
/// an example of using this class.
/// </summary>
public class mxCodecRegistry
{
/// <summary>
/// Maps from constructor names to codecs.
/// </summary>
protected static Dictionary<string, mxObjectCodec> codecs = new Dictionary<string, mxObjectCodec>();
/// <summary>
/// Maps from classnames to codecnames.
/// </summary>
protected static Dictionary<string, string> aliases = new Dictionary<string, string>();
/// <summary>
/// Holds the list of known namespaces. Packages are used to prefix short
/// class names (eg. mxCell) in XML markup.
/// </summary>
protected static List<string> namespaces = new List<string>();
// Registers the known codecs and package names
static mxCodecRegistry()
{
AddNamespace("com.mxgraph");
AddNamespace("System.Collections.Generic");
Register(new mxObjectCodec(new ArrayList()));
Register(new mxModelCodec());
Register(new mxCellCodec());
Register(new mxStylesheetCodec());
}
/// <summary>
/// Registers a new codec and associates the name of the template constructor
/// in the codec with the codec object. Automatically creates an alias if the
/// codename and the classname are not equal.
/// </summary>
public static mxObjectCodec Register(mxObjectCodec codec)
{
if (codec != null)
{
string name = codec.GetName();
codecs[name] = codec;
string classname = GetName(codec.Template);
if (!classname.Equals(name))
{
AddAlias(classname, name);
}
}
return codec;
}
/// <summary>
/// Adds an alias for mapping a classname to a codecname.
/// </summary>
public static void AddAlias(string classname, string codecname)
{
aliases[classname] = codecname;
}
/// <summary>
/// Returns a codec that handles the given object, which can be an object
/// instance or an XML node.
/// </summary>
/// <param name="name">C# type name.</param>
/// <returns></returns>
public static mxObjectCodec GetCodec(String name)
{
if (aliases.ContainsKey(name))
{
name = aliases[name];
}
mxObjectCodec codec = (codecs.ContainsKey(name)) ? codecs[name] : null;
if (codec == null)
{
Object instance = GetInstanceForName(name);
if (instance != null)
{
try
{
codec = new mxObjectCodec(instance);
Register(codec);
}
catch (Exception e)
{
Trace.WriteLine("mxCodecRegistry.GetCodec(" + name + "): " + e.Message);
}
}
}
return codec;
}
/// <summary>
/// Adds the given namespace to the list of known namespaces.
/// </summary>
/// <param name="ns">Name of the namespace to be added.</param>
public static void AddNamespace(String ns)
{
namespaces.Add(ns);
}
/// <summary>
/// Creates and returns a new instance for the given class name.
/// </summary>
/// <param name="name">Name of the class to be instantiated.</param>
/// <returns>Returns a new instance of the given class.</returns>
public static Object GetInstanceForName(String name)
{
Type type = GetTypeForName(name);
if (type != null)
{
try
{
return Activator.CreateInstance(type);
}
catch (Exception e)
{
Trace.WriteLine("mxCodecRegistry.GetInstanceForName(" + name + "): " + e.Message);
}
}
return null;
}
/// <summary>
/// Returns a class that corresponds to the given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Type GetTypeForName(String name)
{
try
{
Type type = Type.GetType(name);
if (type != null)
{
return type;
}
}
catch (Exception e)
{
Trace.WriteLine("mxCodecRegistry.GetTypeForName(" + name + "): " + e.Message);
}
foreach (string ns in namespaces)
{
try
{
Type type = Type.GetType(ns + "." + name);
if (type != null)
{
return type;
}
}
catch (Exception e)
{
Trace.WriteLine("mxCodecRegistry.GetTypeForName(" + ns + "." + name + "): " + e.Message);
}
}
return null;
}
/// <summary>
/// Returns the name that identifies the codec associated
/// with the given instance.
/// The I/O system uses unqualified classnames, eg. for a
/// com.mxgraph.model.mxCell this returns mxCell.
/// </summary>
/// <param name="instance">Instance whose node name should be returned.</param>
/// <returns>Returns a string that identifies the codec.</returns>
public static String GetName(Object instance)
{
Type type = instance.GetType();
if (type.IsArray || typeof(IEnumerable).IsAssignableFrom(type))
{
return "Array";
}
else
{
if (namespaces.Contains(type.Namespace))
{
return type.Name;
}
else
{
return type.FullName;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using AzureGuidance.API.Areas.HelpPage.ModelDescriptions;
using AzureGuidance.API.Areas.HelpPage.Models;
namespace AzureGuidance.API.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.
// File System.Windows.Media.Animation.ObjectKeyFrameCollection.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Animation
{
public partial class ObjectKeyFrameCollection : System.Windows.Freezable, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable
{
#region Methods and constructors
public int Add(ObjectKeyFrame keyFrame)
{
return default(int);
}
public void Clear()
{
}
public System.Windows.Media.Animation.ObjectKeyFrameCollection Clone()
{
return default(System.Windows.Media.Animation.ObjectKeyFrameCollection);
}
protected override void CloneCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void CloneCurrentValueCore(System.Windows.Freezable sourceFreezable)
{
}
public bool Contains(ObjectKeyFrame keyFrame)
{
return default(bool);
}
public void CopyTo(ObjectKeyFrame[] array, int index)
{
}
protected override System.Windows.Freezable CreateInstanceCore()
{
return default(System.Windows.Freezable);
}
protected override bool FreezeCore(bool isChecking)
{
return default(bool);
}
protected override void GetAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
public System.Collections.IEnumerator GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
public int IndexOf(ObjectKeyFrame keyFrame)
{
return default(int);
}
public void Insert(int index, ObjectKeyFrame keyFrame)
{
}
public ObjectKeyFrameCollection()
{
}
public void Remove(ObjectKeyFrame keyFrame)
{
}
public void RemoveAt(int index)
{
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
}
int System.Collections.IList.Add(Object keyFrame)
{
return default(int);
}
bool System.Collections.IList.Contains(Object keyFrame)
{
return default(bool);
}
int System.Collections.IList.IndexOf(Object keyFrame)
{
return default(int);
}
void System.Collections.IList.Insert(int index, Object keyFrame)
{
}
void System.Collections.IList.Remove(Object keyFrame)
{
}
#endregion
#region Properties and indexers
public int Count
{
get
{
return default(int);
}
}
public static System.Windows.Media.Animation.ObjectKeyFrameCollection Empty
{
get
{
return default(System.Windows.Media.Animation.ObjectKeyFrameCollection);
}
}
public bool IsFixedSize
{
get
{
return default(bool);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public bool IsSynchronized
{
get
{
return default(bool);
}
}
public ObjectKeyFrame this [int index]
{
get
{
return default(ObjectKeyFrame);
}
set
{
}
}
public Object SyncRoot
{
get
{
return default(Object);
}
}
Object System.Collections.IList.this [int index]
{
get
{
return default(Object);
}
set
{
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\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 TestCSByte()
{
var test = new BooleanBinaryOpTest__TestCSByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestCSByte
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(SByte);
private const int Op2ElementCount = VectorSize / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private BooleanBinaryOpTest__DataTable<SByte, SByte> _dataTable;
static BooleanBinaryOpTest__TestCSByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
}
public BooleanBinaryOpTest__TestCSByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
_dataTable = new BooleanBinaryOpTest__DataTable<SByte, SByte>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestC(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestC(
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestC(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = Sse41.TestC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse41.TestC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse41.TestC(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanBinaryOpTest__TestCSByte();
var result = Sse41.TestC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<SByte> left, Vector128<SByte> right, bool result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(SByte[] left, SByte[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((~left[i] & right[i]) == 0);
}
if (expectedResult != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestC)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Log;
using Microsoft.Win32;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
/// <summary>
/// Native utility methods.
/// </summary>
internal static class IgniteUtils
{
/** Environment variable: JAVA_HOME. */
private const string EnvJavaHome = "JAVA_HOME";
/** Lookup paths. */
private static readonly string[] JvmDllLookupPaths = {@"jre\bin\server", @"jre\bin\default"};
/** Registry lookup paths. */
private static readonly string[] JreRegistryKeys =
{
@"Software\JavaSoft\Java Runtime Environment",
@"Software\Wow6432Node\JavaSoft\Java Runtime Environment"
};
/** File: jvm.dll. */
internal const string FileJvmDll = "jvm.dll";
/** File: Ignite.Jni.dll. */
internal const string FileIgniteJniDll = "ignite.jni.dll";
/** Prefix for temp directory names. */
private const string DirIgniteTmp = "Ignite_";
/** Loaded. */
private static bool _loaded;
/** Thread-local random. */
[ThreadStatic]
private static Random _rnd;
/// <summary>
/// Initializes the <see cref="IgniteUtils"/> class.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline",
Justification = "Readability.")]
static IgniteUtils()
{
TryCleanTempDirectories();
}
/// <summary>
/// Gets thread local random.
/// </summary>
/// <value>Thread local random.</value>
public static Random ThreadLocalRandom
{
get { return _rnd ?? (_rnd = new Random()); }
}
/// <summary>
/// Returns shuffled list copy.
/// </summary>
/// <returns>Shuffled list copy.</returns>
public static IList<T> Shuffle<T>(IList<T> list)
{
int cnt = list.Count;
if (cnt > 1) {
List<T> res = new List<T>(list);
Random rnd = ThreadLocalRandom;
while (cnt > 1)
{
cnt--;
int idx = rnd.Next(cnt + 1);
T val = res[idx];
res[idx] = res[cnt];
res[cnt] = val;
}
return res;
}
return list;
}
/// <summary>
/// Load JVM DLL if needed.
/// </summary>
/// <param name="configJvmDllPath">JVM DLL path from config.</param>
/// <param name="log">Log.</param>
public static void LoadDlls(string configJvmDllPath, ILogger log)
{
if (_loaded)
{
log.Debug("JNI dll is already loaded.");
return;
}
// 1. Load JNI dll.
LoadJvmDll(configJvmDllPath, log);
// 2. Load GG JNI dll.
UnmanagedUtils.Initialize();
_loaded = true;
}
/// <summary>
/// Create new instance of specified class.
/// </summary>
/// <param name="typeName">Class name</param>
/// <param name="props">Properties to set.</param>
/// <returns>New Instance.</returns>
public static T CreateInstance<T>(string typeName, IEnumerable<KeyValuePair<string, object>> props = null)
{
IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName");
var type = new TypeResolver().ResolveType(typeName);
if (type == null)
throw new IgniteException("Failed to create class instance [className=" + typeName + ']');
var res = (T) Activator.CreateInstance(type);
if (props != null)
SetProperties(res, props);
return res;
}
/// <summary>
/// Set properties on the object.
/// </summary>
/// <param name="target">Target object.</param>
/// <param name="props">Properties.</param>
private static void SetProperties(object target, IEnumerable<KeyValuePair<string, object>> props)
{
if (props == null)
return;
IgniteArgumentCheck.NotNull(target, "target");
Type typ = target.GetType();
foreach (KeyValuePair<string, object> prop in props)
{
PropertyInfo prop0 = typ.GetProperty(prop.Key,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (prop0 == null)
throw new IgniteException("Property is not found [type=" + typ.Name +
", property=" + prop.Key + ']');
prop0.SetValue(target, prop.Value, null);
}
}
/// <summary>
/// Loads the JVM DLL.
/// </summary>
private static void LoadJvmDll(string configJvmDllPath, ILogger log)
{
var messages = new List<string>();
foreach (var dllPath in GetJvmDllPaths(configJvmDllPath))
{
log.Debug("Trying to load JVM dll from [option={0}, path={1}]...", dllPath.Key, dllPath.Value);
var errCode = LoadDll(dllPath.Value, FileJvmDll);
if (errCode == 0)
{
log.Debug("jvm.dll successfully loaded from [option={0}, path={1}]", dllPath.Key, dllPath.Value);
return;
}
var message = string.Format(CultureInfo.InvariantCulture, "[option={0}, path={1}, error={2}]",
dllPath.Key, dllPath.Value, FormatWin32Error(errCode));
messages.Add(message);
log.Debug("Failed to load jvm.dll: " + message);
if (dllPath.Value == configJvmDllPath)
break; // if configJvmDllPath is specified and is invalid - do not try other options
}
if (!messages.Any()) // not loaded and no messages - everything was null
messages.Add(string.Format(CultureInfo.InvariantCulture,
"Please specify IgniteConfiguration.JvmDllPath or {0}.", EnvJavaHome));
if (messages.Count == 1)
throw new IgniteException(string.Format(CultureInfo.InvariantCulture, "Failed to load {0} ({1})",
FileJvmDll, messages[0]));
var combinedMessage =
messages.Aggregate((x, y) => string.Format(CultureInfo.InvariantCulture, "{0}\n{1}", x, y));
throw new IgniteException(string.Format(CultureInfo.InvariantCulture, "Failed to load {0}:\n{1}",
FileJvmDll, combinedMessage));
}
/// <summary>
/// Formats the Win32 error.
/// </summary>
private static string FormatWin32Error(int errorCode)
{
if (errorCode == NativeMethods.ERROR_BAD_EXE_FORMAT)
{
var mode = Environment.Is64BitProcess ? "x64" : "x86";
return string.Format("DLL could not be loaded (193: ERROR_BAD_EXE_FORMAT). " +
"This is often caused by x64/x86 mismatch. " +
"Current process runs in {0} mode, and DLL is not {0}.", mode);
}
return string.Format("{0}: {1}", errorCode, new Win32Exception(errorCode).Message);
}
/// <summary>
/// Try loading DLLs first using file path, then using it's simple name.
/// </summary>
/// <param name="filePath"></param>
/// <param name="simpleName"></param>
/// <returns>Zero in case of success, error code in case of failure.</returns>
private static int LoadDll(string filePath, string simpleName)
{
int res = 0;
IntPtr ptr;
if (filePath != null)
{
ptr = NativeMethods.LoadLibrary(filePath);
if (ptr == IntPtr.Zero)
res = Marshal.GetLastWin32Error();
else
return res;
}
// Failed to load using file path, fallback to simple name.
ptr = NativeMethods.LoadLibrary(simpleName);
if (ptr == IntPtr.Zero)
{
// Preserve the first error code, if any.
if (res == 0)
res = Marshal.GetLastWin32Error();
}
else
res = 0;
return res;
}
/// <summary>
/// Gets the JVM DLL paths in order of lookup priority.
/// </summary>
private static IEnumerable<KeyValuePair<string, string>> GetJvmDllPaths(string configJvmDllPath)
{
if (!string.IsNullOrEmpty(configJvmDllPath))
yield return new KeyValuePair<string, string>("IgniteConfiguration.JvmDllPath", configJvmDllPath);
var javaHomeDir = Environment.GetEnvironmentVariable(EnvJavaHome);
if (!string.IsNullOrEmpty(javaHomeDir))
foreach (var path in JvmDllLookupPaths)
yield return
new KeyValuePair<string, string>(EnvJavaHome, Path.Combine(javaHomeDir, path, FileJvmDll));
// Get paths from the Windows Registry
foreach (var regPath in JreRegistryKeys)
{
using (var jSubKey = Registry.LocalMachine.OpenSubKey(regPath))
{
if (jSubKey == null)
continue;
var curVer = jSubKey.GetValue("CurrentVersion") as string;
// Current version comes first
var versions = new[] {curVer}.Concat(jSubKey.GetSubKeyNames().Where(x => x != curVer));
foreach (var ver in versions.Where(v => !string.IsNullOrEmpty(v)))
{
using (var verKey = jSubKey.OpenSubKey(ver))
{
var dllPath = verKey == null ? null : verKey.GetValue("RuntimeLib") as string;
if (dllPath != null)
yield return new KeyValuePair<string, string>(verKey.Name, dllPath);
}
}
}
}
}
/// <summary>
/// Unpacks an embedded resource into a temporary folder and returns the full path of resulting file.
/// </summary>
/// <param name="resourceName">Resource name.</param>
/// <param name="fileName">Name of the resulting file.</param>
/// <returns>
/// Path to a temp file with an unpacked resource.
/// </returns>
public static string UnpackEmbeddedResource(string resourceName, string fileName)
{
var dllRes = Assembly.GetExecutingAssembly().GetManifestResourceNames()
.Single(x => x.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase));
return WriteResourceToTempFile(dllRes, fileName);
}
/// <summary>
/// Writes the resource to temporary file.
/// </summary>
/// <param name="resource">The resource.</param>
/// <param name="name">File name prefix</param>
/// <returns>Path to the resulting temp file.</returns>
private static string WriteResourceToTempFile(string resource, string name)
{
// Dll file name should not be changed, so we create a temp folder with random name instead.
var file = Path.Combine(GetTempDirectoryName(), name);
using (var src = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource))
using (var dest = File.OpenWrite(file))
{
// ReSharper disable once PossibleNullReferenceException
src.CopyTo(dest);
return file;
}
}
/// <summary>
/// Tries to clean temporary directories created with <see cref="GetTempDirectoryName"/>.
/// </summary>
private static void TryCleanTempDirectories()
{
foreach (var dir in Directory.GetDirectories(Path.GetTempPath(), DirIgniteTmp + "*"))
{
try
{
Directory.Delete(dir, true);
}
catch (IOException)
{
// Expected
}
catch (UnauthorizedAccessException)
{
// Expected
}
}
}
/// <summary>
/// Creates a uniquely named, empty temporary directory on disk and returns the full path of that directory.
/// </summary>
/// <returns>The full path of the temporary directory.</returns>
private static string GetTempDirectoryName()
{
while (true)
{
var dir = Path.Combine(Path.GetTempPath(), DirIgniteTmp + Path.GetRandomFileName());
try
{
return Directory.CreateDirectory(dir).FullName;
}
catch (IOException)
{
// Expected
}
catch (UnauthorizedAccessException)
{
// Expected
}
}
}
/// <summary>
/// Convert unmanaged char array to string.
/// </summary>
/// <param name="chars">Char array.</param>
/// <param name="charsLen">Char array length.</param>
/// <returns></returns>
public static unsafe string Utf8UnmanagedToString(sbyte* chars, int charsLen)
{
IntPtr ptr = new IntPtr(chars);
if (ptr == IntPtr.Zero)
return null;
byte[] arr = new byte[charsLen];
Marshal.Copy(ptr, arr, 0, arr.Length);
return Encoding.UTF8.GetString(arr);
}
/// <summary>
/// Convert string to unmanaged byte array.
/// </summary>
/// <param name="str">String.</param>
/// <returns>Unmanaged byte array.</returns>
public static unsafe sbyte* StringToUtf8Unmanaged(string str)
{
var ptr = IntPtr.Zero;
if (str != null)
{
byte[] strBytes = Encoding.UTF8.GetBytes(str);
ptr = Marshal.AllocHGlobal(strBytes.Length + 1);
Marshal.Copy(strBytes, 0, ptr, strBytes.Length);
*((byte*)ptr.ToPointer() + strBytes.Length) = 0; // NULL-terminator.
}
return (sbyte*)ptr.ToPointer();
}
/// <summary>
/// Reads node collection from stream.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="pred">The predicate.</param>
/// <returns> Nodes list or null. </returns>
public static List<IClusterNode> ReadNodes(IBinaryRawReader reader, Func<ClusterNodeImpl, bool> pred = null)
{
var cnt = reader.ReadInt();
if (cnt < 0)
return null;
var res = new List<IClusterNode>(cnt);
var ignite = ((BinaryReader)reader).Marshaller.Ignite;
if (pred == null)
{
for (var i = 0; i < cnt; i++)
res.Add(ignite.GetNode(reader.ReadGuid()));
}
else
{
for (var i = 0; i < cnt; i++)
{
var node = ignite.GetNode(reader.ReadGuid());
if (pred(node))
res.Add(node);
}
}
return res;
}
/// <summary>
/// Writes the node collection to a stream.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="nodes">The nodes.</param>
public static void WriteNodes(IBinaryRawWriter writer, ICollection<IClusterNode> nodes)
{
Debug.Assert(writer != null);
if (nodes != null)
{
writer.WriteInt(nodes.Count);
foreach (var node in nodes)
writer.WriteGuid(node.Id);
}
else
writer.WriteInt(-1);
}
}
}
| |
using De.Osthus.Ambeth.Annotation;
using De.Osthus.Ambeth.Bytecode;
using De.Osthus.Ambeth.Collections;
using De.Osthus.Ambeth.CompositeId;
using De.Osthus.Ambeth.Config;
using De.Osthus.Ambeth.Ioc.Annotation;
using De.Osthus.Ambeth.Log;
using De.Osthus.Ambeth.Typeinfo;
using De.Osthus.Ambeth.Util;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace De.Osthus.Ambeth.Metadata
{
public class MemberTypeProvider : IMemberTypeProvider, IIntermediateMemberTypeProvider
{
public class TypeAndStringWeakMap<T> : Tuple2KeyHashMap<Type, String, WeakReference>
{
protected override void Transfer(Tuple2KeyEntry<Type, String, WeakReference>[] newTable)
{
int newCapacityMinus1 = newTable.Length - 1;
Tuple2KeyEntry<Type, String, WeakReference>[] table = this.table;
for (int a = table.Length; a-- > 0; )
{
Tuple2KeyEntry<Type, String, WeakReference> entry = table[a], next;
while (entry != null)
{
next = entry.GetNextEntry();
// only handle this entry if it has still a valid value
if (entry.GetValue().Target != null)
{
int i = entry.GetHash() & newCapacityMinus1;
entry.SetNextEntry(newTable[i]);
newTable[i] = entry;
}
entry = next;
}
}
}
}
public static IPropertyInfo[] BuildPropertyPath(Type entityType, String memberName, IPropertyInfoProvider propertyInfoProvider)
{
String[] memberPath = EmbeddedMember.Split(memberName);
Type currType = entityType;
IPropertyInfo[] propertyPath = new IPropertyInfo[memberPath.Length];
for (int a = 0, size = propertyPath.Length; a < size; a++)
{
IPropertyInfo property = propertyInfoProvider.GetProperty(currType, memberPath[a]);
if (property == null)
{
FieldInfo[] fields = ReflectUtil.GetDeclaredFieldInHierarchy(currType, memberPath[a]);
if (fields.Length == 0)
{
throw new Exception("Path illegal: " + memberName);
}
property = new FieldPropertyInfo(currType, memberPath[a], fields[a]);
}
propertyPath[a] = property;
currType = property.PropertyType;
}
return propertyPath;
}
protected static readonly Object[] EMPTY_OBJECTS = new Object[0];
[LogInstance]
public ILogger Log { private get; set; }
protected readonly TypeAndStringWeakMap<PrimitiveMember> typeToPrimitiveMemberMap = new TypeAndStringWeakMap<PrimitiveMember>();
protected readonly TypeAndStringWeakMap<Member> typeToMemberMap = new TypeAndStringWeakMap<Member>();
protected readonly TypeAndStringWeakMap<RelationMember> typeToRelationMemberMap = new TypeAndStringWeakMap<RelationMember>();
protected readonly Object writeLock = new Object();
[Autowired]
public IBytecodeEnhancer BytecodeEnhancer { protected get; set; }
[Autowired]
public ICompositeIdFactory CompositeIdFactory { protected get; set; }
[Autowired]
public IProperties Properties { protected get; set; }
[Autowired]
public IPropertyInfoProvider PropertyInfoProvider { protected get; set; }
public RelationMember GetRelationMember(Type type, String propertyName)
{
return GetMemberIntern(type, propertyName, typeToRelationMemberMap, typeof(RelationMember));
}
public PrimitiveMember GetPrimitiveMember(Type type, String propertyName)
{
return GetMemberIntern(type, propertyName, typeToPrimitiveMemberMap, typeof(PrimitiveMember));
}
public Member GetMember(Type type, String propertyName)
{
return GetMemberIntern(type, propertyName, typeToMemberMap, typeof(Member));
}
protected T GetMemberIntern<T>(Type type, String propertyName, TypeAndStringWeakMap<T> map, Type baseType) where T : Member
{
WeakReference accessorR = map.Get(type, propertyName);
Member member = accessorR != null ? (Member)accessorR.Target : null;
if (member != null)
{
return (T)member;
}
member = (T)GetMemberIntern(type, propertyName, baseType);
if (member is RelationMember)
{
CascadeLoadMode? cascadeLoadMode = null;
CascadeAttribute cascadeAnnotation = (CascadeAttribute)member.GetAnnotation(typeof(CascadeAttribute));
if (cascadeAnnotation != null)
{
cascadeLoadMode = cascadeAnnotation.Load;
}
if (cascadeLoadMode == null || CascadeLoadMode.DEFAULT.Equals(cascadeLoadMode))
{
cascadeLoadMode = (CascadeLoadMode) Enum.Parse(typeof(CascadeLoadMode), Properties.GetString(
((RelationMember)member).IsToMany ? ServiceConfigurationConstants.ToManyDefaultCascadeLoadMode
: ServiceConfigurationConstants.ToOneDefaultCascadeLoadMode, CascadeLoadMode.DEFAULT.ToString()), false);
}
if (cascadeLoadMode == null || CascadeLoadMode.DEFAULT.Equals(cascadeLoadMode))
{
cascadeLoadMode = CascadeLoadMode.LAZY;
}
((IRelationMemberWrite)member).SetCascadeLoadMode(cascadeLoadMode.Value);
}
Object writeLock = this.writeLock;
lock (writeLock)
{
// concurrent thread might have been faster
accessorR = map.Get(type, propertyName);
Object existingMember = accessorR != null ? (T)accessorR.Target : null;
if (existingMember != null)
{
return (T)existingMember;
}
map.Put(type, propertyName, new WeakReference(member));
return (T)member;
}
}
protected Member GetMemberIntern(Type type, String propertyName, Type baseType)
{
if (propertyName.Contains("&"))
{
String[] compositePropertyNames = propertyName.Split('&');
PrimitiveMember[] members = new PrimitiveMember[compositePropertyNames.Length];
for (int a = compositePropertyNames.Length; a-- > 0; )
{
members[a] = (PrimitiveMember)GetMemberIntern(type, compositePropertyNames[a], baseType);
}
return CompositeIdFactory.CreateCompositeIdMember(type, members);
}
Type enhancedType = GetMemberTypeIntern(type, propertyName, baseType);
if (enhancedType == baseType)
{
throw new Exception("Must never happen. No enhancement for " + baseType + " has been done");
}
ConstructorInfo constructor = enhancedType.GetConstructor(Type.EmptyTypes);
return (Member)constructor.Invoke(EMPTY_OBJECTS);
}
protected Type GetMemberTypeIntern(Type targetType, String propertyName, Type baseType)
{
String memberTypeName = targetType.Name + "$" + baseType.Name + "$" + propertyName.Replace('.', '$');
//if (memberTypeName.StartsWith("java."))
//{
// memberTypeName = "ambeth." + memberTypeName;
//}
if (baseType == typeof(RelationMember))
{
return BytecodeEnhancer.GetEnhancedType(baseType, new RelationMemberEnhancementHint(targetType, propertyName));
}
return BytecodeEnhancer.GetEnhancedType(baseType, new MemberEnhancementHint(targetType, propertyName));
}
public IntermediatePrimitiveMember GetIntermediatePrimitiveMember(Type entityType, String propertyName)
{
String[] memberNamePath = EmbeddedMember.Split(propertyName);
Type currDeclaringType = entityType;
Member[] members = new Member[memberNamePath.Length];
for (int a = 0, size = memberNamePath.Length; a < size; a++)
{
IPropertyInfo property = PropertyInfoProvider.GetProperty(currDeclaringType, memberNamePath[a]);
if (property == null)
{
return null;
}
members[a] = new IntermediatePrimitiveMember(currDeclaringType, entityType, property.PropertyType, property.ElementType,
property.Name, property.GetAnnotations());
currDeclaringType = property.PropertyType;
}
if (members.Length > 1)
{
Member[] memberPath = new Member[members.Length - 1];
Array.Copy(members, 0, memberPath, 0, memberPath.Length);
PrimitiveMember lastMember = (PrimitiveMember)members[memberPath.Length];
return new IntermediateEmbeddedPrimitiveMember(entityType, lastMember.RealType, lastMember.ElementType, propertyName, memberPath,
lastMember);
}
return (IntermediatePrimitiveMember) members[0];
}
public IntermediateRelationMember GetIntermediateRelationMember(Type entityType, String propertyName)
{
String[] memberNamePath = EmbeddedMember.Split(propertyName);
Type currDeclaringType = entityType;
Member[] members = new Member[memberNamePath.Length];
for (int a = 0, size = memberNamePath.Length; a < size; a++)
{
IPropertyInfo property = PropertyInfoProvider.GetProperty(currDeclaringType, memberNamePath[a]);
if (property == null)
{
return null;
}
members[a] = new IntermediateRelationMember(currDeclaringType, entityType, property.PropertyType, property.ElementType,
property.Name, property.GetAnnotations());
currDeclaringType = property.PropertyType;
}
if (members.Length > 1)
{
Member[] memberPath = new Member[members.Length - 1];
Array.Copy(members, 0, memberPath, 0, memberPath.Length);
Member lastMember = members[memberPath.Length];
return new IntermediateEmbeddedRelationMember(entityType, lastMember.RealType, lastMember.ElementType, propertyName, memberPath,
lastMember);
}
return (IntermediateRelationMember) members[0];
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace OD4B.Configuration.AsyncWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.Setup;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Packets;
using QuantConnect.Notifications;
using QuantConnect.Statistics;
namespace QuantConnect.Lean.Engine.Results
{
/// <summary>
/// Console local resulthandler passes messages back to the console/local GUI display.
/// </summary>
public class ConsoleResultHandler : IResultHandler
{
private bool _isActive;
private bool _exitTriggered;
private DateTime _updateTime;
private DateTime _lastSampledTimed;
private IAlgorithm _algorithm;
private readonly object _chartLock;
private IConsoleStatusHandler _algorithmNode;
private IMessagingHandler _messagingHandler;
//Sampling Periods:
private DateTime _nextSample;
private TimeSpan _resamplePeriod;
private readonly TimeSpan _notificationPeriod;
private string _chartDirectory;
private readonly Dictionary<string, List<string>> _equityResults;
/// <summary>
/// A dictionary containing summary statistics
/// </summary>
public Dictionary<string, string> FinalStatistics { get; private set; }
/// <summary>
/// Messaging to store notification messages for processing.
/// </summary>
public ConcurrentQueue<Packet> Messages
{
get;
set;
}
/// <summary>
/// Local object access to the algorithm for the underlying Debug and Error messaging.
/// </summary>
public IAlgorithm Algorithm
{
get
{
return _algorithm;
}
set
{
_algorithm = value;
}
}
/// <summary>
/// Charts collection for storing the master copy of user charting data.
/// </summary>
public ConcurrentDictionary<string, Chart> Charts
{
get;
set;
}
/// <summary>
/// Boolean flag indicating the result hander thread is busy.
/// False means it has completely finished and ready to dispose.
/// </summary>
public bool IsActive {
get
{
return _isActive;
}
}
/// <summary>
/// Sampling period for timespans between resamples of the charting equity.
/// </summary>
/// <remarks>Specifically critical for backtesting since with such long timeframes the sampled data can get extreme.</remarks>
public TimeSpan ResamplePeriod
{
get
{
return _resamplePeriod;
}
}
/// <summary>
/// How frequently the backtests push messages to the browser.
/// </summary>
/// <remarks>Update frequency of notification packets</remarks>
public TimeSpan NotificationPeriod
{
get
{
return _notificationPeriod;
}
}
/// <summary>
/// Console result handler constructor.
/// </summary>
public ConsoleResultHandler()
{
Messages = new ConcurrentQueue<Packet>();
Charts = new ConcurrentDictionary<string, Chart>();
FinalStatistics = new Dictionary<string, string>();
_chartLock = new Object();
_isActive = true;
_notificationPeriod = TimeSpan.FromSeconds(5);
_equityResults = new Dictionary<string, List<string>>();
}
/// <summary>
/// Initialize the result handler with this result packet.
/// </summary>
/// <param name="packet">Algorithm job packet for this result handler</param>
/// <param name="messagingHandler"></param>
/// <param name="api"></param>
/// <param name="dataFeed"></param>
/// <param name="setupHandler"></param>
/// <param name="transactionHandler"></param>
public void Initialize(AlgorithmNodePacket packet, IMessagingHandler messagingHandler, IApi api, IDataFeed dataFeed, ISetupHandler setupHandler, ITransactionHandler transactionHandler)
{
// we expect one of two types here, the backtest node packet or the live node packet
var job = packet as BacktestNodePacket;
if (job != null)
{
_algorithmNode = new BacktestConsoleStatusHandler(job);
}
else
{
var live = packet as LiveNodePacket;
if (live == null)
{
throw new ArgumentException("Unexpected AlgorithmNodeType: " + packet.GetType().Name);
}
_algorithmNode = new LiveConsoleStatusHandler(live);
}
_resamplePeriod = _algorithmNode.ComputeSampleEquityPeriod();
var time = DateTime.Now.ToString("yyyy-MM-dd-HH-mm");
_chartDirectory = Path.Combine("../../../Charts/", packet.AlgorithmId, time);
if (Directory.Exists(_chartDirectory))
{
foreach (var file in Directory.EnumerateFiles(_chartDirectory, "*.csv", SearchOption.AllDirectories))
{
File.Delete(file);
}
Directory.Delete(_chartDirectory, true);
}
Directory.CreateDirectory(_chartDirectory);
_messagingHandler = messagingHandler;
}
/// <summary>
/// Entry point for console result handler thread.
/// </summary>
public void Run()
{
try
{
while ( !_exitTriggered || Messages.Count > 0 )
{
Thread.Sleep(100);
var now = DateTime.UtcNow;
if (now > _updateTime)
{
_updateTime = now.AddSeconds(5);
_algorithmNode.LogAlgorithmStatus(_lastSampledTimed);
}
}
// Write Equity and EquityPerformance files in charts directory
foreach (var fileName in _equityResults.Keys)
{
File.WriteAllLines(fileName, _equityResults[fileName]);
}
}
catch (Exception err)
{
// unexpected error, we need to close down shop
Log.Error(err);
// quit the algorithm due to error
_algorithm.RunTimeError = err;
}
Log.Trace("ConsoleResultHandler: Ending Thread...");
_isActive = false;
}
/// <summary>
/// Send a debug message back to the browser console.
/// </summary>
/// <param name="message">Message we'd like shown in console.</param>
public void DebugMessage(string message)
{
Log.Trace(_algorithm.Time + ": Debug >> " + message);
}
/// <summary>
/// Send a logging message to the log list for storage.
/// </summary>
/// <param name="message">Message we'd in the log.</param>
public void LogMessage(string message)
{
Log.Trace(_algorithm.Time + ": Log >> " + message);
}
/// <summary>
/// Send a runtime error message back to the browser highlighted with in red
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="stacktrace">Stacktrace information string</param>
public void RuntimeError(string message, string stacktrace = "")
{
Log.Error(_algorithm.Time + ": Error >> " + message + (!string.IsNullOrEmpty(stacktrace) ? (" >> ST: " + stacktrace) : ""));
}
/// <summary>
/// Send an error message back to the console highlighted in red with a stacktrace.
/// </summary>
/// <param name="message">Error message we'd like shown in console.</param>
/// <param name="stacktrace">Stacktrace information string</param>
public void ErrorMessage(string message, string stacktrace = "")
{
Log.Error(_algorithm.Time + ": Error >> " + message + (!string.IsNullOrEmpty(stacktrace) ? (" >> ST: " + stacktrace) : ""));
}
/// <summary>
/// Add a sample to the chart specified by the chartName, and seriesName.
/// </summary>
/// <param name="chartName">String chart name to place the sample.</param>
/// <param name="seriesName">Series name for the chart.</param>
/// <param name="seriesType">Series type for the chart.</param>
/// <param name="time">Time for the sample</param>
/// <param name="value">Value for the chart sample.</param>
/// <param name="unit">Unit for the sample axis</param>
/// <param name="seriesIndex">Index of the series we're sampling</param>
/// <remarks>Sample can be used to create new charts or sample equity - daily performance.</remarks>
public void Sample(string chartName, string seriesName, int seriesIndex, SeriesType seriesType, DateTime time, decimal value, string unit = "$")
{
var chartFilename = Path.Combine(_chartDirectory, chartName + "-" + seriesName + ".csv");
lock (_chartLock)
{
// Add line to list in dictionary, will be written to file at the end
List<string> rows;
if (!_equityResults.TryGetValue(chartFilename, out rows))
{
rows = new List<string>();
_equityResults[chartFilename] = rows;
}
rows.Add(time + "," + value.ToString("F2", CultureInfo.InvariantCulture));
//Add a copy locally:
if (!Charts.ContainsKey(chartName))
{
Charts.AddOrUpdate(chartName, new Chart(chartName));
}
//Add the sample to our chart:
if (!Charts[chartName].Series.ContainsKey(seriesName))
{
Charts[chartName].Series.Add(seriesName, new Series(seriesName, seriesType, seriesIndex, unit));
}
//Add our value:
Charts[chartName].Series[seriesName].Values.Add(new ChartPoint(time, value));
}
}
/// <summary>
/// Sample the strategy equity at this moment in time.
/// </summary>
/// <param name="time">Current time</param>
/// <param name="value">Current equity value</param>
public void SampleEquity(DateTime time, decimal value)
{
Sample("Strategy Equity", "Equity", 0, SeriesType.Candle, time, value);
_lastSampledTimed = time;
}
/// <summary>
/// Sample today's algorithm daily performance value.
/// </summary>
/// <param name="time">Current time.</param>
/// <param name="value">Value of the daily performance.</param>
public void SamplePerformance(DateTime time, decimal value)
{
Sample("Strategy Equity", "Daily Performance", 1, SeriesType.Line, time, value, "%");
}
/// <summary>
/// Sample the current benchmark performance directly with a time-value pair.
/// </summary>
/// <param name="time">Current backtest date.</param>
/// <param name="value">Current benchmark value.</param>
/// <seealso cref="IResultHandler.Sample"/>
public void SampleBenchmark(DateTime time, decimal value)
{
Sample("Benchmark", "Benchmark", 0, SeriesType.Line, time, value);
}
/// <summary>
/// Analyse the algorithm and determine its security types.
/// </summary>
/// <param name="types">List of security types in the algorithm</param>
public void SecurityType(List<SecurityType> types)
{
//NOP
}
/// <summary>
/// Send an algorithm status update to the browser.
/// </summary>
/// <param name="algorithmId">Algorithm id for the status update.</param>
/// <param name="status">Status enum value.</param>
/// <param name="message">Additional optional status message.</param>
/// <remarks>In backtesting we do not send the algorithm status updates.</remarks>
public void SendStatusUpdate(string algorithmId, AlgorithmStatus status, string message = "")
{
Log.Trace("ConsoleResultHandler.SendStatusUpdate(): Algorithm Status: " + status + " : " + message);
}
/// <summary>
/// Sample the asset prices to generate plots.
/// </summary>
/// <param name="symbol">Symbol we're sampling.</param>
/// <param name="time">Time of sample</param>
/// <param name="value">Value of the asset price</param>
public void SampleAssetPrices(Symbol symbol, DateTime time, decimal value)
{
//NOP. Don't sample asset prices in console.
}
/// <summary>
/// Add a range of samples to the store.
/// </summary>
/// <param name="updates">Charting updates since the last sample request.</param>
public void SampleRange(List<Chart> updates)
{
lock (_chartLock)
{
foreach (var update in updates)
{
//Create the chart if it doesn't exist already:
if (!Charts.ContainsKey(update.Name))
{
Charts.AddOrUpdate(update.Name, new Chart(update.Name, update.ChartType));
}
//Add these samples to this chart.
foreach (var series in update.Series.Values)
{
//If we don't already have this record, its the first packet
if (!Charts[update.Name].Series.ContainsKey(series.Name))
{
Charts[update.Name].Series.Add(series.Name, new Series(series.Name, series.SeriesType));
}
//We already have this record, so just the new samples to the end:
Charts[update.Name].Series[series.Name].Values.AddRange(series.Values);
}
}
}
}
/// <summary>
/// Algorithm final analysis results dumped to the console.
/// </summary>
/// <param name="job">Lean AlgorithmJob task</param>
/// <param name="orders">Collection of orders from the algorithm</param>
/// <param name="profitLoss">Collection of time-profit values for the algorithm</param>
/// <param name="holdings">Current holdings state for the algorithm</param>
/// <param name="statisticsResults">Statistics information for the algorithm (empty if not finished)</param>
/// <param name="banner">Runtime statistics banner information</param>
public void SendFinalResult(AlgorithmNodePacket job, Dictionary<int, Order> orders, Dictionary<DateTime, decimal> profitLoss, Dictionary<string, Holding> holdings, StatisticsResults statisticsResults, Dictionary<string, string> banner)
{
// uncomment these code traces to help write regression tests
//Console.WriteLine("var statistics = new Dictionary<string, string>();");
// Bleh. Nicely format statistical analysis on your algorithm results. Save to file etc.
foreach (var pair in statisticsResults.Summary)
{
Log.Trace("STATISTICS:: " + pair.Key + " " + pair.Value);
//Console.WriteLine(string.Format("statistics.Add(\"{0}\",\"{1}\");", pair.Key, pair.Value));
}
//foreach (var pair in statisticsResults.RollingPerformances)
//{
// Log.Trace("ROLLINGSTATS:: " + pair.Key + " SharpeRatio: " + Math.Round(pair.Value.PortfolioStatistics.SharpeRatio, 3));
//}
FinalStatistics = statisticsResults.Summary;
}
/// <summary>
/// Set the Algorithm instance for ths result.
/// </summary>
/// <param name="algorithm">Algorithm we're working on.</param>
/// <remarks>While setting the algorithm the backtest result handler.</remarks>
public void SetAlgorithm(IAlgorithm algorithm)
{
_algorithm = algorithm;
}
/// <summary>
/// Terminate the result thread and apply any required exit proceedures.
/// </summary>
public void Exit()
{
_exitTriggered = true;
}
/// <summary>
/// Send a new order event to the browser.
/// </summary>
/// <remarks>In backtesting the order events are not sent because it would generate a high load of messaging.</remarks>
/// <param name="newEvent">New order event details</param>
public void OrderEvent(OrderEvent newEvent)
{
Log.Debug("ConsoleResultHandler.OrderEvent(): id:" + newEvent.OrderId + " >> Status:" + newEvent.Status + " >> Fill Price: " + newEvent.FillPrice.ToString("C") + " >> Fill Quantity: " + newEvent.FillQuantity);
}
/// <summary>
/// Set the current runtime statistics of the algorithm
/// </summary>
/// <param name="key">Runtime headline statistic name</param>
/// <param name="value">Runtime headline statistic value</param>
public void RuntimeStatistic(string key, string value)
{
Log.Trace("ConsoleResultHandler.RuntimeStatistic(): " + key + " : " + value);
}
/// <summary>
/// Clear the outstanding message queue to exit the thread.
/// </summary>
public void PurgeQueue()
{
Messages.Clear();
}
/// <summary>
/// Store result on desktop.
/// </summary>
/// <param name="packet">Packet of data to store.</param>
/// <param name="async">Store the packet asyncronously to speed up the thread.</param>
/// <remarks>Async creates crashes in Mono 3.10 if the thread disappears before the upload is complete so it is disabled for now.</remarks>
public void StoreResult(Packet packet, bool async = false)
{
// Do nothing.
}
/// <summary>
/// Provides an abstraction layer for live vs backtest packets to provide status/sampling to the AlgorithmManager
/// </summary>
/// <remarks>
/// Since we can run both live and back test from the console, we need two implementations of what to do
/// at certain times
/// </remarks>
private interface IConsoleStatusHandler
{
void LogAlgorithmStatus(DateTime current);
TimeSpan ComputeSampleEquityPeriod();
}
// uses a const 2 second sample equity period and does nothing for logging algorithm status
private class LiveConsoleStatusHandler : IConsoleStatusHandler
{
private readonly LiveNodePacket _job;
public LiveConsoleStatusHandler(LiveNodePacket _job)
{
this._job = _job;
}
public void LogAlgorithmStatus(DateTime current)
{
// later we can log daily %Gain if possible
}
public TimeSpan ComputeSampleEquityPeriod()
{
return TimeSpan.FromSeconds(2);
}
}
// computes sample equity period from 4000 samples evenly spaced over the backtest interval and logs %complete to log file
private class BacktestConsoleStatusHandler : IConsoleStatusHandler
{
private readonly BacktestNodePacket _job;
private double? _backtestSpanInDays;
public BacktestConsoleStatusHandler(BacktestNodePacket _job)
{
this._job = _job;
}
public void LogAlgorithmStatus(DateTime current)
{
if (!_backtestSpanInDays.HasValue)
{
_backtestSpanInDays = Math.Round((_job.PeriodFinish - _job.PeriodStart).TotalDays);
if (_backtestSpanInDays == 0.0)
{
_backtestSpanInDays = null;
}
}
// we need to wait until we've called initialize on the algorithm
// this is not ideal at all
if (_backtestSpanInDays.HasValue)
{
var daysProcessed = (current - _job.PeriodStart).TotalDays;
if (daysProcessed < 0) daysProcessed = 0;
if (daysProcessed > _backtestSpanInDays.Value) daysProcessed = _backtestSpanInDays.Value;
Log.Trace("Progress: " + (daysProcessed * 100 / _backtestSpanInDays.Value).ToString("F2") + "% Processed: " + daysProcessed.ToString("0.000") + " days of total: " + (int)_backtestSpanInDays.Value);
}
else
{
Log.Trace("Initializing...");
}
}
public TimeSpan ComputeSampleEquityPeriod()
{
const double samples = 4000;
const double minimumSamplePeriod = 4 * 60;
double resampleMinutes = minimumSamplePeriod;
var totalMinutes = (_job.PeriodFinish - _job.PeriodStart).TotalMinutes;
// before initialize is called this will be zero
if (totalMinutes > 0.0)
{
resampleMinutes = (totalMinutes < (minimumSamplePeriod * samples)) ? minimumSamplePeriod : (totalMinutes / samples);
}
// set max value
if (resampleMinutes < minimumSamplePeriod)
{
resampleMinutes = minimumSamplePeriod;
}
return TimeSpan.FromMinutes(resampleMinutes);
}
}
/// <summary>
/// Not used
/// </summary>
public void SetChartSubscription(string symbol)
{
//
}
/// <summary>
/// Process the synchronous result events, sampling and message reading.
/// This method is triggered from the algorithm manager thread.
/// </summary>
/// <remarks>Prime candidate for putting into a base class. Is identical across all result handlers.</remarks>
public void ProcessSynchronousEvents(bool forceProcess = false)
{
var time = _algorithm.Time;
if (time > _nextSample || forceProcess)
{
//Set next sample time: 4000 samples per backtest
_nextSample = time.Add(ResamplePeriod);
//Sample the portfolio value over time for chart.
SampleEquity(time, Math.Round(_algorithm.Portfolio.TotalPortfolioValue, 4));
//Also add the user samples / plots to the result handler tracking:
SampleRange(_algorithm.GetChartUpdates());
//Sample the asset pricing:
foreach (var security in _algorithm.Securities.Values)
{
SampleAssetPrices(security.Symbol, time, security.Price);
}
}
//Send out the debug messages:
_algorithm.DebugMessages.ForEach(x => DebugMessage(x));
_algorithm.DebugMessages.Clear();
//Send out the error messages:
_algorithm.ErrorMessages.ForEach(x => ErrorMessage(x));
_algorithm.ErrorMessages.Clear();
//Send out the log messages:
_algorithm.LogMessages.ForEach(x => LogMessage(x));
_algorithm.LogMessages.Clear();
//Set the running statistics:
foreach (var pair in _algorithm.RuntimeStatistics)
{
RuntimeStatistic(pair.Key, pair.Value);
}
// Dequeue and processes notification messages
//Send all the notification messages but timeout within a second
var start = DateTime.Now;
while (_algorithm.Notify.Messages.Count > 0 && DateTime.Now < start.AddSeconds(1))
{
Notification message;
if (_algorithm.Notify.Messages.TryDequeue(out message))
{
//Process the notification messages:
Log.Trace("ConsoleResultHandler.ProcessSynchronousEvents(): Processing Notification...");
switch (message.GetType().Name)
{
case "NotificationEmail":
_messagingHandler.Email(message as NotificationEmail);
break;
case "NotificationSms":
_messagingHandler.Sms(message as NotificationSms);
break;
case "NotificationWeb":
_messagingHandler.Web(message as NotificationWeb);
break;
default:
try
{
//User code.
message.Send();
}
catch (Exception err)
{
Log.Error(err, "Custom send notification:");
ErrorMessage("Custom send notification: " + err.Message, err.StackTrace);
}
break;
}
}
}
}
} // End Result Handler Thread:
} // End Namespace
| |
using System;
using System.Globalization;
using System.Linq;
using NUnit.Framework;
using SIL.Archiving.Generic;
using SIL.Archiving.IMDI;
using SIL.Archiving.IMDI.Lists;
using SIL.Archiving.IMDI.Schema;
using SIL.TestUtilities;
namespace SIL.Archiving.Tests
{
[TestFixture]
[OfflineSldr]
[Category("Archiving")]
class IMDI30Tests
{
[Test]
public void SessionDate_DateTime_ValidStringProduced()
{
var session = new Session();
var dateIn = DateTime.Today;
session.SetDate(dateIn);
var dateOut = session.Date;
Assert.AreEqual(dateIn.ToString("yyyy-MM-dd"), dateOut, "The date returned was not what was expected.");
}
[Test]
public void SessionDate_YearOnly_ValidStringProduced()
{
var session = new Session();
const int dateIn = 1964;
session.SetDate(dateIn);
var dateOut = session.Date;
Assert.AreEqual(dateIn.ToString(CultureInfo.InvariantCulture), dateOut, "The date returned was not what was expected.");
}
[Test]
public void SessionDate_DateRange_ValidStringProduced()
{
var session = new Session();
const string dateIn = "2013-11-20 to 2013-11-25";
session.SetDate(dateIn);
var dateOut = session.Date;
Assert.AreEqual(dateIn, dateOut, "The date returned was not what was expected.");
}
[Test]
public void ActorType_ArchivingActor_ValidActorType()
{
const string motherTongueIso3 = "spa";
const string primaryLanguageIso3 = "eng";
const string additionalLanguageIso3 = "fra";
var actrIn = new ArchivingActor
{
Code = "123",
Education = "8th grade",
Name = "John Smith",
Age = "50 +- 10",
Gender = "Male",
BirthDate = 1964,
Occupation = "Nerf Herder",
MotherTongueLanguage = new ArchivingLanguage(motherTongueIso3),
PrimaryLanguage = new ArchivingLanguage(primaryLanguageIso3)
};
// additional languages
actrIn.Iso3Languages.Add(new ArchivingLanguage(additionalLanguageIso3));
var actrOut = new ActorType(actrIn);
Assert.AreEqual(actrIn.Name, actrOut.FullName);
Assert.AreEqual(actrIn.Name, actrOut.Name[0]);
Assert.AreEqual(actrIn.Code, actrOut.Code);
Assert.AreEqual(actrIn.Gender, actrOut.Sex.Value);
Assert.AreEqual(actrIn.Occupation, actrOut.Keys.Key.Find(k => k.Name == "Occupation").Value);
Assert.AreEqual(actrIn.GetBirthDate(), actrOut.BirthDate);
Assert.AreEqual(actrIn.Age, actrOut.Age);
// language count
Assert.AreEqual(3, actrOut.Languages.Language.Count);
// mother tongue
string motherTongueCodeFound = null;
foreach (var lang in actrOut.Languages.Language)
{
if (lang.MotherTongue.Value == BooleanEnum.@true)
motherTongueCodeFound = lang.Id;
}
Assert.IsNotNull(motherTongueCodeFound, "Mother tongue not found.");
Assert.AreEqual(motherTongueIso3, motherTongueCodeFound.Substring(motherTongueCodeFound.Length - 3), "Wrong mother tongue returned.");
// primary language
string primaryLanguageCodeFound = null;
foreach (var lang in actrOut.Languages.Language)
{
if (lang.PrimaryLanguage.Value == BooleanEnum.@true)
primaryLanguageCodeFound = lang.Id;
}
Assert.IsNotNull(primaryLanguageCodeFound, "Primary language not found.");
Assert.AreEqual(primaryLanguageIso3, primaryLanguageCodeFound.Substring(primaryLanguageCodeFound.Length - 3), "Wrong primary language returned.");
// additional language
var additionalLanguageFound = false;
foreach (var lang in actrOut.Languages.Language)
{
if (lang.Id.EndsWith(additionalLanguageIso3))
additionalLanguageFound = true;
}
Assert.IsTrue(additionalLanguageFound, "The additional language was not found.");
}
[Test]
public void LocationType_ArchivingLocation_ValidLocationType()
{
var locIn = new ArchivingLocation
{
Continent = "Asia",
Country = "China",
Region = "Great Wall",
Address = "315 N Main St"
};
var locOut = locIn.ToIMDILocationType();
Assert.AreEqual("Asia", locOut.Continent.Value);
Assert.AreEqual("China", locOut.Country.Value);
Assert.AreEqual("Great Wall", locOut.Region[0]);
Assert.AreEqual("315 N Main St", locOut.Address);
}
[Test]
public void SetContinent_InvalidContinent_ReturnsUnspecified()
{
LocationType location = new LocationType();
location.SetContinent("Narnia");
Assert.AreEqual("Unspecified", location.Continent.Value);
}
[Test]
public void AddDescription_Add2ForSameLanguage_AddsOnlyTheFirst()
{
var desc1 = new LanguageString { Iso3LanguageId = "eng", Value = "First description"};
var desc2 = new LanguageString { Iso3LanguageId = "eng", Value = "Second description" };
var obj = new Corpus();
obj.Description.Add(desc1);
obj.Description.Add(desc2);
Assert.AreEqual(1, obj.Description.Count);
Assert.AreEqual("First description", obj.Description.First().Value);
}
[Test]
public void AddSubjectLanguge_AddDuplicate_DuplicateNotAdded()
{
IMDIPackage proj = new IMDIPackage(false, string.Empty);
proj.ContentIso3Languages.Add(new ArchivingLanguage("fra"));
proj.ContentIso3Languages.Add(new ArchivingLanguage("spa"));
proj.ContentIso3Languages.Add(new ArchivingLanguage("spa"));
proj.ContentIso3Languages.Add(new ArchivingLanguage("fra"));
Assert.AreEqual(2, proj.ContentIso3Languages.Count);
Assert.IsTrue(proj.ContentIso3Languages.Contains(new ArchivingLanguage("fra")));
Assert.IsTrue(proj.ContentIso3Languages.Contains(new ArchivingLanguage("spa")));
}
[Test]
public void AddDocumentLanguge_AddDuplicate_DuplicateNotAdded()
{
IMDIPackage proj = new IMDIPackage(false, string.Empty);
proj.MetadataIso3Languages.Add(new ArchivingLanguage("fra"));
proj.MetadataIso3Languages.Add(new ArchivingLanguage("spa"));
proj.MetadataIso3Languages.Add(new ArchivingLanguage("spa"));
proj.MetadataIso3Languages.Add(new ArchivingLanguage("fra"));
Assert.AreEqual(2, proj.MetadataIso3Languages.Count);
Assert.IsTrue(proj.MetadataIso3Languages.Contains(new ArchivingLanguage("fra")));
Assert.IsTrue(proj.MetadataIso3Languages.Contains(new ArchivingLanguage("spa")));
}
[Test]
public void SessionAddActor_Anonymized_ReturnsAnonymizedNames()
{
ArchivingActor actor = new ArchivingActor
{
Name = "Actor Name",
FullName = "Actor Full Name",
Anonymize = true
};
Session session = new Session();
session.AddActor(actor);
var imdiActor = session.MDGroup.Actors.Actor[0];
Assert.AreNotEqual("Actor Name", imdiActor.Name[0]);
Assert.AreNotEqual("Actor Full Name", imdiActor.FullName);
}
[Test]
public void SessionAddActor_Anonymized_RemovesActorFiles()
{
ArchivingActor actor = new ArchivingActor
{
Name = "Actor Name",
FullName = "Actor Full Name",
Anonymize = true
};
actor.Files.Add(new ArchivingFile(System.Reflection.Assembly.GetExecutingAssembly().Location));
Session session = new Session();
session.AddActor(actor);
Assert.AreEqual(0, session.Resources.MediaFile.Count);
Assert.AreEqual(0, session.Resources.WrittenResource.Count);
}
[Test]
public void FindByISO3Code_InvalidIso3Code_MustBeInList_Throws()
{
Assert.Throws<ArgumentException>(() => LanguageList.FindByISO3Code("xyz", true));
}
[Test]
public void FindByISO3Code_InvalidIso3Code_NotMustBeInList_DoesNotThrow()
{
Assert.DoesNotThrow(() => LanguageList.FindByISO3Code("xyz", false));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetList_RemoveNone_ReturnUnknownAndUnspecified()
{
var countries = ListConstructor.GetList(ListType.Countries, true, null, ListConstructor.RemoveUnknown.RemoveNone);
Assert.NotNull(countries.FindByText("Unknown"));
Assert.NotNull(countries.FindByText("Unspecified"));
Assert.NotNull(countries.FindByText("Undefined"));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetList_LeaveUnknown_ReturnUnspecified()
{
var countries = ListConstructor.GetList(ListType.Countries, true, null, ListConstructor.RemoveUnknown.LeaveUnknown);
Assert.NotNull(countries.FindByText("Unknown"));
Assert.IsNull(countries.FindByText("Unspecified"));
Assert.IsNull(countries.FindByText("Undefined"));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetList_RemoveAll_ReturnNone()
{
var countries = ListConstructor.GetList(ListType.Countries, true, null, ListConstructor.RemoveUnknown.RemoveAll);
Assert.IsNull(countries.FindByText("Unknown"));
Assert.IsNull(countries.FindByText("Unspecified"));
Assert.IsNull(countries.FindByText("Undefined"));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetClosedList_RemoveNone_ReturnUnknownAndUnspecified()
{
var countries = ListConstructor.GetClosedList(ListType.Countries, true, ListConstructor.RemoveUnknown.RemoveNone);
Assert.NotNull(countries.FindByText("Unknown"));
Assert.NotNull(countries.FindByText("Unspecified"));
Assert.NotNull(countries.FindByText("Undefined"));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetClosedList_LeaveUnknown_ReturnUnspecified()
{
var countries = ListConstructor.GetClosedList(ListType.Countries, true, ListConstructor.RemoveUnknown.LeaveUnknown);
Assert.NotNull(countries.FindByText("Unknown"));
Assert.IsNull(countries.FindByText("Unspecified"));
Assert.IsNull(countries.FindByText("Undefined"));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetClosedList_RemoveAll_ReturnNone()
{
var countries = ListConstructor.GetClosedList(ListType.Countries, true, ListConstructor.RemoveUnknown.RemoveAll);
Assert.IsNull(countries.FindByText("Unknown"));
Assert.IsNull(countries.FindByText("Unspecified"));
Assert.IsNull(countries.FindByText("Undefined"));
}
[Test]
public void SetSessionGenre_NullValue_Null()
{
var session = new Session();
session.Genre = null;
Assert.AreEqual(null, session.Genre);
}
[Test]
public void SetSessionGenre_ContainsAngleBrackets_LatinOnly()
{
var session = new Session();
session.Genre = "<Unknown>";
Assert.AreEqual("Unknown", session.Genre);
}
[Test]
public void SessionAddKeyValuePair_TwoKeywords_numberUp2()
{
var session = new Session();
var number = session.MDGroup.Content.Keys.Key.Count;
session.AddContentKeyValuePair("keyword", "holiday");
session.AddContentKeyValuePair("keyword", "emotion");
Assert.AreEqual(number + 2, session.MDGroup.Content.Keys.Key.Count);
}
}
}
| |
using System.Text.RegularExpressions;
using NuGet.Resources;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
namespace NuGet
{
public class LocalPackageRepository : PackageRepositoryBase, IPackageLookup
{
private static readonly ConcurrentDictionary<string, PackageCacheEntry> _packageCache = new ConcurrentDictionary<string, PackageCacheEntry>(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<PackageName, string> _packagePathLookup = new ConcurrentDictionary<PackageName, string>();
private readonly bool _enableCaching;
public LocalPackageRepository(string physicalPath)
: this(physicalPath, enableCaching: true)
{
}
public LocalPackageRepository(string physicalPath, bool enableCaching)
: this(new DefaultPackagePathResolver(physicalPath),
new PhysicalFileSystem(physicalPath),
enableCaching)
{
}
public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem)
: this(pathResolver, fileSystem, enableCaching: true)
{
}
public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem, bool enableCaching)
{
if (pathResolver == null)
{
throw new ArgumentNullException("pathResolver");
}
if (fileSystem == null)
{
throw new ArgumentNullException("fileSystem");
}
FileSystem = fileSystem;
PathResolver = pathResolver;
_enableCaching = enableCaching;
}
public override string Source
{
get
{
return FileSystem.Root;
}
}
public IPackagePathResolver PathResolver
{
get;
set;
}
public override bool SupportsPrereleasePackages
{
get { return true; }
}
protected IFileSystem FileSystem
{
get;
private set;
}
public override IQueryable<IPackage> GetPackages()
{
return GetPackages(OpenPackage).AsQueryable();
}
public override void AddPackage(IPackage package)
{
if (PackageSaveMode.HasFlag(PackageSaveModes.Nuspec))
{
// Starting from 2.1, we save the nuspec file into the subdirectory with the name as <packageId>.<version>
// for example, for jQuery version 1.0, it will be "jQuery.1.0\\jQuery.1.0.nuspec"
string packageFilePath = GetManifestFilePath(package.Id, package.Version);
Manifest manifest = Manifest.Create(package);
// The IPackage object doesn't carry the References information.
// Thus we set the References for the manifest to the set of all valid assembly references
manifest.Metadata.ReferenceSets = package.AssemblyReferences
.GroupBy(f => f.TargetFramework)
.Select(
g => new ManifestReferenceSet
{
TargetFramework = g.Key == null ? null : VersionUtility.GetFrameworkString(g.Key),
References = g.Select(p => new ManifestReference { File = p.Name }).ToList()
})
.ToList();
FileSystem.AddFileWithCheck(packageFilePath, manifest.Save);
UpdateAllPackageNodesAddFile(packageFilePath);
}
if (PackageSaveMode.HasFlag(PackageSaveModes.Nupkg))
{
string packageFilePath = GetPackageFilePath(package);
FileSystem.AddFileWithCheck(packageFilePath, package.GetStream);
UpdateAllPackageNodesAddFile(packageFilePath);
}
}
private void UpdateAllPackageNodesAddFile(string packageFilePath)
{
lock (_allPackageNodes)
{
RootNamingTreeNode rootNode;
if (_allPackageNodes.TryGetValue(Path.GetExtension(packageFilePath) ?? "", out rootNode))
{
rootNode.AddFile(packageFilePath);
}
}
}
public override void RemovePackage(IPackage package)
{
string manifestFilePath = GetManifestFilePath(package.Id, package.Version);
if (FileSystem.FileExists(manifestFilePath))
{
// delete .nuspec file
FileSystem.DeleteFileSafe(manifestFilePath);
}
// Delete the package file
string packageFilePath = GetPackageFilePath(package);
FileSystem.DeleteFileSafe(packageFilePath);
// Delete the package directory if any
FileSystem.DeleteDirectorySafe(PathResolver.GetPackageDirectory(package), recursive: false);
// If this is the last package delete the package directory
if (!FileSystem.GetFilesSafe(String.Empty).Any() &&
!FileSystem.GetDirectoriesSafe(String.Empty).Any())
{
FileSystem.DeleteDirectorySafe(String.Empty, recursive: false);
}
}
readonly Dictionary<string, IPackage> _findPackageCache=new Dictionary<string, IPackage>();
public virtual IPackage FindPackage(string packageId, SemanticVersion version)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
if (version == null)
{
throw new ArgumentNullException("version");
}
IPackage findPackage ;
string key = packageId + "." + version.ToNormalizedString();
if (_enableCaching ) lock (_findPackageCache) if (_findPackageCache.TryGetValue(key, out findPackage)) return findPackage;
findPackage = FindPackage(OpenPackage, packageId, version);
if (_enableCaching && findPackage!=null) lock (_findPackageCache) _findPackageCache.Add(key, findPackage);
return findPackage;
}
public virtual IEnumerable<IPackage> FindPackagesById(string packageId)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
return FindPackagesById(OpenPackage, packageId);
}
public virtual bool Exists(string packageId, SemanticVersion version)
{
return FindPackage(packageId, version) != null;
}
public virtual IEnumerable<string> GetPackageLookupPaths(string packageId, SemanticVersion version)
{
// Files created by the path resolver. This would take into account the non-side-by-side scenario
// and we do not need to match this for id and version.
var packageFileName = PathResolver.GetPackageFileName(packageId, version);
var manifestFileName = Path.ChangeExtension(packageFileName, Constants.ManifestExtension);
var filesMatchingFullName = Enumerable.Concat(
GetPackageFiles(packageFileName),
GetPackageFiles(manifestFileName));
if (version != null && version.Version.Revision < 1)
{
// If the build or revision number is not set, we need to look for combinations of the format
// * Foo.1.2.nupkg
// * Foo.1.2.3.nupkg
// * Foo.1.2.0.nupkg
// * Foo.1.2.0.0.nupkg
// To achieve this, we would look for files named 1.2*.nupkg if both build and revision are 0 and
// 1.2.3*.nupkg if only the revision is set to 0.
string partialName = version.Version.Build < 1 ?
String.Join(".", packageId, version.Version.Major, version.Version.Minor) :
String.Join(".", packageId, version.Version.Major, version.Version.Minor, version.Version.Build);
string partialManifestName = partialName + "*" + Constants.ManifestExtension;
partialName += "*" + Constants.PackageExtension;
// Partial names would result is gathering package with matching major and minor but different build and revision.
// Attempt to match the version in the path to the version we're interested in.
var partialNameMatches = GetPackageFiles(partialName).Where(path => FileNameMatchesPattern(packageId, version, path));
var partialManifestNameMatches = GetPackageFiles(partialManifestName).Where(
path => FileNameMatchesPattern(packageId, version, path));
return Enumerable.Concat(filesMatchingFullName, partialNameMatches).Concat(partialManifestNameMatches);
}
return filesMatchingFullName;
}
internal IPackage FindPackage(Func<string, IPackage> openPackage, string packageId, SemanticVersion version)
{
var lookupPackageName = new PackageName(packageId, version);
string packagePath;
// If caching is enabled, check if we have a cached path. Additionally, verify that the file actually exists on disk since it might have moved.
if (_enableCaching &&
_packagePathLookup.TryGetValue(lookupPackageName, out packagePath) &&
FileSystem.FileExists(packagePath))
{
// When depending on the cached path, verify the file exists on disk.
return GetPackage(openPackage, packagePath);
}
// Lookup files which start with the name "<Id>." and attempt to match it with all possible version string combinations (e.g. 1.2.0, 1.2.0.0)
// before opening the package. To avoid creating file name strings, we attempt to specifically match everything after the last path separator
// which would be the file name and extension.
return (from path in GetPackageLookupPaths(packageId, version)
let package = GetPackage(openPackage, path)
where lookupPackageName.Equals(new PackageName(package.Id, package.Version))
select package).FirstOrDefault();
}
internal IEnumerable<IPackage> FindPackagesById(Func<string, IPackage> openPackage, string packageId)
{
Debug.Assert(!String.IsNullOrEmpty(packageId), "The caller has to ensure packageId is never null.");
HashSet<IPackage> packages = new HashSet<IPackage>(PackageEqualityComparer.IdAndVersion);
// get packages through nupkg files
packages.AddRange(
GetPackages(
openPackage,
packageId,
GetPackageFiles(packageId + ".*" + Constants.PackageExtension)));
// then, get packages through nuspec files
packages.AddRange(
GetPackages(
openPackage,
packageId,
GetPackageFiles(packageId + ".*" + Constants.ManifestExtension)));
return packages;
}
internal IEnumerable<IPackage> GetPackages(Func<string, IPackage> openPackage,
string packageId,
IEnumerable<string> packagePaths)
{
foreach (var path in packagePaths)
{
IPackage package = null;
try
{
package = GetPackage(openPackage, path);
}
catch (InvalidOperationException)
{
// ignore error for unzipped packages (nuspec files).
if (string.Equals(
Constants.ManifestExtension,
Path.GetExtension(path),
StringComparison.OrdinalIgnoreCase))
{
}
else
{
throw;
}
}
if (package != null && package.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase))
{
yield return package;
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We want to suppress all errors opening a package")]
internal IEnumerable<IPackage> GetPackages(Func<string, IPackage> openPackage)
{
return GetPackageFiles()
.Select(path =>
{
try
{
return GetPackage(openPackage, path);
}
catch
{
return null;
}
})
.Where(p => p != null);
}
private IPackage GetPackage(Func<string, IPackage> openPackage, string path)
{
PackageCacheEntry cacheEntry;
DateTimeOffset lastModified = FileSystem.GetLastModified(path);
// If we never cached this file or we did and it's current last modified time is newer
// create a new entry
if (!_packageCache.TryGetValue(path, out cacheEntry) ||
(cacheEntry != null && lastModified > cacheEntry.LastModifiedTime))
{
// We need to do this so we capture the correct loop variable
// Console.WriteLine("Adding {0} to cache",path);
string packagePath = path;
// Create the package
IPackage package = openPackage(packagePath);
// create a cache entry with the last modified time
cacheEntry = new PackageCacheEntry(package, lastModified);
if (_enableCaching)
{
// Store the entry
_packageCache[packagePath] = cacheEntry;
_packagePathLookup.GetOrAdd(new PackageName(package.Id, package.Version), path);
}
}
return cacheEntry.Package;
}
//key: extension
private readonly Dictionary<string, RootNamingTreeNode> _allPackageNodes=new Dictionary<string, RootNamingTreeNode>();
internal IEnumerable<string> GetPackageFiles(string filter = null)
{
filter = filter ?? "*" + Constants.PackageExtension;
Debug.Assert(
filter.EndsWith(Constants.PackageExtension, StringComparison.OrdinalIgnoreCase) ||
filter.EndsWith(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase));
// Check for package files one level deep. We use this at package install time
// to determine the set of installed packages. Installed packages are copied to
// {id}.{version}\{packagefile}.{extension}.
string extension = Path.GetExtension(filter);
RootNamingTreeNode knownPackages;
lock (_allPackageNodes)
{
if (!_allPackageNodes.TryGetValue(extension, out knownPackages))
{
knownPackages = PreparePackages(extension);
_allPackageNodes[extension] = knownPackages;
}
}
IEnumerable<string> result = knownPackages.GetFiltered(filter);
/* if (result.Count() != GetPackageFilesTest(filter).Count())
{
}*/
return result;
/*
foreach (var dir in FileSystem.GetDirectories(String.Empty))
{
foreach (var path in FileSystem.GetFiles(dir, filter))
{
yield return path;
}
}
// Check top level directory
foreach (var path in FileSystem.GetFiles(String.Empty, filter))
{
yield return path;
}*/
}
/* internal IEnumerable<string> GetPackageFilesTest(string filter )
{
foreach (var dir in FileSystem.GetDirectories(String.Empty))
{
foreach (var path in FileSystem.GetFiles(dir, filter))
{
yield return path;
}
}
// Check top level directory
foreach (var path in FileSystem.GetFiles(String.Empty, filter))
{
yield return path;
}
}*/
private RootNamingTreeNode PreparePackages(string extension)
{
var allPackages=new List<string>();
foreach (var dir in FileSystem.GetDirectories(String.Empty))
{
allPackages.AddRange(FileSystem.GetFiles(dir, "*"+extension));
}
// Check top level directory
allPackages.AddRange(FileSystem.GetFiles(String.Empty, "*" + extension));
return new RootNamingTreeNode(allPackages);
}
private static readonly Regex PackageNameRegex = new Regex(@"^(.+)\.\d+\.\d+\.\d+\.\d+.*$",RegexOptions.Compiled);
private class RootNamingTreeNode
{
private readonly List<string> _allPackages;
private NamingTreeNode _rootNode;
public RootNamingTreeNode(List<string> allPackages)
{
_allPackages = allPackages;
RebuildNodes();
}
private void RebuildNodes()
{
_rootNode=new NamingTreeNode(null, _allPackages.Select(x => new PackagePath { FileName = Path.GetFileNameWithoutExtension(x), FullPath = x }).ToArray());
}
public void AddFile(string fileName)
{
if (!_allPackages.Contains(fileName))
{
_allPackages.Add(fileName);
RebuildNodes();
}
}
public void RemoveFile(string fileName)
{
if (_allPackages.Contains(fileName))
{
_allPackages.Remove(fileName);
RebuildNodes();
}
}
public IEnumerable<string> GetFiltered(string filter)
{
return _rootNode.GetFiltered(filter);
}
}
private class NamingTreeNode
{
/// <summary>
/// plne cesty
/// </summary>
private readonly PackagePath[] _leaves;
private readonly Dictionary<string, NamingTreeNode> _subNodes;
private readonly string _baseName;
public NamingTreeNode(string baseName, IEnumerable<PackagePath> paths)
{
_baseName = baseName;
List<PackagePath> leavesList = new List<PackagePath>();
Dictionary<string,List<PackagePath>> subnodesList=new Dictionary<string, List<PackagePath>>();
foreach (PackagePath packagePath in paths)
{
string fileName = packagePath.FileName;
if (baseName != null)
{
fileName=fileName.Remove(0, baseName.Length);
}
string[] parts = fileName.Split(new []{'.'},2);
if (parts.Length == 1)
{
leavesList.Add(packagePath);
}
else
{
string key = (((baseName != null) ? (baseName) : "") + parts[0] + ".").ToUpper();
List<PackagePath> subpackagesByKey;
if (!subnodesList.TryGetValue(key, out subpackagesByKey))
{
subpackagesByKey=new List<PackagePath>();
subnodesList.Add(key,subpackagesByKey);
}
subpackagesByKey.Add(packagePath);
}
}
if (leavesList.Count > 0) _leaves = leavesList.ToArray();
if (subnodesList.Count > 0)
{
_subNodes=new Dictionary<string, NamingTreeNode>();
foreach (KeyValuePair<string, List<PackagePath>> keyValuePair in subnodesList)
{
_subNodes.Add(keyValuePair.Key, new NamingTreeNode(keyValuePair.Key, keyValuePair.Value));
}
}
}
public IEnumerable<string> GetFiltered(string filter)
{
List<string> result=new List<string>();
FillByFilterRecursive(result, Path.GetFileNameWithoutExtension(filter), Path.GetFileNameWithoutExtension(filter));
return result;
}
private void FillByFilterRecursive(List<string> result, string filter, string fullFilterWithoutExtension)
{
string[] parts = filter.Split(new[] { '.' }, 2);
if (parts.Length == 2 && !parts[0].Contains("*"))
{
string key = ((_baseName??"")+ parts[0] + '.').ToUpper();
NamingTreeNode node;
if (_subNodes!=null)
if (_subNodes.TryGetValue(key, out node))
{
node.FillByFilterRecursive(result, parts[1], fullFilterWithoutExtension);
}
return;
}
if (_baseName == null)
{
}
string[] strings = fullFilterWithoutExtension.Split('*');
if (strings.Length>2)
{
Regex reg = new Regex("^" + fullFilterWithoutExtension.Replace(".",@"\.").Replace("*", ".*") + "$",RegexOptions.IgnoreCase);
result.AddRange(GetAllLeavesRecursive().Where(x => reg.IsMatch(x.FileName)).Select(x=>x.FullPath));
}
else
if (strings.Length == 2)
{
result.AddRange(GetAllLeavesRecursive().Where(x => x.FileName.StartsWith(strings[0],StringComparison.InvariantCultureIgnoreCase) && x.FileName.EndsWith(strings[1],StringComparison.InvariantCultureIgnoreCase)).Select(x=>x.FullPath));
}
else
{
result.AddRange(GetAllLeavesRecursive().Where(x=>String.Compare(x.FileName,fullFilterWithoutExtension,StringComparison.InvariantCultureIgnoreCase)==0).Select(x=>x.FullPath));
}
}
private IEnumerable<PackagePath> GetAllLeavesRecursive()
{
if (_leaves == null && _subNodes == null) return new PackagePath[0];
if (_leaves != null && _subNodes == null) return _leaves;
List<PackagePath> results = new List<PackagePath>();
if (_leaves!=null)
results.AddRange(_leaves);
foreach (NamingTreeNode namingTreeNode in _subNodes.Values)
{
results.AddRange(namingTreeNode.GetAllLeavesRecursive());
}
return results;
}
}
private struct PackagePath
{
public string FileName;
public string FullPath;
}
private static string GetPackageName(string path)
{
string fileName = Path.GetFileName(path);
if (fileName == null) return String.Empty;
Match match = PackageNameRegex.Match(fileName);
if (match.Success)
{
return match.Groups[1].Value;
}
return String.Empty;
}
internal virtual IPackage OpenPackage(string path)
{
if (!FileSystem.FileExists(path))
{
return null;
}
if (string.Equals(Path.GetExtension(path), Constants.PackageExtension, StringComparison.OrdinalIgnoreCase))
{
OptimizedZipPackage package;
try
{
package = new OptimizedZipPackage(FileSystem, path);
}
catch (FileFormatException ex)
{
throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ErrorReadingPackage, path), ex);
}
// Set the last modified date on the package
package.Published = FileSystem.GetLastModified(path);
return package;
}
else if (Path.GetExtension(path) == Constants.ManifestExtension)
{
if (FileSystem.FileExists(path))
{
return new UnzippedPackage(FileSystem, Path.GetFileNameWithoutExtension(path));
}
}
return null;
}
protected virtual string GetPackageFilePath(IPackage package)
{
return Path.Combine(PathResolver.GetPackageDirectory(package),
PathResolver.GetPackageFileName(package));
}
protected virtual string GetPackageFilePath(string id, SemanticVersion version)
{
return Path.Combine(PathResolver.GetPackageDirectory(id, version),
PathResolver.GetPackageFileName(id, version));
}
private static bool FileNameMatchesPattern(string packageId, SemanticVersion version, string path)
{
var name = Path.GetFileNameWithoutExtension(path);
SemanticVersion parsedVersion;
// When matching by pattern, we will always have a version token. Packages without versions would be matched early on by the version-less path resolver
// when doing an exact match.
return name.Length > packageId.Length &&
SemanticVersion.TryParse(name.Substring(packageId.Length + 1), out parsedVersion) &&
parsedVersion == version;
}
private string GetManifestFilePath(string packageId, SemanticVersion version)
{
string packageDirectory = PathResolver.GetPackageDirectory(packageId, version);
string manifestFileName = packageDirectory + Constants.ManifestExtension;
return Path.Combine(packageDirectory, manifestFileName);
}
private class PackageCacheEntry
{
public PackageCacheEntry(IPackage package, DateTimeOffset lastModifiedTime)
{
Package = package;
LastModifiedTime = lastModifiedTime;
}
public IPackage Package { get; private set; }
public DateTimeOffset LastModifiedTime { get; private set; }
}
}
}
| |
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace MongoDB
{
/// <summary>
/// Type to hold an interned string that maps to the bson symbol type.
/// </summary>
[Serializable]
public struct MongoSymbol : IEquatable<MongoSymbol>, IEquatable<String>, IComparable<MongoSymbol>, IComparable<String>, IXmlSerializable
{
/// <summary>
/// Gets or sets the empty.
/// </summary>
/// <value>The empty.</value>
public static MongoSymbol Empty { get; private set; }
/// <summary>
/// Initializes the <see cref="MongoSymbol"/> struct.
/// </summary>
static MongoSymbol(){
Empty = new MongoSymbol();
}
/// <summary>
/// Initializes a new instance of the <see cref="MongoSymbol"/> struct.
/// </summary>
/// <param name="value">The value.</param>
public MongoSymbol(string value)
: this(){
if(!string.IsNullOrEmpty(value))
Value = String.Intern(value);
}
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>The value.</value>
public string Value { get; private set; }
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(MongoSymbol other){
return Value.CompareTo(other.Value);
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(string other){
return Value.CompareTo(other);
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(MongoSymbol other){
return Equals(other.Value, Value);
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(string other){
return Value.Equals(other);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString(){
return Value;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj){
if(ReferenceEquals(null, obj))
return false;
return obj.GetType() == typeof(MongoSymbol) && Equals((MongoSymbol)obj);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(MongoSymbol a, MongoSymbol b){
return SymbolEqual(a.Value, b.Value);
}
/*
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(MongoSymbol a, string b){
return SymbolEqual(a.Value, b);
}*/
/*
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(string a, MongoSymbol b){
return SymbolEqual(a, b.Value);
}*/
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(MongoSymbol a, MongoSymbol b){
return !(a == b);
}
/*
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(MongoSymbol a, String b){
return !(a == b);
}*/
/*
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(string a, MongoSymbol b){
return !(a == b);
}*/
/// <summary>
/// Performs an implicit conversion from <see cref="MongoDB.MongoSymbol"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="s">The s.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator string(MongoSymbol s){
return s.Value;
}
/// <summary>
/// Performs an implicit conversion from <see cref="System.String"/> to <see cref="MongoDB.MongoSymbol"/>.
/// </summary>
/// <param name="s">The s.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator MongoSymbol(string s){
return new MongoSymbol(s);
}
/// <summary>
/// Determines whether the specified s is empty.
/// </summary>
/// <param name="s">The s.</param>
/// <returns>
/// <c>true</c> if the specified s is empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsEmpty(MongoSymbol s){
return s == Empty;
}
/// <summary>
/// Symbols the equal.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns></returns>
private static bool SymbolEqual(string a, string b){
return a == b;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode(){
return (Value != null ? Value.GetHashCode() : 0);
}
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>
/// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.
/// </returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
void IXmlSerializable.ReadXml(XmlReader reader)
{
if(reader.IsEmptyElement)
return;
Value = string.Intern(reader.ReadString());
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if(Value != null)
writer.WriteString(Value);
}
}
}
| |
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>
/// Controller class for PN_efe_conv
/// </summary>
[System.ComponentModel.DataObject]
public partial class PnEfeConvController
{
// Preload our schema..
PnEfeConv thisSchemaLoad = new PnEfeConv();
private string userName = String.Empty;
protected string UserName
{
get
{
if (userName.Length == 0)
{
if (System.Web.HttpContext.Current != null)
{
userName=System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
}
return userName;
}
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public PnEfeConvCollection FetchAll()
{
PnEfeConvCollection coll = new PnEfeConvCollection();
Query qry = new Query(PnEfeConv.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public PnEfeConvCollection FetchByID(object IdEfeConv)
{
PnEfeConvCollection coll = new PnEfeConvCollection().Where("id_efe_conv", IdEfeConv).Load();
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public PnEfeConvCollection FetchByQuery(Query qry)
{
PnEfeConvCollection coll = new PnEfeConvCollection();
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(object IdEfeConv)
{
return (PnEfeConv.Delete(IdEfeConv) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public bool Destroy(object IdEfeConv)
{
return (PnEfeConv.Destroy(IdEfeConv) == 1);
}
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Insert(string Nombre,string Domicilio,string Departamento,int? Localidad,int? CodPos,string Cuidad,string Referente,string Tel,string ComGestion,string ComGestionFirmante,DateTime? FechaCompGes,DateTime? FechaFinCompGes,string ComGestionPagoIndirecto,string TerceroAdmin,string TerceroAdminFirmante,DateTime? FechaTerceroAdmin,DateTime? FechaFinTerceroAdmin,string Cuie,string Usuario,DateTime? FechaModificacion,string DniFirmanteActual,string ComGestionFirmanteActual,string N2008,string N2009,int? IdNomencladorDetalle,int? IdZonaSani,string Mail,string Incentivo,string PerAltaCom,string AdendaPer,DateTime? FechaAdendaPer,string CategoriaPer)
{
PnEfeConv item = new PnEfeConv();
item.Nombre = Nombre;
item.Domicilio = Domicilio;
item.Departamento = Departamento;
item.Localidad = Localidad;
item.CodPos = CodPos;
item.Cuidad = Cuidad;
item.Referente = Referente;
item.Tel = Tel;
item.ComGestion = ComGestion;
item.ComGestionFirmante = ComGestionFirmante;
item.FechaCompGes = FechaCompGes;
item.FechaFinCompGes = FechaFinCompGes;
item.ComGestionPagoIndirecto = ComGestionPagoIndirecto;
item.TerceroAdmin = TerceroAdmin;
item.TerceroAdminFirmante = TerceroAdminFirmante;
item.FechaTerceroAdmin = FechaTerceroAdmin;
item.FechaFinTerceroAdmin = FechaFinTerceroAdmin;
item.Cuie = Cuie;
item.Usuario = Usuario;
item.FechaModificacion = FechaModificacion;
item.DniFirmanteActual = DniFirmanteActual;
item.ComGestionFirmanteActual = ComGestionFirmanteActual;
item.N2008 = N2008;
item.N2009 = N2009;
item.IdNomencladorDetalle = IdNomencladorDetalle;
item.IdZonaSani = IdZonaSani;
item.Mail = Mail;
item.Incentivo = Incentivo;
item.PerAltaCom = PerAltaCom;
item.AdendaPer = AdendaPer;
item.FechaAdendaPer = FechaAdendaPer;
item.CategoriaPer = CategoriaPer;
item.Save(UserName);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(int IdEfeConv,string Nombre,string Domicilio,string Departamento,int? Localidad,int? CodPos,string Cuidad,string Referente,string Tel,string ComGestion,string ComGestionFirmante,DateTime? FechaCompGes,DateTime? FechaFinCompGes,string ComGestionPagoIndirecto,string TerceroAdmin,string TerceroAdminFirmante,DateTime? FechaTerceroAdmin,DateTime? FechaFinTerceroAdmin,string Cuie,string Usuario,DateTime? FechaModificacion,string DniFirmanteActual,string ComGestionFirmanteActual,string N2008,string N2009,int? IdNomencladorDetalle,int? IdZonaSani,string Mail,string Incentivo,string PerAltaCom,string AdendaPer,DateTime? FechaAdendaPer,string CategoriaPer)
{
PnEfeConv item = new PnEfeConv();
item.MarkOld();
item.IsLoaded = true;
item.IdEfeConv = IdEfeConv;
item.Nombre = Nombre;
item.Domicilio = Domicilio;
item.Departamento = Departamento;
item.Localidad = Localidad;
item.CodPos = CodPos;
item.Cuidad = Cuidad;
item.Referente = Referente;
item.Tel = Tel;
item.ComGestion = ComGestion;
item.ComGestionFirmante = ComGestionFirmante;
item.FechaCompGes = FechaCompGes;
item.FechaFinCompGes = FechaFinCompGes;
item.ComGestionPagoIndirecto = ComGestionPagoIndirecto;
item.TerceroAdmin = TerceroAdmin;
item.TerceroAdminFirmante = TerceroAdminFirmante;
item.FechaTerceroAdmin = FechaTerceroAdmin;
item.FechaFinTerceroAdmin = FechaFinTerceroAdmin;
item.Cuie = Cuie;
item.Usuario = Usuario;
item.FechaModificacion = FechaModificacion;
item.DniFirmanteActual = DniFirmanteActual;
item.ComGestionFirmanteActual = ComGestionFirmanteActual;
item.N2008 = N2008;
item.N2009 = N2009;
item.IdNomencladorDetalle = IdNomencladorDetalle;
item.IdZonaSani = IdZonaSani;
item.Mail = Mail;
item.Incentivo = Incentivo;
item.PerAltaCom = PerAltaCom;
item.AdendaPer = AdendaPer;
item.FechaAdendaPer = FechaAdendaPer;
item.CategoriaPer = CategoriaPer;
item.Save(UserName);
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Linq;
using System.Abstract;
using System.Collections.ObjectModel;
using System.Collections.Generic;
namespace Contoso.Abstract
{
/// <summary>
/// Interface IAppServiceBus
/// </summary>
/// <seealso cref="System.Abstract.IServiceBus" />
/// <remark>
/// An application service bus specific service bus interface
/// </remark>
public interface IAppServiceBus : IServiceBus
{
/// <summary>
/// Adds this instance.
/// </summary>
/// <typeparam name="TMessageHandler">The type of the message handler.</typeparam>
/// <returns>IAppServiceBus.</returns>
IAppServiceBus Add<TMessageHandler>()
where TMessageHandler : class;
/// <summary>
/// Adds the specified message handler type.
/// </summary>
/// <param name="messageHandlerType">Type of the message handler.</param>
/// <returns>IAppServiceBus.</returns>
IAppServiceBus Add(Type messageHandlerType);
}
/// <summary>
/// Class AppServiceBus.
/// </summary>
/// <seealso cref="Contoso.Abstract.IAppServiceBus" />
/// <remark>
/// An application service bus implementation
/// </remark>
/// <example>
/// <code>
///ServiceBusManager.SetProvider(() => new AppServiceBus()
///.Add(Handler1)
///.Add(Handler2))
///.RegisterWithServiceLocator();
///ServiceBusManager.Send<Message1>(x => x.Body = "Message");
///</code>
/// </example>
public class AppServiceBus : Collection<AppServiceBusRegistration>, IAppServiceBus, ServiceBusManager.IRegisterWithLocator
{
readonly Func<Type, IServiceMessageHandler<object>> _messageHandlerFactory;
readonly Func<IServiceLocator> _locator;
/// <summary>
/// Initializes a new instance of the <see cref="AppServiceBus" /> class.
/// </summary>
public AppServiceBus()
: this(t => (IServiceMessageHandler<object>)Activator.CreateInstance(t), () => ServiceLocatorManager.Current) { }
/// <summary>
/// Initializes a new instance of the <see cref="AppServiceBus" /> class.
/// </summary>
/// <param name="messageHandlerFactory">The message handler factory.</param>
public AppServiceBus(Func<Type, IServiceMessageHandler<object>> messageHandlerFactory)
: this(messageHandlerFactory, () => ServiceLocatorManager.Current) { }
/// <summary>
/// Initializes a new instance of the <see cref="AppServiceBus" /> class.
/// </summary>
/// <param name="messageHandlerFactory">The message handler factory.</param>
/// <param name="locator">The locator.</param>
/// <exception cref="ArgumentNullException">messageHandlerFactory
/// or
/// locator</exception>
public AppServiceBus(Func<Type, IServiceMessageHandler<object>> messageHandlerFactory, Func<IServiceLocator> locator)
{
_messageHandlerFactory = messageHandlerFactory ?? throw new ArgumentNullException(nameof(messageHandlerFactory));
_locator = locator ?? throw new ArgumentNullException(nameof(locator));
}
Action<IServiceLocator, string> ServiceBusManager.IRegisterWithLocator.RegisterWithLocator =>
(locator, name) => ServiceBusManager.RegisterInstance<IAppServiceBus>(this, name, locator);
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException"></exception>
public object GetService(Type serviceType) =>
throw new NotImplementedException();
/// <summary>
/// Creates a new message.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="messageBuilder">The message builder.</param>
/// <returns>The newly created message.</returns>
public TMessage CreateMessage<TMessage>(Action<TMessage> messageBuilder)
where TMessage : class
{
var message = _locator().Resolve<TMessage>();
messageBuilder?.Invoke(message);
return message;
}
/// <summary>
/// Adds a message handler.
/// </summary>
/// <typeparam name="TMessageHandler">The type of the message handler.</typeparam>
/// <returns>Fluent</returns>
public IAppServiceBus Add<TMessageHandler>()
where TMessageHandler : class =>
Add(typeof(TMessageHandler));
/// <summary>
/// Adds a message handler
/// </summary>
/// <param name="messageHandlerType">Type of the message handler.</param>
/// <returns>Fluent</returns>
/// <exception cref="InvalidOperationException">Unable find a message handler</exception>
public IAppServiceBus Add(Type messageHandlerType)
{
var messageType = GetMessageTypeFromHandler(messageHandlerType);
if (messageType == null)
throw new InvalidOperationException("Unable find a message handler");
Add(new AppServiceBusRegistration
{
MessageHandlerType = messageHandlerType,
MessageType = messageType,
});
return this;
}
/// <summary>
/// Sends a message on the bus
/// </summary>
/// <param name="destination">The destination.</param>
/// <param name="messages">The messages.</param>
/// <returns>Null</returns>
/// <exception cref="ArgumentNullException">messages</exception>
public IServiceBusCallback Send(IServiceBusEndpoint destination, params object[] messages)
{
if (messages == null)
throw new ArgumentNullException(nameof(messages));
foreach (var message in messages)
foreach (var type in GetTypesOfMessageHandlers(message.GetType()))
HandleTheMessage(type, message);
return null;
}
void HandleTheMessage(Type type, object message) =>
_messageHandlerFactory(type)
.Handle(message);
IEnumerable<Type> GetTypesOfMessageHandlers(Type messageType) =>
Items.Where(x => x.MessageType == messageType)
.Select(x => x.MessageHandlerType);
/// <summary>
/// Gets the message type from handler.
/// </summary>
/// <param name="messageHandlerType">Type of the message handler.</param>
/// <returns>Type.</returns>
static Type GetMessageTypeFromHandler(Type messageHandlerType) =>
null;
//var serviceMessageType = typeof(IServiceMessage);
//var applicationServiceMessageType = typeof(IApplicationServiceMessage);
//return messageHandlerType.GetInterfaces()
// .Where(h => h.IsGenericType && (h.FullName.StartsWith("System.Abstract.IServiceMessageHandler`1") || h.FullName.StartsWith("Contoso.Abstract.IApplicationServiceMessageHandler`1")))
// .Select(h => h.GetGenericArguments()[0])
// .Where(m => m.GetInterfaces().Any(x => x == serviceMessageType || x == applicationServiceMessageType))
// .SingleOrDefault();
/// <summary>
/// Replies messages back up the bus.
/// </summary>
/// <param name="messages">The messages.</param>
/// <exception cref="NotImplementedException"></exception>
public void Reply(params object[] messages) =>
throw new NotImplementedException();
/// <summary>
/// Returns a value back up the bus.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <exception cref="NotImplementedException"></exception>
public void Return<T>(T value) =>
throw new NotImplementedException();
}
}
| |
// ------------------------------------------------------------------------------------------------
// KingTomato Script
// --
//
// Summary:
//
// Because I didn't have ALL *grin* the events I wanted to have with presto pack, I added a
// few more. You can find the syntax to use them below. These events include some like
// eventBottomPrint, eventTopPrint, eventCenterPrint, (All useful to retrieve a current
// weapon). Additionally, you can catch menu text (as in TAB menu). Very cool for things
// like hacking admin :P
//
// Events:
// eventCenterPrint(%msg, %timeout);
// eventBottomPrint(%msg, %timeout);
// eventTopPrint(%msg, %timeout);
// Returns the print message with the message and the time to be shown for.
// eventClientInput(%team, %msg);
// This event triggers when the user types something into the chat or team chat box. You
// can then parse the message how ever you want, inclusing returning mute to stop the
// displaying of the message.
// eventNewMenu(%menuTitle)
// Triggers when the tab menu is either opened, or the menu changes (due to item
// selection, or what ever)
// eventAddMenuItem(%menuItem, %menuCommand)
// Triggers when an item is added to the menu. Each 5menuItem will be in the form of
// something like "1Change Teams Observer" with a %menuCommand of something like
// "changeteams"
// eventInfoLine(%line, %text)
// Triggers when a line in the bottom right box of the tab menu is set or updated
// eventVote(%vote)
// Triggers when the user votes one way or the other. %vote will be passed as either
// yes or no.
// eventModInfo(%version, %name, %mod, %info, %favKey)
// Triggers on a connection, and will return the information sent from the server
// about itself. Will pass the following information:
// %version - Version of server (ex: 1.11)
// %name - Server name
// %mod - Server mod
// %info - Server Info
// %favKey - Name of the key used to mark favorites.
// eventTime(%seconds)
// This will trigger every time the server sends an "update time" message to
// the client. This usually occurs every 20 seconds on a map with a time limit,
// and will return a negative number (negative sybmolising time left).
// %seconds - Number of seconds on map.
//
// -----------------------------------------------------------------------------------------------------
$Script::Creator = "KingTomato";
$Script::Version = "1.4";
$Script::Description = "Extended events library designed to include bottomPrint, topPrint, centerPrint, "
@ "Input Commands, Bot Commands, and more! Please read file for more information";
// -----------------------------------------------------------------------------------------------------
// eventCenterPrint(%msg, %timeout);
// eventBottomPrint(%msg, %timeout);
// eventTopPrint(%msg, %timeout);
// Returns the print message with the message and the time to be shown for.
// -----------------------------------------------------------------------------------------------------
function remoteCP(%manager, %msg, %timeout) {
if (%manager == 2048) {
$centerPrintId++;
if (%timeout)
schedule("clearCenterPrint(" @ $centerPrintId @ ");", %timeout);
Client::centerPrint(%msg, 0);
Event::Trigger(eventcenterPrint, String::DoubleSlashes(%msg), %timeout);
}
}
function remoteBP(%manager, %msg, %timeout) {
if (%manager == 2048) {
$centerPrintId++;
if (%timeout)
schedule("clearCenterPrint(" @ $centerPrintId @ ");", %timeout);
Client::centerPrint(%msg, 1);
Event::Trigger(eventBottomPrint, String::DoubleSlashes(%msg), %timeout);
}
}
function remoteTP(%manager, %msg, %timeout) {
if (%manager == 2048) {
$centerPrintId++;
if (%timeout)
schedule("clearCenterPrint(" @ $centerPrintId @ ");", %timeout);
Client::centerPrint(%msg, 2);
Event::Trigger(eventTopPrint, String::DoubleSlashes(%msg), %timeout);
}
}
// ------------------------------------------------------------------------------------------------
// eventClientInput(%team, %message)
// This event triggers when the user types something into the chat or team chat box. You
// can then parse the message how ever you want, inclusing returning mute to stop the
// displaying of the message.
// ------------------------------------------------------------------------------------------------
function say(%team, %msg) {
%returns = Event::Trigger(eventClientInput, %team, %msg);
if (Event::Returned(%returns, mute))
return;
%msg = Acronym::Replace(%msg);
// Flood Protect Addition
if ($FloodProtect::Enabled)
{
%timeNow = getIntegerTime(false) >> 5;
%delta = $FloodProtect::Time - %timeNow;
remoteBP(2048, "<jc><f2>-Flood Protection Enabled-\n"
@"To prevent further delay, your message "
@"has been stopped until the flood limit is reached.\n\n"
@"Time up in <f0>" @ %delta @ "<f2> seconds", 10);
return;
}
// End Flood Protect Addition
remoteEval(2048, say, %team, %msg);
}
// ------------------------------------------------------------------------------------------------
// eventInventoryText(%text)
// When the inventory text is altered
// ------------------------------------------------------------------------------------------------
function remoteITXT(%manager, %msg) {
if(%manager == 2048)
Control::setValue(EnergyDisplayText, %msg);
}
// ------------------------------------------------------------------------------------------------
// eventNewMenu(%menuTitle)
// Triggers when the tab menu is either opened, or the menu changes (due to item
// selection, or what ever)
// ------------------------------------------------------------------------------------------------
function remoteNewMenu(%server, %title)
{
if(%server != 2048)
return;
if(isObject(CurServerMenu))
deleteObject(CurServerMenu);
newObject(CurServerMenu, ChatMenu, %title);
setCMMode(PlayChatMenu, 0);
setCMMode(CurServerMenu, 1);
Event::Trigger(eventNewMenu, %title);
}
// ------------------------------------------------------------------------------------------------
// eventAddMenuItem(%menuItem, %menuCommand)
// Triggers when an item is added to the menu. Each 5menuItem will be in the form of
// something like "1Change Teams Observer" with a %menuCommand of something like
// "changeteams"
// ------------------------------------------------------------------------------------------------
function remoteAddMenuItem(%server, %title, %code)
{
if(%server != 2048)
return;
addCMCommand(CurServerMenu, %title, clientMenuSelect, %code);
Event::Trigger(eventAddMenuItem, %title, %code);
}
// ------------------------------------------------------------------------------------------------
// eventInfoLine(%line, %text)
// Triggers when a line in the bottom right box of the tab menu is set or updated
// ------------------------------------------------------------------------------------------------
function remoteSetInfoLine(%mgr, %lineNum, %text)
{
if(%mgr != 2048)
return;
if (%lineNum == 1)
{
if (%text == "")
Control::setVisible(InfoCtrlBox, FALSE);
else
Control::setVisible(InfoCtrlBox, TRUE);
}
Control::setText("InfoCtrlLine" @ %lineNum, %text);
Event::Trigger(eventInfoLine, %lineNum, %text);
}
// ------------------------------------------------------------------------------------------------
// eventVote(%vote)
// Triggers when the user votes one way or the other. %vote will be passed as either
// yes or no.
// ------------------------------------------------------------------------------------------------
function voteYes()
{
remoteEval(2048, VoteYes);
Event::Trigger(eventVote, yes);
}
function voteNo()
{
remoteEval(2048, VoteNo);
Event::Trigger(eventVote, no);
}
// ------------------------------------------------------------------------------------------------
// eventModInfo(%version, %name, %mod, %info, %favKey)
// Triggers on a connection, and will return the information sent from the server
// about itself. Will pass the following information:
// %version - Version of server (ex: 1.11)
// %name - Server name
// %mod - Server mod
// %info - Server Info
// %favKey - Name of the key used to mark favorites.
// ------------------------------------------------------------------------------------------------
function remoteSVInfo(%server, %version, %hostname, %mod, %info, %favKey)
{
if(%server == 2048)
{
$ServerVersion = %version;
$ServerName = %hostname;
$modList = %mod;
$ServerMod = $modList;
$ServerInfo = %info;
$ServerFavoritesKey = %favKey;
EvalSearchPath();
Event::Trigger(eventModInfo, %version, %name, %mod, %info, %favKey);
}
}
// ------------------------------------------------------------------------------------------------
// eventTime(%seconds)
// This will trigger every time the server sends an "update time" message to
// the client. This usually occurs every 20 seconds on a map with a time limit,
// and will return a negative number (negative sybmolising time left).
// %seconds - Number of seconds on map.
// ------------------------------------------------------------------------------------------------
function remoteSetTime(%server, %time)
{
if(%server == 2048)
{
setHudTimer(%time);
Event::Trigger(eventTime, %time);
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace CodeJewels.Service.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
/// <summary>
/// Base class for paddles
/// </summary>
public class PaddleBase : NetworkBehaviour {
private float thrust = 10.0f;
private float paddleLimitMaxZ = 5.0f;
private float paddleLimitMinZ = -5.0f;
private float currentLimitZMax = 5;
private float currentLimitZMin = -5;
private Vector3 up = new Vector3(1, 0, 0);
private Rigidbody rigidBody;
protected Animator animator;
public int playerIndex;
protected List<SuperPowerBase> myPowers = new List<SuperPowerBase>();
public string currentPowerName = "";
protected Text powerText;
protected Dictionary<string, bool> remoteInputs = new Dictionary<string, bool>();
protected float messageTimer = 0.3f;
protected float timeToNextMessage;
public virtual void Start()
{
rigidBody = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
PaddleNetworking[] playerList = GameObject.FindObjectsOfType<PaddleNetworking>();
int index = 0;
foreach (PaddleNetworking player in playerList)
{
if (player.gameObject == gameObject)
{
playerIndex = index;
}
++index;
}
currentPowerName = "";
RaycastHit hit;
LayerMask mask = 1 << 10; //wall
Vector3 offset = new Vector3(0, .5f, 0);//spawner is in the floor -_-
if (Physics.Raycast(transform.position + offset, Vector3.forward, out hit, 10, mask))
{
float paddleColliderHalfSize = 1f;
paddleColliderHalfSize = GetComponent<MeshCollider>().bounds.size.y/2; //collision precise
paddleLimitMaxZ = hit.point.z - paddleColliderHalfSize;
paddleLimitMinZ = -paddleLimitMaxZ; //Assume symmetric...todo:another raycast opposite direction
}
currentLimitZMax = paddleLimitMaxZ;
currentLimitZMin = paddleLimitMinZ;
}
private void OnEnable()
{
}
protected void SetThrust(float thrust)
{
this.thrust = thrust;
}
//Disallow paddle movement beyond positional point z
// z is the location of the center of the obstruction object
// paddle movement returns to normal when obstruct is called
// again but with isCleanup=true
public void Obstruct(float z=0, bool isCleanup=false)
{
if (!isCleanup)
{
float paddleColliderHalfSize = GetComponent<MeshCollider>().bounds.size.y / 2;
float myZ = transform.position.z;
//support more obstructs later
// reset both pairs of numbers
currentLimitZMax = paddleLimitMaxZ;
currentLimitZMin = paddleLimitMinZ;
if(myZ > z)
{
currentLimitZMin= z + paddleColliderHalfSize;
}
else
{
currentLimitZMax= z - paddleColliderHalfSize;
}
}
else
{
currentLimitZMax = paddleLimitMaxZ;
currentLimitZMin = paddleLimitMinZ;
}
}
// +ve for "up"
protected void MovePaddles(float dir)
{
Debug.Assert(Time.inFixedTimeStep, "Paddle movement should only happen inside physics code");
if (rigidBody)
{
//Stop momentum caused by switching controllers
rigidBody.velocity = Vector3.zero;
rigidBody.angularVelocity = Vector3.zero;
// Invert for one side
if (transform.position.x < 0) dir *= -1;
// Clamp between [-1,1]
dir = Mathf.Clamp(dir, -1.0f, 1.0f);
//rigidBody.AddForce(dir * up * Thrust);
transform.Translate(dir * up * thrust * Time.fixedDeltaTime);
}
}
internal void FixedUpdate()
{
// Clamp Z if we're outside an arbitrary value
// Assumed symettric table
if(transform.position.z < currentLimitZMin || transform.position.z > currentLimitZMax)
{
transform.position = new Vector3(
transform.position.x,
transform.position.y,
Mathf.Clamp(transform.position.z, currentLimitZMin, currentLimitZMax)
);
}
}
internal void Update()
{
//Try to cleanup oldest power
if (myPowers.Count > 0)
{
SuperPowerBase p = myPowers[0];
if(!p.isActive && !p.isReady)
{
myPowers.RemoveAt(0);
Destroy(p);
//Debug.Log("Cleaning");
}
}
}
internal void TryActivate()
{
}
public void AddPower(string powerName)
{
if (myPowers.Count > 0)
{ myPowers[myPowers.Count - 1].isReady = false; }
//Debug.Log(powerName);
SuperPowerBase spb = gameObject.AddComponent(Type.GetType(powerName)) as SuperPowerBase;
spb.isReady = true;
myPowers.Add(spb);
if (!powerText)
{
GameObject powerUI = GameObject.FindGameObjectWithTag("PowerUp");
powerText = powerUI.transform.GetChild(playerIndex).GetComponent<Text>();
}
powerText.text = powerName;
}
public void SetPower(string powerName)
{
//Debug.Log("Set Power: " + powerName);
currentPowerName = powerName;
if (!powerText)
{
GameObject powerUI = GameObject.FindGameObjectWithTag("PowerUp");
powerText = powerUI.transform.GetChild(playerIndex).GetComponent<Text>();
}
powerText.text = powerName;
}
public virtual void SendInput(string input, bool isPress)
{
if (NetworkManager.singleton.isNetworkActive)
{
bool willSend= false;
if (!remoteInputs.ContainsKey(input))
{
remoteInputs.Add(input, isPress);
willSend = true;
}
else
{
bool lastState = remoteInputs[input]; //needs optimizing
willSend = (lastState != isPress);
}
if (!willSend) return;
PaddleNetworking pn = GetComponent<PaddleNetworking>();
if (pn.isServer)
{
pn.RpcSendInput(input, isPress);
}
else
{
//isClient
pn.CmdSendInput(input, isPress);
}
remoteInputs[input] = isPress;
}
}
public void RecieveRemoteInput(string input, bool isPressed)
{
//Only works because its animations
if (input.Contains("Fire1")) //ctrl+v'd from player
{
if (isPressed)
{
animator.SetBool("pull", true);
animator.SetBool("hit", true);
}
else
{
animator.SetBool("pull", false);
animator.SetBool("hit", false);
}
}
}
}
| |
using System.Diagnostics;
using System;
class Polynomial {
public static void Main(string[] args)
{
/* Size of the array of elements to compute the polynomial on */
const int arraySize = 1024*1024*8;
/* Allocate arrays of inputs and outputs */
double[] x = new double[arraySize];
double[] pYeppp = new double[arraySize];
double[] pNaive = new double[arraySize];
/* Populate the array of inputs with random data */
Random rng = new Random();
for (int i = 0; i < x.Length; i++) {
x[i] = rng.NextDouble();
}
/* Zero-initialize the output arrays */
Array.Clear(pYeppp, 0, pYeppp.Length);
Array.Clear(pNaive, 0, pYeppp.Length);
/* Retrieve the number of timer ticks per second */
ulong frequency = Yeppp.Library.GetTimerFrequency();
/* Retrieve the number of timer ticks before calling the C version of polynomial evaluation */
ulong startTimeNaive = Yeppp.Library.GetTimerTicks();
/* Evaluate polynomial using C# implementation */
EvaluatePolynomialNaive(x, pNaive);
/* Retrieve the number of timer ticks after calling the C version of polynomial evaluation */
ulong endTimeNaive = Yeppp.Library.GetTimerTicks();
/* Retrieve the number of timer ticks before calling Yeppp! polynomial evaluation */
ulong startTimeYeppp = Yeppp.Library.GetTimerTicks();
/* Evaluate polynomial using Yeppp! */
Yeppp.Math.EvaluatePolynomial_V64fV64f_V64f(coefs, 0, x, 0, pYeppp, 0, coefs.Length, x.Length);
/* Retrieve the number of timer ticks after calling Yeppp! polynomial evaluation */
ulong endTimeYeppp = Yeppp.Library.GetTimerTicks();
/* Compute time in seconds and performance in FLOPS */
double secsNaive = ((double)(endTimeNaive - startTimeNaive)) / ((double)(frequency));
double secsYeppp = ((double)(endTimeYeppp - startTimeYeppp)) / ((double)(frequency));
double flopsNaive = (double)(arraySize * (coefs.Length - 1) * 2) / secsNaive;
double flopsYeppp = (double)(arraySize * (coefs.Length - 1) * 2) / secsYeppp;
/* Report the timing and performance results */
Console.WriteLine("Naive implementation:");
Console.WriteLine("\tTime = {0:F2} secs", secsNaive);
Console.WriteLine("\tPerformance = {0:F2} GFLOPS", flopsNaive * 1.0e-9);
Console.WriteLine("Yeppp! implementation:");
Console.WriteLine("\tTime = {0:F2} secs", secsYeppp);
Console.WriteLine("\tPerformance = {0:F2} GFLOPS", flopsYeppp * 1.0e-9);
/* Make sure the result is correct. */
Console.WriteLine("Max difference: {0:F3}%", ComputeMaxDifference(pNaive, pYeppp) * 100.0f);
}
/* C# implementation with hard-coded coefficients. */
private static void EvaluatePolynomialNaive(double[] xArray, double[] yArray)
{
Debug.Assert(xArray.Length == yArray.Length);
for (int index = 0; index < xArray.Length; index++)
{
double x = xArray[index];
double y = c0 + x * (c1 + x * (c2 + x * (c3 + x * (c4 + x * (c5 + x * (c6 + x * (c7 + x * (c8 + x * (c9 + x * (c10 + x * (c11 +
x * (c12 + x * (c13 + x * (c14 + x * (c15 + x * (c16 + x * (c17 + x * (c18 + x * (c19 + x * (c20 + x * (c21 +
x * (c22 + x * (c23 + x * (c24 + x * (c25 + x * (c26 + x * (c27 + x * (c28 + x * (c29 + x * (c30 + x * (c31 +
x * (c32 + x * (c33 + x * (c34 + x * (c35 + x * (c36 + x * (c37 + x * (c38 + x * (c39 + x * (c40 + x * (c41 +
x * (c42 + x * (c43 + x * (c44 + x * (c45 + x * (c46 + x * (c47 + x * (c48 + x * (c49 + x * (c50 + x * (c51 +
x * (c52 + x * (c53 + x * (c54 + x * (c55 + x * (c56 + x * (c57 + x * (c58 + x * (c59 + x * (c60 + x * (c61 +
x * (c62 + x * (c63 + x * (c64 + x * (c65 + x * (c66 + x * (c67 + x * (c68 + x * (c69 + x * (c70 + x * (c71 +
x * (c72 + x * (c73 + x * (c74 + x * (c75 + x * (c76 + x * (c77 + x * (c78 + x * (c79 + x * (c80 + x * (c81 +
x * (c82 + x * (c83 + x * (c84 + x * (c85 + x * (c86 + x * (c87 + x * (c88 + x * (c89 + x * (c90 + x * (c91 +
x * (c92 + x * (c93 + x * (c94 + x * (c95 + x * (c96 + x * (c97 + x * (c98 + x * (c99 + x * c100)
))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))));
yArray[index] = y;
}
}
/* This function computes the maximum relative error between two vectors. */
private static double ComputeMaxDifference(double[] xArray, double[] yArray) {
Debug.Assert(xArray.Length == yArray.Length);
double maxDiff = 0.0;
for (int index = 0; index < xArray.Length; index++)
{
if (xArray[index] == 0.0)
continue;
double diff = Math.Abs(xArray[index] - yArray[index]) / Math.Abs(xArray[index]);
maxDiff = Math.Max(maxDiff, diff);
}
return maxDiff;
}
/* Polynomial Coefficients 101 */
private const double c0 = 1.53270461724076346;
private const double c1 = 1.45339856462100293;
private const double c2 = 1.21078763026010761;
private const double c3 = 1.46952786401453397;
private const double c4 = 1.34249847863665017;
private const double c5 = 0.75093174077762164;
private const double c6 = 1.90239336671587562;
private const double c7 = 1.62162053962810579;
private const double c8 = 0.53312230473555923;
private const double c9 = 1.76588453111778762;
private const double c10 = 1.31215699612484679;
private const double c11 = 1.49636144227257237;
private const double c12 = 1.52170011054112963;
private const double c13 = 0.83637497322280110;
private const double c14 = 1.12764540941736043;
private const double c15 = 0.65513628703807597;
private const double c16 = 1.15879020877781906;
private const double c17 = 1.98262901973751791;
private const double c18 = 1.09134643523639479;
private const double c19 = 1.92898634047221235;
private const double c20 = 1.01233347751449659;
private const double c21 = 1.89462732589369078;
private const double c22 = 1.28216239080886344;
private const double c23 = 1.78448898277094016;
private const double c24 = 1.22382217182612910;
private const double c25 = 1.23434674193555734;
private const double c26 = 1.13914782832335501;
private const double c27 = 0.73506235075797319;
private const double c28 = 0.55461432517332724;
private const double c29 = 1.51704871121967963;
private const double c30 = 1.22430234239661516;
private const double c31 = 1.55001237689160722;
private const double c32 = 0.84197209952298114;
private const double c33 = 1.59396169927319749;
private const double c34 = 0.97067044414760438;
private const double c35 = 0.99001960195021281;
private const double c36 = 1.17887814292622884;
private const double c37 = 0.58955609453835851;
private const double c38 = 0.58145654861350322;
private const double c39 = 1.32447212043555583;
private const double c40 = 1.24673632882394241;
private const double c41 = 1.24571828921765111;
private const double c42 = 1.21901343493503215;
private const double c43 = 1.89453941213996638;
private const double c44 = 1.85561626872427416;
private const double c45 = 1.13302165522004133;
private const double c46 = 1.79145993815510725;
private const double c47 = 1.59227069037095317;
private const double c48 = 1.89104468672467114;
private const double c49 = 1.78733894997070918;
private const double c50 = 1.32648559107345081;
private const double c51 = 1.68531055586072865;
private const double c52 = 1.08980909640581993;
private const double c53 = 1.34308207822154847;
private const double c54 = 1.81689492849547059;
private const double c55 = 1.38582137073988747;
private const double c56 = 1.04974901183570510;
private const double c57 = 1.14348742300966456;
private const double c58 = 1.87597730040483323;
private const double c59 = 0.62131555899466420;
private const double c60 = 0.64710935668225787;
private const double c61 = 1.49846610600978751;
private const double c62 = 1.07834176789680957;
private const double c63 = 1.69130785175832059;
private const double c64 = 1.64547687732258793;
private const double c65 = 1.02441150427208083;
private const double c66 = 1.86129006037146541;
private const double c67 = 0.98309038830424073;
private const double c68 = 1.75444578237500969;
private const double c69 = 1.08698336765112349;
private const double c70 = 1.89455010772036759;
private const double c71 = 0.65812118412299539;
private const double c72 = 0.62102711487851459;
private const double c73 = 1.69991208083436747;
private const double c74 = 1.65467704495635767;
private const double c75 = 1.69599459626992174;
private const double c76 = 0.82365682103308750;
private const double c77 = 1.71353437063595036;
private const double c78 = 0.54992984722831769;
private const double c79 = 0.54717367088443119;
private const double c80 = 0.79915543248858154;
private const double c81 = 1.70160318364006257;
private const double c82 = 1.34441280175456970;
private const double c83 = 0.79789486341474966;
private const double c84 = 0.61517383020710754;
private const double c85 = 0.55177400048576055;
private const double c86 = 1.43229889543908696;
private const double c87 = 1.60658663666266949;
private const double c88 = 1.78861146369896090;
private const double c89 = 1.05843250742401821;
private const double c90 = 1.58481799048208832;
private const double c91 = 1.70954313374718085;
private const double c92 = 0.52590070195022226;
private const double c93 = 0.92705074709607885;
private const double c94 = 0.71442651832362455;
private const double c95 = 1.14752795948077643;
private const double c96 = 0.89860175106926404;
private const double c97 = 0.76771198245570573;
private const double c98 = 0.67059202034800746;
private const double c99 = 0.53785922275590729;
private const double c100 = 0.82098327929734880;
/* The same coefficients as an array. This array is used for a Yeppp! function call. */
private static readonly double[] coefs = {
c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19,
c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32, c33, c34, c35, c36, c37, c38, c39,
c40, c41, c42, c43, c44, c45, c46, c47, c48, c49, c50, c51, c52, c53, c54, c55, c56, c57, c58, c59,
c60, c61, c62, c63, c64, c65, c66, c67, c68, c69, c70, c71, c72, c73, c74, c75, c76, c77, c78, c79,
c80, c81, c82, c83, c84, c85, c86, c87, c88, c89, c90, c91, c92, c93, c94, c95, c96, c97, c98, c99,
c100
};
}
| |
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
using FluentAssertions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.FileProviders;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace CompressedStaticFiles.Tests
{
public class CompressedStaticFileMiddlewareTests
{
/// <summary>
/// Call the next middleware if no matching file is found.
/// </summary>
/// <returns></returns>
[Fact]
public async Task CallNextMiddleware()
{
// Arrange
var builder = new WebHostBuilder()
.ConfigureServices(sp =>
{
sp.AddCompressedStaticFiles();
})
.Configure(app =>
{
app.UseCompressedStaticFiles();
app.Use(next =>
{
return async context =>
{
context.Response.StatusCode = 999;
};
});
});
var server = new TestServer(builder);
// Act
var response = await server.CreateClient().GetAsync("/this_file_does_not_exist.html");
// Assert
response.StatusCode.Should().Be(999);
}
/// <summary>
/// Serve the uncompressed file if no compressed version exist
/// </summary>
/// <returns></returns>
[Fact]
public async Task Uncompressed()
{
// Arrange
var builder = new WebHostBuilder()
.ConfigureServices(sp =>
{
sp.AddCompressedStaticFiles();
})
.Configure(app =>
{
app.UseCompressedStaticFiles();
app.Use(next =>
{
return async context =>
{
// this test should never call the next middleware
// set status code to 999 to detect a test failure
context.Response.StatusCode = 999;
};
});
}).UseWebRoot(Path.Combine(Environment.CurrentDirectory, "wwwroot"));
var server = new TestServer(builder);
// Act
var response = await server.CreateClient().GetAsync("/i_exist_only_uncompressed.html");
var content = await response.Content.ReadAsStringAsync();
// Assert
response.StatusCode.Should().Be(200);
content.Should().Be("uncompressed");
response.Content.Headers.TryGetValues("Content-Type", out IEnumerable<string> contentTypeValues);
contentTypeValues.Single().Should().Be("text/html");
}
/// <summary>
/// Serve the compressed file if it exists and the browser supports it testing with a browser that supports both br and gzip
/// </summary>
/// <returns></returns>
[Fact]
public async Task SupportsBrAndGZip()
{
// Arrange
var builder = new WebHostBuilder()
.ConfigureServices(sp =>
{
sp.AddCompressedStaticFiles();
})
.Configure(app =>
{
app.UseCompressedStaticFiles();
app.Use(next =>
{
return async context =>
{
// this test should never call the next middleware
// set status code to 999 to detect a test failure
context.Response.StatusCode = 999;
};
});
}).UseWebRoot(Path.Combine(Environment.CurrentDirectory, "wwwroot"));
var server = new TestServer(builder);
// Act
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("Accept-Encoding", "br, gzip");
var response = await client.GetAsync("/i_also_exist_compressed.html");
var content = await response.Content.ReadAsStringAsync();
// Assert
response.StatusCode.Should().Be(200);
content.Should().Be("br");
response.Content.Headers.TryGetValues("Content-Type", out IEnumerable<string> contentTypeValues);
contentTypeValues.Single().Should().Be("text/html");
}
/// <summary>
/// Serve the compressed file if it exists and the browser supports it testing with a browser that only supports gzip
/// </summary>
/// <returns></returns>
[Fact]
public async Task SupportsGzip()
{
// Arrange
var builder = new WebHostBuilder()
.ConfigureServices(sp =>
{
sp.AddCompressedStaticFiles();
})
.Configure(app =>
{
app.UseCompressedStaticFiles();
app.Use(next =>
{
return async context =>
{
// this test should never call the next middleware
// set status code to 999 to detect a test failure
context.Response.StatusCode = 999;
};
});
}).UseWebRoot(Path.Combine(Environment.CurrentDirectory, "wwwroot"));
var server = new TestServer(builder);
// Act
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
var response = await client.GetAsync("/i_also_exist_compressed.html");
var content = await response.Content.ReadAsStringAsync();
// Assert
response.StatusCode.Should().Be(200);
content.Should().Be("gzip");
response.Content.Headers.TryGetValues("Content-Type", out IEnumerable<string> contentTypeValues);
contentTypeValues.Single().Should().Be("text/html");
}
/// <summary>
/// Should send the uncompressed file if its smaller than the original
/// </summary>
/// <returns></returns>
[Fact]
public async Task UncompressedSmaller()
{
// Arrange
var builder = new WebHostBuilder()
.ConfigureServices(sp =>
{
sp.AddCompressedStaticFiles();
})
.Configure(app =>
{
app.UseCompressedStaticFiles();
app.Use(next =>
{
return async context =>
{
// this test should never call the next middleware
// set status code to 999 to detect a test failure
context.Response.StatusCode = 999;
};
});
}).UseWebRoot(Path.Combine(Environment.CurrentDirectory, "wwwroot"));
var server = new TestServer(builder);
// Act
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("Accept-Encoding", "br");
var response = await client.GetAsync("/i_am_smaller_in_uncompressed.html");
var content = await response.Content.ReadAsStringAsync();
// Assert
response.StatusCode.Should().Be(200);
content.Should().Be("uncompressed");
response.Content.Headers.TryGetValues("Content-Type", out IEnumerable<string> contentTypeValues);
contentTypeValues.Single().Should().Be("text/html");
}
/// <summary>
/// Use the FileProvider from options.
/// </summary>
[Fact]
public async Task UseCustomFileProvider()
{
// Arrange
var fileInfo = Substitute.For<IFileInfo>();
fileInfo.Exists.Returns(true);
fileInfo.IsDirectory.Returns(false);
fileInfo.Length.Returns(12);
fileInfo.LastModified.Returns(new DateTimeOffset(2018, 12, 16, 13, 36, 0, new TimeSpan()));
fileInfo.CreateReadStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes("fileprovider")));
var mockFileProvider = Substitute.For<IFileProvider>();
mockFileProvider.GetFileInfo("/i_only_exist_in_mociFileProvider.html").Returns(fileInfo);
var staticFileOptions = new StaticFileOptions() { FileProvider = mockFileProvider };
var builder = new WebHostBuilder()
.ConfigureServices(sp =>
{
sp.AddCompressedStaticFiles();
})
.Configure(app =>
{
app.UseCompressedStaticFiles(staticFileOptions);
app.Use(next =>
{
return async context =>
{
// this test should never call the next middleware
// set status code to 999 to detect a test failure
context.Response.StatusCode = 999;
};
});
}).UseWebRoot(Path.Combine(Environment.CurrentDirectory, "wwwroot"));
var server = new TestServer(builder);
// Act
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("Accept-Encoding", "br");
var response = await client.GetAsync("/i_only_exist_in_mociFileProvider.html");
var content = await response.Content.ReadAsStringAsync();
// Assert
response.StatusCode.Should().Be(200);
content.Should().Be("fileprovider");
response.Content.Headers.TryGetValues("Content-Type", out IEnumerable<string> contentTypeValues);
contentTypeValues.Single().Should().Be("text/html");
}
/// <summary>
/// Should not send precompressed content if it has been disabled.
/// </summary>
/// <returns></returns>
[Fact]
public async Task Disabled()
{
// Arrange
var builder = new WebHostBuilder()
.ConfigureServices(sp =>
{
sp.AddCompressedStaticFiles(options => options.EnablePrecompressedFiles = false);
})
.Configure(app =>
{
app.UseCompressedStaticFiles();
app.Use(next =>
{
return async context =>
{
// this test should never call the next middleware
// set status code to 999 to detect a test failure
context.Response.StatusCode = 999;
};
});
}).UseWebRoot(Path.Combine(Environment.CurrentDirectory, "wwwroot"));
var server = new TestServer(builder);
// Act
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("Accept-Encoding", "br");
var response = await client.GetAsync("/i_also_exist_compressed.html");
var content = await response.Content.ReadAsStringAsync();
// Assert
response.StatusCode.Should().Be(200);
content.Should().Be("uncompressed");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace CookBookAPI.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.Azure.Management.SignalR;
using Microsoft.Azure.Management.SignalR.Models;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Xunit;
namespace SignalR.Tests
{
public class SignalRTests
{
[Fact]
public void SignalRCheckNameTest()
{
var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (var context = MockContext.Start(typeof(SignalRTests).FullName))
{
var resourceClient = SignalRTestUtilities.GetResourceManagementClient(context, handler);
var signalrClient = SignalRTestUtilities.GetSignalRManagementClient(context, handler);
// Create resource group
var location = SignalRTestUtilities.GetDefaultSignalRLocation(resourceClient);
var resourceGroup = SignalRTestUtilities.CreateResourceGroup(resourceClient, location);
// Check valid name
var signalrName = TestUtilities.GenerateName("signalr-service-test");
var checkNameRequest = signalrClient.SignalR.CheckNameAvailability(
location,
new NameAvailabilityParameters
{
Type = SignalRTestUtilities.SignalRResourceType,
Name = signalrName
});
Assert.True(checkNameRequest.NameAvailable);
Assert.Null(checkNameRequest.Reason);
Assert.Null(checkNameRequest.Message);
signalrName = SignalRTestUtilities.CreateSignalR(signalrClient, resourceGroup.Name, location).Name;
checkNameRequest = signalrClient.SignalR.CheckNameAvailability(
location,
new NameAvailabilityParameters
{
Type = SignalRTestUtilities.SignalRResourceType,
Name = signalrName,
});
Assert.False(checkNameRequest.NameAvailable);
Assert.Equal("AlreadyExists", checkNameRequest.Reason);
Assert.Equal("Domain already exists", checkNameRequest.Message);
}
}
[Fact]
public void SignalRFreeTierToStandardTest()
{
var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (var context = MockContext.Start(typeof(SignalRTests).FullName))
{
var resourceClient = SignalRTestUtilities.GetResourceManagementClient(context, handler);
var signalrClient = SignalRTestUtilities.GetSignalRManagementClient(context, handler);
var location = SignalRTestUtilities.GetDefaultSignalRLocation(resourceClient);
var resourceGroup = SignalRTestUtilities.CreateResourceGroup(resourceClient, location);
var signalrName = TestUtilities.GenerateName("signalr-service-test");
var signalr = SignalRTestUtilities.CreateSignalR(signalrClient, resourceGroup.Name, location, isStandard: false);
SignalRScenarioVerification(signalrClient, resourceGroup, signalr, false);
}
}
[Fact]
public void SignalRStandardTierToFreeTest()
{
var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (var context = MockContext.Start(typeof(SignalRTests).FullName))
{
var resourceClient = SignalRTestUtilities.GetResourceManagementClient(context, handler);
var signalrClient = SignalRTestUtilities.GetSignalRManagementClient(context, handler);
var location = SignalRTestUtilities.GetDefaultSignalRLocation(resourceClient);
var resourceGroup = SignalRTestUtilities.CreateResourceGroup(resourceClient, location);
var signalrName = TestUtilities.GenerateName("signalr-service-test");
var capacity = 2;
var signalr = SignalRTestUtilities.CreateSignalR(signalrClient, resourceGroup.Name, location, isStandard: true, capacity: capacity);
SignalRScenarioVerification(signalrClient, resourceGroup, signalr, true, capacity);
}
}
[Fact]
public void SignalRUsageTest()
{
var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (var context = MockContext.Start(typeof(SignalRTests).FullName))
{
var resourceClient = SignalRTestUtilities.GetResourceManagementClient(context, handler);
var signalrClient = SignalRTestUtilities.GetSignalRManagementClient(context, handler);
var location = SignalRTestUtilities.GetDefaultSignalRLocation(resourceClient);
var usages = signalrClient.Usages.List(location);
Assert.NotEmpty(usages);
var usage = usages.First();
Assert.NotNull(usage);
Assert.NotEmpty(usage.Id);
Assert.NotNull(usage.CurrentValue);
Assert.NotNull(usage.Limit);
Assert.NotNull(usage.Name);
Assert.NotEmpty(usage.Name.Value);
Assert.NotEmpty(usage.Name.LocalizedValue);
Assert.NotEmpty(usage.Unit);
}
}
private void SignalRScenarioVerification(SignalRManagementClient signalrClient, ResourceGroup resourceGroup, SignalRResource signalr, bool isStandard, int capacity = 1)
{
// Validate the newly created SignalR instance
SignalRTestUtilities.ValidateResourceDefaultTags(signalr);
Assert.NotNull(signalr.Sku);
if (isStandard)
{
Assert.Equal(SignalRSkuTier.Standard, signalr.Sku.Tier);
Assert.Equal("Standard_S1", signalr.Sku.Name);
Assert.Equal("S1", signalr.Sku.Size);
Assert.Equal(capacity, signalr.Sku.Capacity);
}
else
{
Assert.Equal(SignalRSkuTier.Free, signalr.Sku.Tier);
Assert.Equal("Free_F1", signalr.Sku.Name);
Assert.Equal("F1", signalr.Sku.Size);
Assert.Equal(capacity, signalr.Sku.Capacity);
}
// Currently, HostNamePrefix is used as a placeholder. It's not regarded by the RP
Assert.Null(signalr.HostNamePrefix);
Assert.Equal(ProvisioningState.Succeeded, signalr.ProvisioningState);
Assert.NotEmpty(signalr.HostName);
Assert.NotEmpty(signalr.ExternalIP);
Assert.NotNull(signalr.PublicPort);
Assert.NotNull(signalr.ServerPort);
Assert.NotEmpty(signalr.Version);
// List the SignalR instances by resource group
var signalrByResourceGroup = signalrClient.SignalR.ListByResourceGroup(resourceGroup.Name);
Assert.Single(signalrByResourceGroup);
signalr = signalrByResourceGroup.FirstOrDefault(r => StringComparer.OrdinalIgnoreCase.Equals(r.Name, signalr.Name));
SignalRTestUtilities.ValidateResourceDefaultTags(signalr);
// Get the SignalR instance by name
signalr = signalrClient.SignalR.Get(resourceGroup.Name, signalr.Name);
SignalRTestUtilities.ValidateResourceDefaultTags(signalr);
// List keys
var keys = signalrClient.SignalR.ListKeys(resourceGroup.Name, signalr.Name);
Assert.NotNull(keys);
Assert.NotEmpty(keys.PrimaryKey);
Assert.NotEmpty(keys.PrimaryConnectionString);
Assert.NotEmpty(keys.SecondaryKey);
Assert.NotEmpty(keys.SecondaryConnectionString);
// Update the SignalR instance
capacity = isStandard ? 1 : 5;
signalr = signalrClient.SignalR.Update(resourceGroup.Name, signalr.Name, new SignalRUpdateParameters
{
Tags = SignalRTestUtilities.DefaultNewTags,
Sku = new ResourceSku
{
Name = isStandard ? "Free_F1" : "Standard_S1",
Tier = isStandard ? "Free" : "Standard",
Size = isStandard ? "F1" : "S1",
Capacity = capacity,
},
Properties = new SignalRCreateOrUpdateProperties
{
HostNamePrefix = TestUtilities.GenerateName("signalr-service-test"),
},
});
// Validate the updated SignalR instance
SignalRTestUtilities.ValidateResourceDefaultNewTags(signalr);
Assert.NotNull(signalr.Sku);
if (isStandard)
{
Assert.Equal(SignalRSkuTier.Free, signalr.Sku.Tier);
Assert.Equal("Free_F1", signalr.Sku.Name);
Assert.Equal("F1", signalr.Sku.Size);
Assert.Equal(capacity, signalr.Sku.Capacity);
}
else
{
Assert.Equal(SignalRSkuTier.Standard, signalr.Sku.Tier);
Assert.Equal("Standard_S1", signalr.Sku.Name);
Assert.Equal("S1", signalr.Sku.Size);
Assert.Equal(capacity, signalr.Sku.Capacity);
}
Assert.Null(signalr.HostNamePrefix);
Assert.Equal(ProvisioningState.Succeeded, signalr.ProvisioningState);
Assert.NotEmpty(signalr.HostName);
Assert.NotEmpty(signalr.ExternalIP);
Assert.NotNull(signalr.PublicPort);
Assert.NotNull(signalr.ServerPort);
Assert.NotEmpty(signalr.Version);
// List keys of the updated SignalR instance
keys = signalrClient.SignalR.ListKeys(resourceGroup.Name, signalr.Name);
Assert.NotNull(keys);
Assert.NotEmpty(keys.PrimaryKey);
Assert.NotEmpty(keys.PrimaryConnectionString);
Assert.NotEmpty(keys.SecondaryKey);
Assert.NotEmpty(keys.SecondaryConnectionString);
// Regenerate primary key
var newKeys1 = signalrClient.SignalR.RegenerateKey(resourceGroup.Name, signalr.Name, new RegenerateKeyParameters
{
KeyType = "Primary",
});
Assert.NotNull(newKeys1);
Assert.NotEqual(keys.PrimaryKey, newKeys1.PrimaryKey);
Assert.NotEqual(keys.PrimaryConnectionString, newKeys1.PrimaryConnectionString);
Assert.Null(newKeys1.SecondaryKey);
Assert.Null(newKeys1.SecondaryConnectionString);
// Ensure only the primary key is regenerated
newKeys1 = signalrClient.SignalR.ListKeys(resourceGroup.Name, signalr.Name);
Assert.NotNull(newKeys1);
Assert.NotEqual(keys.PrimaryKey, newKeys1.PrimaryKey);
Assert.NotEqual(keys.PrimaryConnectionString, newKeys1.PrimaryConnectionString);
Assert.Equal(keys.SecondaryKey, newKeys1.SecondaryKey);
Assert.Equal(keys.SecondaryConnectionString, newKeys1.SecondaryConnectionString);
// Regenerate secondary key
var newKeys2 = signalrClient.SignalR.RegenerateKey(resourceGroup.Name, signalr.Name, new RegenerateKeyParameters
{
KeyType = "Secondary",
});
Assert.NotNull(newKeys2);
Assert.Null(newKeys2.PrimaryKey);
Assert.Null(newKeys2.PrimaryConnectionString);
Assert.NotEqual(keys.SecondaryKey, newKeys2.SecondaryKey);
Assert.NotEqual(keys.SecondaryConnectionString, newKeys2.SecondaryConnectionString);
// ensure only the secondary key is regenerated
newKeys2 = signalrClient.SignalR.ListKeys(resourceGroup.Name, signalr.Name);
Assert.NotNull(newKeys2);
Assert.Equal(newKeys1.PrimaryKey, newKeys2.PrimaryKey);
Assert.Equal(newKeys1.PrimaryConnectionString, newKeys2.PrimaryConnectionString);
Assert.NotEqual(newKeys1.SecondaryKey, newKeys2.SecondaryKey);
Assert.NotEqual(newKeys1.SecondaryConnectionString, newKeys2.SecondaryConnectionString);
// Delete the SignalR instance
signalrClient.SignalR.Delete(resourceGroup.Name, signalr.Name);
// Delete again, should be no-op
signalrClient.SignalR.Delete(resourceGroup.Name, signalr.Name);
}
}
}
| |
// 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.DevTestLabs
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// LabsOperations operations.
/// </summary>
public partial interface ILabsOperations
{
/// <summary>
/// List labs in a subscription.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<Lab>>> ListBySubscriptionWithHttpMessagesAsync(ODataQuery<Lab> odataQuery = default(ODataQuery<Lab>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List labs in a resource group.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<Lab>>> ListByResourceGroupWithHttpMessagesAsync(ODataQuery<Lab> odataQuery = default(ODataQuery<Lab>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get lab.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example:
/// 'properties($select=defaultStorageAccount)'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Lab>> GetWithHttpMessagesAsync(string name, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or replace an existing lab. This operation can take a while
/// to complete.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// A lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Lab>> CreateOrUpdateWithHttpMessagesAsync(string name, Lab lab, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or replace an existing lab. This operation can take a while
/// to complete.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// A lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Lab>> BeginCreateOrUpdateWithHttpMessagesAsync(string name, Lab lab, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete lab. This operation can take a while to complete.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete lab. This operation can take a while to complete.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Modify properties of labs.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// A lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Lab>> UpdateWithHttpMessagesAsync(string name, LabFragment lab, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Claim a random claimable virtual machine in the lab. This
/// operation can take a while to complete.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> ClaimAnyVmWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Claim a random claimable virtual machine in the lab. This
/// operation can take a while to complete.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginClaimAnyVmWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create virtual machines in a lab. This operation can take a while
/// to complete.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='labVirtualMachineCreationParameter'>
/// Properties for creating a virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> CreateEnvironmentWithHttpMessagesAsync(string name, LabVirtualMachineCreationParameter labVirtualMachineCreationParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create virtual machines in a lab. This operation can take a while
/// to complete.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='labVirtualMachineCreationParameter'>
/// Properties for creating a virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginCreateEnvironmentWithHttpMessagesAsync(string name, LabVirtualMachineCreationParameter labVirtualMachineCreationParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Exports the lab resource usage into a storage account This
/// operation can take a while to complete.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='exportResourceUsageParameters'>
/// The parameters of the export operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> ExportResourceUsageWithHttpMessagesAsync(string name, ExportResourceUsageParameters exportResourceUsageParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Exports the lab resource usage into a storage account This
/// operation can take a while to complete.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='exportResourceUsageParameters'>
/// The parameters of the export operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginExportResourceUsageWithHttpMessagesAsync(string name, ExportResourceUsageParameters exportResourceUsageParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generate a URI for uploading custom disk images to a Lab.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='generateUploadUriParameter'>
/// Properties for generating an upload URI.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<GenerateUploadUriResponse>> GenerateUploadUriWithHttpMessagesAsync(string name, GenerateUploadUriParameter generateUploadUriParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List disk images available for custom image creation.
/// </summary>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<LabVhd>>> ListVhdsWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List labs in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<Lab>>> ListBySubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List labs in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<Lab>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List disk images available for custom image creation.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<LabVhd>>> ListVhdsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ToolStripCustomizer.Properties;
namespace ToolStripCustomizer
{
static class Generator
{
private const string CsPattern =
@"public \s+ override \s+ Color \s+ (?<Property>\w+) \s* \{ \s*
get \s* \{ \s* return \s+ Color\.From
(( Name \( \s* ""(?<Name>\w+)"" \s* \) ) |
( Argb \( (\s*(?<A>\d+)\s*,)? \s* (?<R>\d+) \s*,\s* (?<G>\d+) \s*,\s* (?<B>\d+) \s* \) ))
; \s* \} \s* \}";
private const string VbPattern =
@"Public \s+ Overrides \s+ ReadOnly \s+ Property \s+ (?<Property>\w+)\(\) \s+ As \s+ Color \s*
Get \s* Return \s+ Color\.From
(( Name \( \s* ""(?<Name>\w+)"" \s* \) ) |
( Argb \( (\s*(?<A>\d+)\s*,)? \s* (?<R>\d+) \s*,\s* (?<G>\d+) \s*,\s* (?<B>\d+) \s* \) ))
\s+ End \s+ Get";
private static readonly string CsTemplate = Settings.Default.Template;
private static readonly string VbTemplate = Settings.Default.TemplateVB;
private static readonly string Header = Settings.Default.AutoGeneratedHeader;
private static readonly string CsComment = Settings.Default.CommentCS;
private static readonly string VbComment = Settings.Default.CommentVB;
private static readonly string CsPropertyNameTemplate = Settings.Default.PropertyTemplateName;
private static readonly string VbPropertyNameTemplate = Settings.Default.PropertyTemplateNameVB;
private static readonly string CsPropertyArgbTemplate = Settings.Default.PropertyTemplateArgb;
private static readonly string VbPropertyArgbTemplate = Settings.Default.PropertyTemplateArgbVB;
public static void SaveAs(CustomizableColorTable table, string filePath)
{
if (table == null) throw new ArgumentNullException("table");
if (filePath == null) throw new ArgumentNullException("filePath");
// VB or C#?
bool vb = IsVbFile(filePath);
// Get user-defined namespace and class name.
string nameSpace = Settings.Default.DefaultNamespace;
string className = GetClassName(filePath);
StringBuilder properties = new StringBuilder();
// For each color in color table.
IEnumerable<ColorTableGroup> values = Enum.GetValues(
typeof(ColorTableGroup)).Cast<ColorTableGroup>();
foreach (ColorTableGroup colorGroup in values)
{
// Color and name of the property.
Color color = table[colorGroup];
string propertyName = Enum.GetName(typeof(ColorTableGroup), colorGroup);
// Templates for Color.FromArgb and Color.FromName.
string propertyTemplateArgb = vb ? VbPropertyArgbTemplate
: CsPropertyArgbTemplate;
string propertyTemplateName = vb ? VbPropertyNameTemplate
: CsPropertyNameTemplate;
// Compose property.
string property;
if (color.IsNamedColor)
{
property = string.Format(CultureInfo.InvariantCulture,
propertyTemplateName, propertyName,
color.Name);
}
else
{
property = string.Format(CultureInfo.InvariantCulture,
propertyTemplateArgb, propertyName,
color.A, color.R, color.G, color.B);
}
// Append to list.
properties.AppendLine(property);
}
string header = Settings.Default.IncludeHeader
? string.Format(
CultureInfo.InvariantCulture,
Header, vb ? VbComment : CsComment)
: string.Empty;
// Generate output.
string output = string.Format(
CultureInfo.InvariantCulture,
vb ? VbTemplate : CsTemplate,
header, nameSpace, className, properties);
File.WriteAllText(filePath, output);
}
public static void LoadFrom(CustomizableColorTable table, string filePath)
{
if (table == null) throw new ArgumentNullException("table");
if (filePath == null) throw new ArgumentNullException("filePath");
// VB or C#?
bool vb = IsVbFile(filePath);
Regex regex = new Regex(
vb ? VbPattern : CsPattern,
RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace |
RegexOptions.Multiline | RegexOptions.IgnoreCase);
// Try to open and read file.
string text = File.ReadAllText(filePath);
Match match = regex.Match(text);
if (!match.Success) throw new InvalidOperationException();
// Reset all colors to their default values.
table.InitFromBase(true);
bool modified = false;
while (match.Success)
{
string property = match.Groups["Property"].Value;
string name = match.Groups["Name"].Value;
Color color;
if (!string.IsNullOrEmpty(name))
{
color = Color.FromName(name);
}
else
{
int r = int.Parse(match.Groups["R"].Value);
int g = int.Parse(match.Groups["G"].Value);
int b = int.Parse(match.Groups["B"].Value);
// Alpha chanel is optional.
int a;
if (!int.TryParse(match.Groups["A"].Value, out a)) a = 255;
color = Color.FromArgb(a, r, g, b);
}
try
{
ColorTableGroup colorGroup = (ColorTableGroup) Enum.Parse(
typeof (ColorTableGroup), property);
table[colorGroup] = color;
modified = true;
}
catch (ArgumentException)
{
}
match = match.NextMatch();
}
if (modified)
{
table.MakeColorsDefault();
}
}
private static string GetClassName(string fileName)
{
var name = new StringBuilder(Path.GetFileNameWithoutExtension(fileName));
for (int i = name.Length - 1; i >= 0; i--)
{
if (!Char.IsLetterOrDigit(name[i]) && name[i] != '_')
{
name.Remove(i, 1);
}
}
if (name.Length == 0)
{
return "MyColorTable";
}
else if (Char.IsDigit(name[0]))
{
name.Insert(0, '_');
}
return name.ToString();
}
private static bool IsVbFile(string filePath)
{
if (filePath == null) throw new ArgumentNullException("filePath");
bool vb = false;
string ext = Path.GetExtension(filePath);
if (!string.IsNullOrEmpty(ext))
{
vb = ext.Equals(".vb", StringComparison.OrdinalIgnoreCase);
}
return vb;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Channel option specified when creating a channel.
/// Corresponds to grpc_channel_args from grpc/grpc.h.
/// </summary>
public sealed class ChannelOption
{
/// <summary>
/// Type of <c>ChannelOption</c>.
/// </summary>
public enum OptionType
{
/// <summary>
/// Channel option with integer value.
/// </summary>
Integer,
/// <summary>
/// Channel option with string value.
/// </summary>
String
}
private readonly OptionType type;
private readonly string name;
private readonly int intValue;
private readonly string stringValue;
/// <summary>
/// Creates a channel option with a string value.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="stringValue">String value.</param>
public ChannelOption(string name, string stringValue)
{
this.type = OptionType.String;
this.name = Preconditions.CheckNotNull(name, "name");
this.stringValue = Preconditions.CheckNotNull(stringValue, "stringValue");
}
/// <summary>
/// Creates a channel option with an integer value.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="intValue">Integer value.</param>
public ChannelOption(string name, int intValue)
{
this.type = OptionType.Integer;
this.name = Preconditions.CheckNotNull(name, "name");
this.intValue = intValue;
}
/// <summary>
/// Gets the type of the <c>ChannelOption</c>.
/// </summary>
public OptionType Type
{
get
{
return type;
}
}
/// <summary>
/// Gets the name of the <c>ChannelOption</c>.
/// </summary>
public string Name
{
get
{
return name;
}
}
/// <summary>
/// Gets the integer value the <c>ChannelOption</c>.
/// </summary>
public int IntValue
{
get
{
Preconditions.CheckState(type == OptionType.Integer);
return intValue;
}
}
/// <summary>
/// Gets the string value the <c>ChannelOption</c>.
/// </summary>
public string StringValue
{
get
{
Preconditions.CheckState(type == OptionType.String);
return stringValue;
}
}
}
/// <summary>
/// Defines names of supported channel options.
/// </summary>
public static class ChannelOptions
{
/// <summary>Override SSL target check. Only to be used for testing.</summary>
public const string SslTargetNameOverride = "grpc.ssl_target_name_override";
/// <summary>Enable census for tracing and stats collection</summary>
public const string Census = "grpc.census";
/// <summary>Maximum number of concurrent incoming streams to allow on a http2 connection</summary>
public const string MaxConcurrentStreams = "grpc.max_concurrent_streams";
/// <summary>Maximum message length that the channel can receive</summary>
public const string MaxMessageLength = "grpc.max_message_length";
/// <summary>Initial sequence number for http2 transports</summary>
public const string Http2InitialSequenceNumber = "grpc.http2.initial_sequence_number";
/// <summary>Default authority for calls.</summary>
public const string DefaultAuthority = "grpc.default_authority";
/// <summary>Primary user agent: goes at the start of the user-agent metadata</summary>
public const string PrimaryUserAgentString = "grpc.primary_user_agent";
/// <summary>Secondary user agent: goes at the end of the user-agent metadata</summary>
public const string SecondaryUserAgentString = "grpc.secondary_user_agent";
/// <summary>
/// Creates native object for a collection of channel options.
/// </summary>
/// <returns>The native channel arguments.</returns>
internal static ChannelArgsSafeHandle CreateChannelArgs(ICollection<ChannelOption> options)
{
if (options == null || options.Count == 0)
{
return ChannelArgsSafeHandle.CreateNull();
}
ChannelArgsSafeHandle nativeArgs = null;
try
{
nativeArgs = ChannelArgsSafeHandle.Create(options.Count);
int i = 0;
foreach (var option in options)
{
if (option.Type == ChannelOption.OptionType.Integer)
{
nativeArgs.SetInteger(i, option.Name, option.IntValue);
}
else if (option.Type == ChannelOption.OptionType.String)
{
nativeArgs.SetString(i, option.Name, option.StringValue);
}
else
{
throw new InvalidOperationException("Unknown option type");
}
i++;
}
return nativeArgs;
}
catch (Exception)
{
if (nativeArgs != null)
{
nativeArgs.Dispose();
}
throw;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AxiomCoders.PdfTemplateEditor.Controls;
namespace AxiomCoders.PdfTemplateEditor.Controls
{
public struct CMYKColor
{
public float CVal;
public float MVal;
public float YVal;
public float KVal;
};
public partial class ColorDlg : Form
{
public CMYKColor cmykColor;
public ColorDlg()
{
InitializeComponent();
colorTable.SelectedIndexChanged += new EventHandler(this.colorTable_SelectedIndexChanged);
colorWheel.SelectedColorChanged += new EventHandler(this.colorWheel_SelectedColorChanged);
colorSlider2.SelectedValueChanged += new EventHandler(this.colorSlider2_SelectedValueChanged);
colorList.SelectedIndexChanged += new EventHandler(this.colorList_SelectedIndexChanged);
}
private bool firstSet;
private HSLColor selHSLColor;
public Color SelectedColor
{
get{ return selHSLColor.Color; }
set { selHSLColor = new HSLColor(value); }
}
private int DefaultColorHue;
private void tabControl1_Selected(object sender, EventArgs e)
{
if(tabControl1.SelectedIndex == 0)
{
if(colorTable.ColorExist(SelectedColor))
{
colorTable.SelectedItem = SelectedColor;
}else{
colorTable.SetCustomColor(SelectedColor);
}
}
if(tabControl1.SelectedIndex == 1)
{
colorWheel.SelectedHSLColor = selHSLColor;
colorSlider2.SelectedHSLColor = selHSLColor;
colorSlider2.Percent = (float)selHSLColor.Lightness;
}
if(tabControl1.SelectedIndex == 3)
{
DefaultColorHue = (int)selHSLColor.Hue;
UpdateFineTune();
}
}
private void colorTable_SelectedIndexChanged(object sender, EventArgs e)
{
selHSLColor.Color = colorTable.SelectedItem;
selHSLColor.Hue = colorTable.SelectedItem.GetHue();
selHSLColor.Saturation = colorTable.SelectedItem.GetSaturation();
selHSLColor.Lightness = colorTable.SelectedItem.GetBrightness();
UpdateCMYKValues();
lblFinalColorValue.BackColor = colorTable.SelectedItem;
}
private void colorWheel_SelectedColorChanged(object sender, EventArgs e)
{
selHSLColor = colorWheel.SelectedHSLColor;
//selHSLColor.Lightness = colorSlider2.Percent;
colorSlider2.SelectedHSLColor = selHSLColor;
UpdateCMYKValues();
lblFinalColorValue.BackColor = SelectedColor;
}
private void colorSlider2_SelectedValueChanged(object sender, EventArgs e)
{
selHSLColor = colorSlider2.SelectedHSLColor;
colorWheel.SelectedHSLColor = selHSLColor;
UpdateCMYKValues();
lblFinalColorValue.BackColor = SelectedColor;
}
private void colorList_SelectedIndexChanged(object sender, EventArgs e)
{
Color tmpColor = (Color)colorList.SelectedItem;
selHSLColor.Color = tmpColor;
selHSLColor.Hue = tmpColor.GetHue();
selHSLColor.Saturation = tmpColor.GetSaturation();
selHSLColor.Lightness = tmpColor.GetBrightness();
UpdateCMYKValues();
lblFinalColorValue.BackColor = selHSLColor.Color;
}
private void UpdateFineTune()
{
UpdateCMYKValues();
lblFinalColorValue.BackColor = selHSLColor.Color;
}
private void UpdateCMYKValues()
{
float i = 1.0f;
float Cyan, Yellow, Magenta, Black;
Cyan = 1.0f - (float)(selHSLColor.Color.R / 255f);
Magenta = 1.0f - (float)(selHSLColor.Color.G / 255f);
Yellow = 1.0f - (float)(selHSLColor.Color.B / 255f);
Black = Math.Min(Math.Min(Cyan, Magenta),Yellow);
Cyan = Math.Min(1, Math.Max(0, Cyan - Black));
Magenta = Math.Min(1, Math.Max(0, Magenta - Black));
Yellow = Math.Min(1, Math.Max(0, Yellow - Black));
Black = Math.Min(1, Math.Max(0, Black));
int CVal = (int)(Cyan * 100.0f);
int MVal = (int)(Magenta * 100.0f);
int YVal = (int)(Yellow * 100.0f);
int KVal = (int)(Black * 100.0f);
txtCValue.Text = CVal.ToString();
txtMValue.Text = MVal.ToString();
txtYValue.Text = YVal.ToString();
txtKValue.Text = KVal.ToString();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void btnOk_Click(object sender, EventArgs e)
{
if(txtCValue.Text == "")
UpdateCMYKValues();
cmykColor.CVal = (float)(Convert.ToDouble(txtCValue.Text));
cmykColor.MVal = (float)(Convert.ToDouble(txtMValue.Text));
cmykColor.YVal = (float)(Convert.ToDouble(txtYValue.Text));
cmykColor.KVal = (float)(Convert.ToDouble(txtCValue.Text));
this.DialogResult = DialogResult.OK;
this.Close();
}
public DialogResult ShowDlg(Color baseColor)
{
if(baseColor != null)
{
selHSLColor.Hue = baseColor.GetHue();
selHSLColor.Saturation = baseColor.GetSaturation();
selHSLColor.Lightness = baseColor.GetBrightness();
selHSLColor.Color = baseColor;
lblFinalColorValue.BackColor = baseColor;
}
return ShowDialog();
}
}
}
| |
using System;
using Swicli.Library;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Security;
namespace SWICFFITests
{
public static class SWICFFITestsProgram
{
static SWICFFITestsProgram()
{
Console.WriteLine("SWICLITestDLL::SWICLITestClass.<clinit>()");
}
public static void Main(String[] args)
{
PrologCLR.ClientReady = true;
PrologCLR.Main(args);
return;
SWICFFITestsWindows.WinMain(args);
#if NET40
dynamic d = new PInvokeMetaObject("glibc");
#endif
PrologCLR.cliDynTest_1();
// PrologCLR.cliDynTest_3<String>();
PrologCLR.cliDynTest_2();
SWICFFITestsWindows.install();
}
public static void install()
{
Console.WriteLine("SWICLITestDLL::SWICLITestClass.install()");
//Console.WriteLine("SWICLITestClass::install press ctrol-D to leave CSharp");
//System.Reflection.Assembly.Load("csharp").EntryPoint.DeclaringType.GetMethod("Main", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).Invoke(null, new object[] { new String[0] });
}
}
[StructLayout(LayoutKind.Sequential)]
public struct WINHTTP_CURRENT_USER_IE_PROXY_CONFIG
{
[MarshalAs(UnmanagedType.Bool)]
bool AutoDetect;
[MarshalAs(UnmanagedType.LPWStr)]
string AutoConfigUrl;
[MarshalAs(UnmanagedType.LPWStr)]
string Proxy;
[MarshalAs(UnmanagedType.LPWStr)]
string ProxyBypass;
}
[SuppressUnmanagedCodeSecurity]
public static class SWICFFITestsWindows
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
static SWICFFITestsWindows()
{
Console.WriteLine(typeof(SWICFFITestsWindows).ToString() + ".<clinit>()");
}
public static void WinMain(String[] args)
{
PInvokeMetaObject pi = PrologCLR.cliGetDll("user32.dll");
pi.Invoke<int>("MessageBox",
new Type[] { typeof(IntPtr), typeof(String), typeof(String), typeof(uint) },
typeof(int),
(object)null, new IntPtr(0), "Hello World!", "Hello Dialog", (uint)0);
//pi.InvokeDLL<int>("MessageBox", new IntPtr(0), "Hello World!", "Hello Dialog", 0);
MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
}
/*
HANDLE CreateEvent(
LPSECURITY_ATTRIBUTES lpEventAttributes,
BOOL bManualReset,
BOOL bInitialState,
LPCTSTR lpName
);
*/
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateEvent(IntPtr lpEventAttributes,
bool bManualReset, bool bInitialState, [System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)] string lpName);
/*
HANDLE CreateFileMapping(
HANDLE hFile,
LPSECURITY_ATTRIBUTES lpAttributes,
DWORD flProtect,
DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow,
LPCTSTR lpName
);
*/
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateFileMapping(IntPtr hFile,
IntPtr lpFileMappingAttributes, uint flProtect,
uint dwMaximumSizeHigh,
uint dwMaximumSizeLow, string lpName);
[DllImport("shell32.dll", EntryPoint = "ShellExecute", SetLastError = true)]
public static extern string ShellExecute(IntPtr HWND, string operation, string file, string parameters, string directory, int showcmd);
public static void install()
{
Console.WriteLine(typeof(SWICFFITestsWindows).ToString() + ".install()");
}
[DllImport("dwmapi.dll")]
unsafe static extern int DwmGetWindowAttribute(
IntPtr hwnd,
uint dwAttribute,
void* pvAttribute,
uint cbAttribute);
[DllImport("kernel32.dll", SetLastError = false)]
public static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetThreadPriority(
IntPtr hThread,
int nPriority);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateFileMappingW(
IntPtr hFile,
IntPtr lpFileMappingAttributes,
uint flProtect,
uint dwMaximumSizeHigh,
uint dwMaximumSizeLow,
[MarshalAs(UnmanagedType.LPTStr)] string lpName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr MapViewOfFile(
IntPtr hFileMappingObject,
uint dwDesiredAccess,
uint dwFileOffsetHigh,
uint dwFileOffsetLow,
UIntPtr dwNumberOfBytesToMap);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetProcessDPIAware();
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowScrollBar(
IntPtr hWnd,
int wBar,
[MarshalAs(UnmanagedType.Bool)] bool bShow);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetVersionEx(ref OSVERSIONINFOEX lpVersionInfo);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetLayeredWindowAttributes(
IntPtr hwnd,
out uint pcrKey,
out byte pbAlpha,
out uint pdwFlags);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "2")]
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetLayeredWindowAttributes(
IntPtr hwnd,
uint crKey,
byte bAlpha,
uint dwFlags);
[DllImport("gdi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateFontW(
int nHeight,
int nWidth,
int nEscapement,
int nOrientation,
int fnWeight,
uint fdwItalic,
uint fdwUnderline,
uint fdwStrikeOut,
uint fdwCharSet,
uint fdwOutputPrecision,
uint fdwClipPrecision,
uint fdwQuality,
uint fdwPitchAndFamily,
string lpszFace);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left, Top, Right, Bottom;
public RECT(int left, int top, int right, int bottom)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
public RECT(System.Drawing.Rectangle r) : this(r.Left, r.Top, r.Right, r.Bottom) { }
public int X
{
get { return Left; }
set { Right -= (Left - value); Left = value; }
}
public int Y
{
get { return Top; }
set { Bottom -= (Top - value); Top = value; }
}
public int Height
{
get { return Bottom - Top; }
set { Bottom = value + Top; }
}
public int Width
{
get { return Right - Left; }
set { Right = value + Left; }
}
public System.Drawing.Point Location
{
get { return new System.Drawing.Point(Left, Top); }
set { X = value.X; Y = value.Y; }
}
public System.Drawing.Size Size
{
get { return new System.Drawing.Size(Width, Height); }
set { Width = value.Width; Height = value.Height; }
}
public static implicit operator System.Drawing.Rectangle(RECT r)
{
return new System.Drawing.Rectangle(r.Left, r.Top, r.Width, r.Height);
}
public static implicit operator RECT(System.Drawing.Rectangle r)
{
return new RECT(r);
}
public static bool operator ==(RECT r1, RECT r2)
{
return r1.Equals(r2);
}
public static bool operator !=(RECT r1, RECT r2)
{
return !r1.Equals(r2);
}
public bool Equals(RECT r)
{
return r.Left == Left && r.Top == Top && r.Right == Right && r.Bottom == Bottom;
}
public override bool Equals(object obj)
{
if (obj is RECT)
return Equals((RECT)obj);
else if (obj is System.Drawing.Rectangle)
return Equals(new RECT((System.Drawing.Rectangle)obj));
return false;
}
public override int GetHashCode()
{
return ((System.Drawing.Rectangle)this).GetHashCode();
}
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.CurrentCulture, "{{Left={0},Top={1},Right={2},Bottom={3}}}", Left, Top, Right, Bottom);
}
}
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct BITMAPINFO
{
/// <summary>
/// A BITMAPINFOHEADER structure that contains information about the dimensions of color format.
/// </summary>
public BITMAPINFOHEADER bmiHeader;
/// <summary>
/// An array of RGBQUAD. The elements of the array that make up the color table.
/// </summary>
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 1, ArraySubType = UnmanagedType.Struct)]
public RGBQUAD[] bmiColors;
}
[StructLayout(LayoutKind.Sequential)]
public struct RGBQUAD
{
public byte rgbBlue;
public byte rgbGreen;
public byte rgbRed;
public byte rgbReserved;
}
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int DrawTextW(
IntPtr hdc,
string lpString,
int nCount,
ref RECT lpRect,
uint uFormat);
[DllImport("gdi32.dll", SetLastError = true)]
public static extern IntPtr CreateDIBSection(
IntPtr hdc,
ref BITMAPINFO pbmi,
uint iUsage,
out IntPtr ppvBits,
IntPtr hSection,
uint dwOffset);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateFileW(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public unsafe static extern bool WriteFile(
IntPtr hFile,
void* lpBuffer,
uint nNumberOfBytesToWrite,
out uint lpNumberOfBytesWritten,
IntPtr lpOverlapped);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public unsafe static extern bool ReadFile(
Microsoft.Win32.SafeHandles.SafeFileHandle sfhFile,
void* lpBuffer,
uint nNumberOfBytesToRead,
out uint lpNumberOfBytesRead,
IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetHandleInformation(
IntPtr hObject,
uint dwMask,
uint dwFlags);
[DllImport("user32.dll", SetLastError = false)]
public static extern int GetUpdateRgn(
IntPtr hWnd,
IntPtr hRgn,
[MarshalAs(UnmanagedType.Bool)] bool bErase);
[DllImport("uxtheme.dll", PreserveSig = false, SetLastError = false)]
public static extern void DrawThemeBackground(
IntPtr hTheme,
IntPtr hdc,
int iPartId,
int iStateId,
ref RECT pRect,
ref RECT pClipRect);
[DllImport("uxtheme.dll", CharSet = CharSet.Unicode, SetLastError = false)]
public static extern IntPtr OpenThemeData(
IntPtr hwnd,
[MarshalAs(UnmanagedType.LPWStr)] string pszClassList);
[DllImport("uxtheme.dll", PreserveSig = false)]
public static extern void CloseThemeData(IntPtr hTheme);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr FindWindowExW(
IntPtr hwndParent,
IntPtr hwndChildAfter,
[MarshalAs(UnmanagedType.LPWStr)] string lpszClass,
[MarshalAs(UnmanagedType.LPWStr)] string lpszWindow);
[DllImport("user32.dll", SetLastError = false)]
public static extern IntPtr SendMessageW(
IntPtr hWnd,
uint msg,
IntPtr wParam,
IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public extern static bool PostMessageW(
IntPtr handle,
uint msg,
IntPtr wParam,
IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowLongW(
IntPtr hWnd,
int nIndex);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint SetWindowLongW(
IntPtr hWnd,
int nIndex,
uint dwNewLong);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryPerformanceCounter(out ulong lpPerformanceCount);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryPerformanceFrequency(out ulong lpFrequency);
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
public static extern unsafe void memcpy(void* dst, void* src, UIntPtr length);
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
public static extern unsafe void memset(void* dst, int c, UIntPtr length);
[DllImport("User32.dll", SetLastError = false)]
public static extern int GetSystemMetrics(int nIndex);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint WaitForSingleObject(
IntPtr hHandle,
uint dwMilliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint WaitForMultipleObjects(
uint nCount,
IntPtr[] lpHandles,
[MarshalAs(UnmanagedType.Bool)] bool bWaitAll,
uint dwMilliseconds);
public static uint WaitForMultipleObjects(IntPtr[] lpHandles, bool bWaitAll, uint dwMilliseconds)
{
return WaitForMultipleObjects((uint)lpHandles.Length, lpHandles, bWaitAll, dwMilliseconds);
}
[DllImport("wtsapi32.dll", SetLastError = true)]
public static extern uint WTSRegisterSessionNotification(IntPtr hWnd, uint dwFlags);
[DllImport("wtsapi32.dll", SetLastError = true)]
public static extern uint WTSUnRegisterSessionNotification(IntPtr hWnd);
[DllImport("Gdi32.dll", SetLastError = true)]
public static extern uint GetRegionData_Borked(
IntPtr hRgn,
uint dwCount,
IntPtr lpRgnData);
[DllImport("Gdi32.dll", SetLastError = true)]
public unsafe static extern IntPtr CreateRectRgn(
int nLeftRect,
int nTopRect,
int nRightRect,
int nBottomRect);
[DllImport("Gdi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public extern static bool MoveToEx(
IntPtr hdc,
int X,
int Y,
out POINT lpPoint);
[DllImport("Gdi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public extern static bool LineTo(
IntPtr hdc,
int nXEnd,
int nYEnd);
[DllImport("User32.dll", SetLastError = true)]
public extern static int FillRect(
IntPtr hDC,
ref RECT lprc,
IntPtr hbr);
[DllImport("Gdi32.dll", SetLastError = true)]
public extern static IntPtr CreatePen(
int fnPenStyle,
int nWidth,
uint crColor);
[DllImport("Gdi32.dll", SetLastError = true)]
public extern static IntPtr CreateSolidBrush(uint crColor);
[DllImport("Gdi32.dll", SetLastError = false)]
public extern static IntPtr SelectObject(
IntPtr hdc,
IntPtr hgdiobj);
[DllImport("Gdi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public extern static bool DeleteObject(IntPtr hObject);
[DllImport("Gdi32.dll", SetLastError = true)]
public extern static uint DeleteDC(IntPtr hdc);
[DllImport("Gdi32.Dll", SetLastError = true)]
public extern static IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("Gdi32.Dll", SetLastError = true)]
public extern static uint BitBlt(
IntPtr hdcDest,
int nXDest,
int nYDest,
int nWidth,
int nHeight,
IntPtr hdcSrc,
int nXSrc,
int nYSrc,
uint dwRop);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr VirtualAlloc(
IntPtr lpAddress,
UIntPtr dwSize,
uint flAllocationType,
uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool VirtualFree(
IntPtr lpAddress,
UIntPtr dwSize,
uint dwFreeType);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool VirtualProtect(
IntPtr lpAddress,
UIntPtr dwSize,
uint flNewProtect,
out uint lpflOldProtect);
[DllImport("Kernel32.dll", SetLastError = false)]
public static extern IntPtr HeapAlloc(IntPtr hHeap, uint dwFlags, UIntPtr dwBytes);
[DllImport("Kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HeapFree(IntPtr hHeap, uint dwFlags, IntPtr lpMem);
[DllImport("Kernel32.dll", SetLastError = false)]
public static extern UIntPtr HeapSize(IntPtr hHeap, uint dwFlags, IntPtr lpMem);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern IntPtr HeapCreate(
uint flOptions,
[MarshalAs(UnmanagedType.SysUInt)] IntPtr dwInitialSize,
[MarshalAs(UnmanagedType.SysUInt)] IntPtr dwMaximumSize
);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern uint HeapDestroy(IntPtr hHeap);
[DllImport("Kernel32.Dll", SetLastError = true)]
public unsafe static extern uint HeapSetInformation(
IntPtr HeapHandle,
int HeapInformationClass,
void* HeapInformation,
uint HeapInformationLength
);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr LoadLibraryW(
[MarshalAs(UnmanagedType.LPWStr)] string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FreeLibrary(IntPtr hModule);
[DllImport("winhttp.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpGetIEProxyConfigForCurrentUser(ref WINHTTP_CURRENT_USER_IE_PROXY_CONFIG pProxyConfig);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GlobalFree(IntPtr hMem);
[DllImport("user32.dll", SetLastError = false)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = false)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = false)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public const int ERROR_SERVICE_NOT_ACTIVE = 1062;
public const int VER_PLATFORM_WIN32s = 0;
public const int VER_PLATFORM_WIN32_WINDOWS = 1;
public const int VER_PLATFORM_WIN32_NT = 2;
public const int VER_PLATFORM_WIN32_HH = 3;
public const int VER_PLATFORM_WIN32_CE = 3;
public const int VER_BUILDNUMBER = 0x0000004; // dwBuildNumber
public const int VER_MAJORVERSION = 0x0000002; // dwMajorVersion
// If you are testing the major version, you must also test the minor version and the service pack major and minor versions.
public const int VER_MINORVERSION = 0x0000001; // dwMinorVersion
public const int VER_PLATFORMID = 0x0000008; // dwPlatformId
public const int VER_SERVICEPACKMAJOR = 0x0000020; // wServicePackMajor
public const int VER_SERVICEPACKMINOR = 0x0000010; // wServicePackMinor
public const int VER_SUITENAME = 0x0000040; // wSuiteMask
public const int VER_PRODUCT_TYPE = 0x0000080; // dwProductType
public const int VER_EQUAL = 1; // The current value must be equal to the specified value.
public const int VER_GREATER = 2; // The current value must be greater than the specified value.
public const int VER_GREATER_EQUAL = 3; // The current value must be greater than or equal to the specified value.
public const int VER_LESS = 4; // The current value must be less than the specified value.
public const int VER_LESS_EQUAL = 5; // The current value must be less than or equal to the specified value.
public const int VER_AND = 6;
// All product suites specified in the wSuiteMask member must be present in the current system.
public const int VER_OR = 7; // At least one of the specified product suites must be present in the current system.
[StructLayout(LayoutKind.Sequential)]
public struct OSVERSIONINFOEX
{
public int OSVersionInfoSize;
public int MajorVersion;
public int MinorVersion;
public int BuildNumber;
public int PlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string CSDVersion;
public UInt16 ServicePackMajor;
public UInt16 ServicePackMinor;
public UInt16 SuiteMask;
public byte ProductType;
public byte Reserved;
}
// [DllImport("kernel32")]
// static extern bool GetVersionEx(ref OSVERSIONINFOEX versionInfo);
[DllImport("kernel32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool VerifyVersionInfo(ref OSVERSIONINFOEX versionInfo,
int typeMask,
ulong conditionMask);
[DllImport("kernel32")]
public static extern ulong VerSetConditionMask(ulong conditionMask, int typeBitMask, int operatorMask);
#region Native WiFi API
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WLAN_INTERFACE_INFO_LIST
{
public WLAN_INTERFACE_INFO_LIST(IntPtr pList)
{
NumberOfItems = Marshal.ReadInt32(pList, 0);
Index = Marshal.ReadInt32(pList, 4);
InterfaceInfo = new WLAN_INTERFACE_INFO[NumberOfItems];
for (int i = 0; i < NumberOfItems; i++)
{
IntPtr pItemList = new IntPtr(pList.ToInt32() + (i * 284));
WLAN_INTERFACE_INFO wii = new WLAN_INTERFACE_INFO();
byte[] intGuid = new byte[16];
for (int j = 0; j < 16; j++)
{
intGuid[j] = Marshal.ReadByte(pItemList, 8 + j);
}
wii.InterfaceGuid = new Guid(intGuid);
//wii.InterfacePtr = new IntPtr(pItemList.ToInt32() + 8);
wii.InterfaceDescription =
Marshal.PtrToStringUni(new IntPtr(pItemList.ToInt32() + 24), 256).Replace("\0", "");
wii.State = (WLAN_INTERFACE_STATE)Marshal.ReadInt32(pItemList, 280);
InterfaceInfo[i] = wii;
}
}
public int NumberOfItems; // Contains the number of items in the InterfaceInfo member.
public int Index; // The index of the current item. The index of the first item is 0.
[MarshalAs(UnmanagedType.ByValArray)]
public WLAN_INTERFACE_INFO[] InterfaceInfo;
// Pointer to an array of WLAN_INTERFACE_INFO structures containing interface information.
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WLAN_INTERFACE_INFO
{
public Guid InterfaceGuid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string InterfaceDescription;
public WLAN_INTERFACE_STATE State;
}
public enum WLAN_INTERFACE_STATE
{
wlan_interface_state_not_ready = 0,
wlan_interface_state_connected = 1,
wlan_interface_state_ad_hoc_network_formed = 2,
wlan_interface_state_disconnecting = 3,
wlan_interface_state_disconnected = 4,
wlan_interface_state_associating = 5,
wlan_interface_state_discovering = 6,
wlan_interface_state_authenticating = 7
}
[DllImport("wlanapi", SetLastError = true)]
public static extern uint WlanOpenHandle(
[In] uint dwClientVersion,
[In, Out] IntPtr pReserved,
[Out] out uint pdwNegotiatedVersion,
[Out] out uint phClientHandle);
[DllImport("wlanapi", SetLastError = true)]
public static extern uint WlanCloseHandle(
[In] uint hClientHandle,
[In] IntPtr pReserved);
[DllImport("wlanapi", SetLastError = true)]
public static extern uint WlanEnumInterfaces(
[In] uint hClientHandle,
[In] IntPtr pReserved,
[Out] out IntPtr ppInterfaceList);
[DllImport("wlanapi", SetLastError = true)]
public static extern void WlanFreeMemory([In] IntPtr pMemory);
#endregion
#region Windows Zero Configuration API
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct INTFS_KEY_TABLE
{
public uint dwNumIntfs;
[MarshalAs(UnmanagedType.ByValArray)]
public uint[] pIntfs;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct INTF_KEY_ENTRY
{
public string wszGuid;
}
[DllImport("wzcsapi.dll", SetLastError = true)]
public static extern int WZCEnumInterfaces(
[In] IntPtr pSvrAddr,
[Out] out INTFS_KEY_TABLE pIntfs);
#endregion
/// <summary>Enumeration of the different ways of showing a window using
/// ShowWindow</summary>
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow);
}
public enum WindowShowStyle : uint
{
/// <summary>Hides the window and activates another window.</summary>
/// <remarks>See SW_HIDE</remarks>
Hide = 0,
/// <summary>Activates and displays a window. If the window is minimized
/// or maximized, the system restores it to its original size and
/// position. An application should specify this flag when displaying
/// the window for the first time.</summary>
/// <remarks>See SW_SHOWNORMAL</remarks>
ShowNormal = 1,
/// <summary>Activates the window and displays it as a minimized window.</summary>
/// <remarks>See SW_SHOWMINIMIZED</remarks>
ShowMinimized = 2,
/// <summary>Activates the window and displays it as a maximized window.</summary>
/// <remarks>See SW_SHOWMAXIMIZED</remarks>
ShowMaximized = 3,
/// <summary>Maximizes the specified window.</summary>
/// <remarks>See SW_MAXIMIZE</remarks>
Maximize = 3,
/// <summary>Displays a window in its most recent size and position.
/// This value is similar to "ShowNormal", except the window is not
/// actived.</summary>
/// <remarks>See SW_SHOWNOACTIVATE</remarks>
ShowNormalNoActivate = 4,
/// <summary>Activates the window and displays it in its current size
/// and position.</summary>
/// <remarks>See SW_SHOW</remarks>
Show = 5,
/// <summary>Minimizes the specified window and activates the next
/// top-level window in the Z order.</summary>
/// <remarks>See SW_MINIMIZE</remarks>
Minimize = 6,
/// <summary>Displays the window as a minimized window. This value is
/// similar to "ShowMinimized", except the window is not activated.</summary>
/// <remarks>See SW_SHOWMINNOACTIVE</remarks>
ShowMinNoActivate = 7,
/// <summary>Displays the window in its current size and position. This
/// value is similar to "Show", except the window is not activated.</summary>
/// <remarks>See SW_SHOWNA</remarks>
ShowNoActivate = 8,
/// <summary>Activates and displays the window. If the window is
/// minimized or maximized, the system restores it to its original size
/// and position. An application should specify this flag when restoring
/// a minimized window.</summary>
/// <remarks>See SW_RESTORE</remarks>
Restore = 9,
/// <summary>Sets the show state based on the SW_ value specified in the
/// STARTUPINFO structure passed to the CreateProcess function by the
/// program that started the application.</summary>
/// <remarks>See SW_SHOWDEFAULT</remarks>
ShowDefault = 10,
/// <summary>Windows 2000/XP: Minimizes a window, even if the thread
/// that owns the window is hung. This flag should only be used when
/// minimizing windows from a different thread.</summary>
/// <remarks>See SW_FORCEMINIMIZE</remarks>
ForceMinimized = 11
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left, Top, Right, Bottom;
public RECT(int left, int top, int right, int bottom)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
public RECT(System.Drawing.Rectangle r)
: this(r.Left, r.Top, r.Right, r.Bottom)
{
}
public int X
{
get { return Left; }
set { Right -= (Left - value); Left = value; }
}
public int Y
{
get { return Top; }
set { Bottom -= (Top - value); Top = value; }
}
public int Width
{
get { return Right - Left; }
set { Right = value + Left; }
}
public int Height
{
get { return Bottom - Top; }
set { Bottom = value + Top; }
}
public Point Location
{
get { return new Point(Left, Top); }
set { X = value.X; Y = value.Y; }
}
public Size Size
{
get { return new Size(Width, Height); }
set { Width = value.Width; Height = value.Height; }
}
public static implicit operator Rectangle(RECT r)
{
return new Rectangle(r.Left, r.Top, r.Width, r.Height);
}
public static implicit operator RECT(Rectangle r)
{
return new RECT(r);
}
public static bool operator ==(RECT r1, RECT r2)
{
return r1.Equals(r2);
}
public static bool operator !=(RECT r1, RECT r2)
{
return !r1.Equals(r2);
}
public bool Equals(RECT r)
{
return r.Left == Left && r.Top == Top && r.Right == Right && r.Bottom == Bottom;
}
public override bool Equals(object obj)
{
if (obj is RECT)
{
return Equals((RECT)obj);
}
if (obj is Rectangle)
{
return Equals(new RECT((Rectangle)obj));
}
return false;
}
public override int GetHashCode()
{
return ((Rectangle)this).GetHashCode();
}
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.CurrentCulture, "{{Left={0},Top={1},Right={2},Bottom={3}}}", Left, Top, Right, Bottom);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct SIZE
{
public int Width;
public int Height;
public SIZE(int width, int height)
{
Width = width;
Height = height;
}
public static explicit operator Size(SIZE s)
{
return new Size(s.Width, s.Height);
}
public static explicit operator SIZE(Size s)
{
return new SIZE(s.Width, s.Height);
}
public override string ToString()
{
return string.Format("{0}x{1}", Width, Height);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
X = x;
Y = y;
}
public static explicit operator Point(POINT p)
{
return new Point(p.X, p.Y);
}
public static explicit operator POINT(Point p)
{
return new POINT(p.X, p.Y);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWINFO
{
public uint cbSize;
public RECT rcWindow;
public RECT rcClient;
public uint dwStyle;
public uint dwExStyle;
public uint dwWindowStatus;
public uint cxWindowBorders;
public uint cyWindowBorders;
public ushort atomWindowType;
public ushort wCreatorVersion;
public WINDOWINFO(Boolean? filler)
: this() // Allows automatic initialization of "cbSize" with "new WINDOWINFO(null/true/false)".
{
cbSize = (UInt32)(Marshal.SizeOf(typeof(WINDOWINFO)));
}
}
public struct WINDOWPLACEMENT
{
public int length;
public int flags;
public WindowShowStyle showCmd;
public POINT ptMinPosition;
public POINT ptMaxPosition;
public RECT rcNormalPosition;
}
public struct BLENDFUNCTION
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
}
[StructLayout(LayoutKind.Sequential)]
public struct APPBARDATA
{
public int cbSize;
public IntPtr hWnd;
public int uCallbackMessage;
public int uEdge;
public RECT rc;
public IntPtr lParam;
public static APPBARDATA NewAPPBARDATA()
{
APPBARDATA abd = new APPBARDATA();
abd.cbSize = Marshal.SizeOf(typeof(APPBARDATA));
return abd;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct DWM_BLURBEHIND
{
public DWM_BB dwFlags;
public bool fEnable;
public IntPtr hRgnBlur;
public bool fTransitionOnMaximized;
}
[Flags]
public enum DWM_BB : uint
{
ENABLE = 0x00000001,
BLURREGION = 0x00000002,
TRANSITIONONMAXIMIZED = 0x00000004,
}
[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
public int leftWidth;
public int rightWidth;
public int topHeight;
public int bottomHeight;
}
[StructLayout(LayoutKind.Sequential)]
public struct DWM_THUMBNAIL_PROPERTIES
{
public int dwFlags;
public RECT rcDestination;
public RECT rcSource;
public byte opacity;
public bool fVisible;
public bool fSourceClientAreaOnly;
}
[StructLayout(LayoutKind.Sequential)]
public struct CursorInfo
{
public Int32 cbSize; // Specifies the size, in bytes, of the structure.
public Int32 flags; // Specifies the cursor state. This parameter can be one of the following values:
public IntPtr hCursor; // Handle to the cursor.
public Point ptScreenPos; // A POINT structure that receives the screen coordinates of the cursor.
}
[StructLayout(LayoutKind.Sequential)]
public struct IconInfo
{
public bool fIcon; // Specifies whether this structure defines an icon or a cursor. A value of TRUE specifies
public Int32 xHotspot; // Specifies the x-coordinate of a cursor's hot spot. If this structure defines an icon, the hot
public Int32 yHotspot; // Specifies the y-coordinate of the cursor's hot spot. If this structure defines an icon, the hot
public IntPtr hbmMask; // (HBITMAP) Specifies the icon bitmask bitmap. If this structure defines a black and white icon,
public IntPtr hbmColor; // (HBITMAP) Handle to the icon color bitmap. This member can be optional if this
}
/// <summary>
/// Structure, which contains information for a single stream .
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
public struct AVISTREAMINFO
{
/// <summary>
/// Four-character code indicating the stream type.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int type;
/// <summary>
/// Four-character code of the compressor handler that will compress this video stream when it is saved.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int handler;
/// <summary>
/// Applicable flags for the stream.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int flags;
/// <summary>
/// Capability flags; currently unused.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int Capabilities;
/// <summary>
/// Priority of the stream.
/// </summary>
///
[MarshalAs(UnmanagedType.I2)]
public short priority;
/// <summary>
/// Language of the stream.
/// </summary>
///
[MarshalAs(UnmanagedType.I2)]
public short language;
/// <summary>
/// Time scale applicable for the stream.
/// </summary>
///
/// <remarks>Dividing <b>rate</b> by <b>scale</b> gives the playback rate in number of samples per second.</remarks>
///
[MarshalAs(UnmanagedType.I4)]
public int scale;
/// <summary>
/// Rate in an integer format.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int rate;
/// <summary>
/// Sample number of the first frame of the AVI file.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int start;
/// <summary>
/// Length of this stream.
/// </summary>
///
/// <remarks>The units are defined by <b>rate</b> and <b>scale</b>.</remarks>
///
[MarshalAs(UnmanagedType.I4)]
public int length;
/// <summary>
/// Audio skew. This member specifies how much to skew the audio data ahead of the video frames in interleaved files.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int initialFrames;
/// <summary>
/// Recommended buffer size, in bytes, for the stream.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int suggestedBufferSize;
/// <summary>
/// Quality indicator of the video data in the stream.
/// </summary>
///
/// <remarks>Quality is represented as a number between 0 and 10,000.</remarks>
///
[MarshalAs(UnmanagedType.I4)]
public int quality;
/// <summary>
/// Size, in bytes, of a single data sample.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int sampleSize;
/// <summary>
/// Dimensions of the video destination rectangle.
/// </summary>
///
[MarshalAs(UnmanagedType.Struct, SizeConst = 16)]
public RECT rectFrame;
/// <summary>
/// Number of times the stream has been edited.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int editCount;
/// <summary>
/// Number of times the stream format has changed.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int formatChangeCount;
/// <summary>
/// Description of the stream.
/// </summary>
///
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string name;
}
/// <summary>
/// Structure, which contains information about a stream and how it is compressed and saved.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct AVICOMPRESSOPTIONS
{
/// <summary>
/// Four-character code indicating the stream type.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int type;
/// <summary>
/// Four-character code for the compressor handler that will compress this video stream when it is saved.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int handler;
/// <summary>
/// Maximum period between video key frames.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int keyFrameEvery;
/// <summary>
/// Quality value passed to a video compressor.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int quality;
/// <summary>
/// Video compressor data rate.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int bytesPerSecond;
/// <summary>
/// Flags used for compression.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int flags;
/// <summary>
/// Pointer to a structure defining the data format.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int format;
/// <summary>
/// Size, in bytes, of the data referenced by <b>format</b>.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int formatSize;
/// <summary>
/// Video-compressor-specific data; used internally.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int parameters;
/// <summary>
/// Size, in bytes, of the data referenced by <b>parameters</b>.
/// </summary>
[MarshalAs(UnmanagedType.I4)]
public int parametersSize;
/// <summary>
/// Interleave factor for interspersing stream data with data from the first stream.
/// </summary>
///
[MarshalAs(UnmanagedType.I4)]
public int interleaveEvery;
}
public enum BitmapCompressionMode : uint
{
BI_RGB = 0,
BI_RLE8 = 1,
BI_RLE4 = 2,
BI_BITFIELDS = 3,
BI_JPEG = 4,
BI_PNG = 5
}
[StructLayout(LayoutKind.Sequential)]
public struct BITMAPINFOHEADER
{
public uint biSize;
public int biWidth;
public int biHeight;
public ushort biPlanes;
public ushort biBitCount;
public BitmapCompressionMode biCompression;
public uint biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public uint biClrUsed;
public uint biClrImportant;
public BITMAPINFOHEADER(int width, int height, ushort bitCount)
{
biSize = (uint)Marshal.SizeOf(typeof(BITMAPINFOHEADER));
biWidth = width;
biHeight = height;
biPlanes = 1;
biBitCount = bitCount;
biCompression = BitmapCompressionMode.BI_RGB;
biSizeImage = 0;
biXPelsPerMeter = 0;
biYPelsPerMeter = 0;
biClrUsed = 0;
biClrImportant = 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace OpenQA.Selenium
{
[TestFixture]
public class FormHandlingTests : DriverTestFixture
{
[Test]
public void ShouldClickOnSubmitInputElements()
{
driver.Url = formsPage;
driver.FindElement(By.Id("submitButton")).Click();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(500));
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ClickingOnUnclickableElementsDoesNothing()
{
driver.Url = formsPage;
driver.FindElement(By.XPath("//body")).Click();
}
[Test]
public void ShouldBeAbleToClickImageButtons()
{
driver.Url = formsPage;
driver.FindElement(By.Id("imageButton")).Click();
System.Threading.Thread.Sleep(500);
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldBeAbleToSubmitForms()
{
driver.Url = formsPage;
driver.FindElement(By.Name("login")).Submit();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(500));
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldSubmitAFormWhenAnyInputElementWithinThatFormIsSubmitted()
{
driver.Url = formsPage;
driver.FindElement(By.Id("checky")).Submit();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(500));
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldSubmitAFormWhenAnyElementWithinThatFormIsSubmitted()
{
driver.Url = formsPage;
driver.FindElement(By.XPath("//form/p")).Submit();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(500));
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToSubmitAFormThatDoesNotExist()
{
driver.Url = formsPage;
driver.FindElement(By.Name("there is no spoon")).Submit();
}
[Test]
public void ShouldBeAbleToEnterTextIntoATextAreaBySettingItsValue()
{
driver.Url = javascriptPage;
IWebElement textarea = driver.FindElement(By.Id("keyUpArea"));
String cheesey = "Brie and cheddar";
textarea.SendKeys(cheesey);
Assert.AreEqual(textarea.GetAttribute("value"), cheesey);
}
[Test]
public void ShouldSubmitAFormUsingTheNewlineLiteral()
{
driver.Url = formsPage;
IWebElement nestedForm = driver.FindElement(By.Id("nested_form"));
IWebElement input = nestedForm.FindElement(By.Name("x"));
input.SendKeys("\n");
// We are losing the race to get notified of a navigation in IE.
System.Threading.Thread.Sleep(500);
Assert.AreEqual("We Arrive Here", driver.Title);
Assert.IsTrue(driver.Url.EndsWith("?x=name"));
}
[Test]
public void ShouldSubmitAFormUsingTheEnterKey()
{
driver.Url = formsPage;
IWebElement nestedForm = driver.FindElement(By.Id("nested_form"));
IWebElement input = nestedForm.FindElement(By.Name("x"));
input.SendKeys(Keys.Enter);
// We are losing the race to get notified of a navigation in IE.
System.Threading.Thread.Sleep(500);
Assert.AreEqual("We Arrive Here", driver.Title);
Assert.IsTrue(driver.Url.EndsWith("?x=name"));
}
[Test]
public void ShouldEnterDataIntoFormFields()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']"));
String originalValue = element.GetAttribute("value");
Assert.AreEqual(originalValue, "change");
element.Clear();
element.SendKeys("some text");
element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']"));
String newFormValue = element.GetAttribute("value");
Assert.AreEqual(newFormValue, "some text");
}
[Test]
[IgnoreBrowser(Browser.Chrome, "ChromeDriver does not yet support file uploads")]
public void ShouldBeAbleToAlterTheContentsOfAFileUploadInputElement()
{
driver.Url = formsPage;
IWebElement uploadElement = driver.FindElement(By.Id("upload"));
Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value")));
System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt");
System.IO.StreamWriter inputFileWriter = inputFile.CreateText();
inputFileWriter.WriteLine("Hello world");
inputFileWriter.Close();
uploadElement.SendKeys(inputFile.FullName);
System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value"));
Assert.AreEqual(inputFile.Name, outputFile.Name);
inputFile.Delete();
}
[Test]
[IgnoreBrowser(Browser.Chrome, "ChromeDriver does not yet support file uploads")]
public void ShouldBeAbleToUploadTheSameFileTwice()
{
System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt");
System.IO.StreamWriter inputFileWriter = inputFile.CreateText();
inputFileWriter.WriteLine("Hello world");
inputFileWriter.Close();
driver.Url = formsPage;
IWebElement uploadElement = driver.FindElement(By.Id("upload"));
Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value")));
uploadElement.SendKeys(inputFile.FullName);
uploadElement.Submit();
driver.Url = formsPage;
uploadElement = driver.FindElement(By.Id("upload"));
Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value")));
uploadElement.SendKeys(inputFile.FullName);
uploadElement.Submit();
// If we get this far, then we're all good.
}
[Test]
public void SendingKeyboardEventsShouldAppendTextInInputs()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("working"));
element.SendKeys("Some");
String value = element.GetAttribute("value");
Assert.AreEqual(value, "Some");
element.SendKeys(" text");
value = element.GetAttribute("value");
Assert.AreEqual(value, "Some text");
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit, "Not implemented going to the end of the line first")]
[IgnoreBrowser(Browser.Chrome, "Not implemented going to the end of the line first")]
public void SendingKeyboardEventsShouldAppendTextInTextAreas()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("withText"));
element.SendKeys(". Some text");
String value = element.GetAttribute("value");
Assert.AreEqual(value, "Example text. Some text");
}
[Test]
public void ShouldBeAbleToClearTextFromInputElements()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("working"));
element.SendKeys("Some text");
String value = element.GetAttribute("value");
Assert.IsTrue(value.Length > 0);
element.Clear();
value = element.GetAttribute("value");
Assert.AreEqual(value.Length, 0);
}
[Test]
public void EmptyTextBoxesShouldReturnAnEmptyStringNotNull()
{
driver.Url = formsPage;
IWebElement emptyTextBox = driver.FindElement(By.Id("working"));
Assert.AreEqual(emptyTextBox.GetAttribute("value"), "");
IWebElement emptyTextArea = driver.FindElement(By.Id("emptyTextArea"));
Assert.AreEqual(emptyTextBox.GetAttribute("value"), "");
}
[Test]
public void ShouldBeAbleToClearTextFromTextAreas()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("withText"));
element.SendKeys("Some text");
String value = element.GetAttribute("value");
Assert.IsTrue(value.Length > 0);
element.Clear();
value = element.GetAttribute("value");
Assert.AreEqual(value.Length, 0);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal delegate BoundStatement GenerateMethodBody(EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals);
/// <summary>
/// Synthesized expression evaluation method.
/// </summary>
internal sealed class EEMethodSymbol : MethodSymbol
{
// We only create a single EE method (per EE type) that represents an arbitrary expression,
// whose lowering may produce synthesized members (lambdas, dynamic sites, etc).
// We may thus assume that the method ordinal is always 0.
//
// Consider making the implementation more flexible in order to avoid this assumption.
// In future we might need to compile multiple expression and then we'll need to assign
// a unique method ordinal to each of them to avoid duplicate synthesized member names.
private const int _methodOrdinal = 0;
internal readonly TypeMap TypeMap;
internal readonly MethodSymbol SubstitutedSourceMethod;
internal readonly ImmutableArray<LocalSymbol> Locals;
internal readonly ImmutableArray<LocalSymbol> LocalsForBinding;
private readonly EENamedTypeSymbol _container;
private readonly string _name;
private readonly ImmutableArray<Location> _locations;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly ImmutableArray<ParameterSymbol> _parameters;
private readonly ParameterSymbol _thisParameter;
private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables;
/// <summary>
/// Invoked at most once to generate the method body.
/// (If the compilation has no errors, it will be invoked
/// exactly once, otherwise it may be skipped.)
/// </summary>
private readonly GenerateMethodBody _generateMethodBody;
private TypeSymbol _lazyReturnType;
// NOTE: This is only used for asserts, so it could be conditional on DEBUG.
private readonly ImmutableArray<TypeParameterSymbol> _allTypeParameters;
internal EEMethodSymbol(
EENamedTypeSymbol container,
string name,
Location location,
MethodSymbol sourceMethod,
ImmutableArray<LocalSymbol> sourceLocals,
ImmutableArray<LocalSymbol> sourceLocalsForBinding,
ImmutableDictionary<string, DisplayClassVariable> sourceDisplayClassVariables,
GenerateMethodBody generateMethodBody)
{
Debug.Assert(sourceMethod.IsDefinition);
Debug.Assert(sourceMethod.ContainingSymbol == container.SubstitutedSourceType.OriginalDefinition);
Debug.Assert(sourceLocals.All(l => l.ContainingSymbol == sourceMethod));
_container = container;
_name = name;
_locations = ImmutableArray.Create(location);
// What we want is to map all original type parameters to the corresponding new type parameters
// (since the old ones have the wrong owners). Unfortunately, we have a circular dependency:
// 1) Each new type parameter requires the entire map in order to be able to construct its constraint list.
// 2) The map cannot be constructed until all new type parameters exist.
// Our solution is to pass each new type parameter a lazy reference to the type map. We then
// initialize the map as soon as the new type parameters are available - and before they are
// handed out - so that there is never a period where they can require the type map and find
// it uninitialized.
var sourceMethodTypeParameters = sourceMethod.TypeParameters;
var allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters);
var getTypeMap = new Func<TypeMap>(() => this.TypeMap);
_typeParameters = sourceMethodTypeParameters.SelectAsArray(
(tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap),
(object)null);
_allTypeParameters = container.TypeParameters.Concat(_typeParameters);
this.TypeMap = new TypeMap(allSourceTypeParameters, _allTypeParameters);
EENamedTypeSymbol.VerifyTypeParameters(this, _typeParameters);
var substitutedSourceType = container.SubstitutedSourceType;
this.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType);
if (sourceMethod.Arity > 0)
{
this.SubstitutedSourceMethod = this.SubstitutedSourceMethod.Construct(_typeParameters.As<TypeSymbol>());
}
TypeParameterChecker.Check(this.SubstitutedSourceMethod, _allTypeParameters);
// Create a map from original parameter to target parameter.
var parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance();
var substitutedSourceThisParameter = this.SubstitutedSourceMethod.ThisParameter;
var substitutedSourceHasThisParameter = (object)substitutedSourceThisParameter != null;
if (substitutedSourceHasThisParameter)
{
_thisParameter = MakeParameterSymbol(0, GeneratedNames.ThisProxyFieldName(), substitutedSourceThisParameter);
Debug.Assert(_thisParameter.Type == this.SubstitutedSourceMethod.ContainingType);
parameterBuilder.Add(_thisParameter);
}
var ordinalOffset = (substitutedSourceHasThisParameter ? 1 : 0);
foreach (var substitutedSourceParameter in this.SubstitutedSourceMethod.Parameters)
{
var ordinal = substitutedSourceParameter.Ordinal + ordinalOffset;
Debug.Assert(ordinal == parameterBuilder.Count);
var parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter);
parameterBuilder.Add(parameter);
}
_parameters = parameterBuilder.ToImmutableAndFree();
var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
var localsMap = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance();
foreach (var sourceLocal in sourceLocals)
{
var local = sourceLocal.ToOtherMethod(this, this.TypeMap);
localsMap.Add(sourceLocal, local);
localsBuilder.Add(local);
}
this.Locals = localsBuilder.ToImmutableAndFree();
localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var sourceLocal in sourceLocalsForBinding)
{
LocalSymbol local;
if (!localsMap.TryGetValue(sourceLocal, out local))
{
local = sourceLocal.ToOtherMethod(this, this.TypeMap);
localsMap.Add(sourceLocal, local);
}
localsBuilder.Add(local);
}
this.LocalsForBinding = localsBuilder.ToImmutableAndFree();
// Create a map from variable name to display class field.
var displayClassVariables = PooledDictionary<string, DisplayClassVariable>.GetInstance();
foreach (var pair in sourceDisplayClassVariables)
{
var variable = pair.Value;
var oldDisplayClassInstance = variable.DisplayClassInstance;
// Note: we don't call ToOtherMethod in the local case because doing so would produce
// a new LocalSymbol that would not be ReferenceEquals to the one in this.LocalsForBinding.
var oldDisplayClassInstanceFromLocal = oldDisplayClassInstance as DisplayClassInstanceFromLocal;
var newDisplayClassInstance = (oldDisplayClassInstanceFromLocal == null) ?
oldDisplayClassInstance.ToOtherMethod(this, this.TypeMap) :
new DisplayClassInstanceFromLocal((EELocalSymbol)localsMap[oldDisplayClassInstanceFromLocal.Local]);
variable = variable.SubstituteFields(newDisplayClassInstance, this.TypeMap);
displayClassVariables.Add(pair.Key, variable);
}
_displayClassVariables = displayClassVariables.ToImmutableDictionary();
displayClassVariables.Free();
localsMap.Free();
_generateMethodBody = generateMethodBody;
}
private ParameterSymbol MakeParameterSymbol(int ordinal, string name, ParameterSymbol sourceParameter)
{
return new SynthesizedParameterSymbol(this, sourceParameter.Type, ordinal, sourceParameter.RefKind, name, sourceParameter.CustomModifiers, sourceParameter.CountOfCustomModifiersPrecedingByRef);
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataFinal
{
get { return false; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override string Name
{
get { return _name; }
}
public override int Arity
{
get { return _typeParameters.Length; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
internal override bool HasSpecialName
{
get { return true; }
}
internal override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get { return default(System.Reflection.MethodImplAttributes); }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
public override DllImportData GetDllImportData()
{
return null;
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { return null; }
}
internal override bool RequiresSecurityObject
{
get { return false; }
}
internal override bool TryGetThisParameter(out ParameterSymbol thisParameter)
{
thisParameter = null;
return true;
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsVararg
{
get { return this.SubstitutedSourceMethod.IsVararg; }
}
internal override RefKind RefKind
{
get { return this.SubstitutedSourceMethod.RefKind; }
}
public override bool ReturnsVoid
{
get { return this.ReturnType.SpecialType == SpecialType.System_Void; }
}
public override bool IsAsync
{
get { return false; }
}
public override TypeSymbol ReturnType
{
get
{
if (_lazyReturnType == null)
{
throw new InvalidOperationException();
}
return _lazyReturnType;
}
}
public override ImmutableArray<TypeSymbol> TypeArguments
{
get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _parameters; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
internal override ushort CountOfCustomModifiersPrecedingByRef
{
get { return 0; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override Cci.CallingConvention CallingConvention
{
get
{
Debug.Assert(this.IsStatic);
var cc = Cci.CallingConvention.Default;
if (this.IsVararg)
{
cc |= Cci.CallingConvention.ExtraArguments;
}
if (this.IsGenericMethod)
{
cc |= Cci.CallingConvention.Generic;
}
return cc;
}
}
internal override bool GenerateDebugInfo
{
get { return false; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override ImmutableArray<Location> Locations
{
get { return _locations; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { throw ExceptionUtilities.Unreachable; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Internal; }
}
public override bool IsStatic
{
get { return true; }
}
public override bool IsVirtual
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, DiagnosticBag diagnostics)
{
ImmutableArray<LocalSymbol> declaredLocalsArray;
var body = _generateMethodBody(this, diagnostics, out declaredLocalsArray);
var compilation = compilationState.Compilation;
_lazyReturnType = CalculateReturnType(compilation, body);
// Can't do this until the return type has been computed.
TypeParameterChecker.Check(this, _allTypeParameters);
if (diagnostics.HasAnyErrors())
{
return;
}
DiagnosticsPass.IssueDiagnostics(compilation, body, diagnostics, this);
if (diagnostics.HasAnyErrors())
{
return;
}
// Check for use-site diagnostics (e.g. missing types in the signature).
DiagnosticInfo useSiteDiagnosticInfo = null;
this.CalculateUseSiteDiagnostic(ref useSiteDiagnosticInfo);
if (useSiteDiagnosticInfo != null && useSiteDiagnosticInfo.Severity == DiagnosticSeverity.Error)
{
diagnostics.Add(useSiteDiagnosticInfo, this.Locations[0]);
return;
}
try
{
var declaredLocals = PooledHashSet<LocalSymbol>.GetInstance();
try
{
// Rewrite local declaration statement.
body = (BoundStatement)LocalDeclarationRewriter.Rewrite(compilation, _container, declaredLocals, body, declaredLocalsArray);
// Verify local declaration names.
foreach (var local in declaredLocals)
{
Debug.Assert(local.Locations.Length > 0);
var name = local.Name;
if (name.StartsWith("$", StringComparison.Ordinal))
{
diagnostics.Add(ErrorCode.ERR_UnexpectedCharacter, local.Locations[0], name[0]);
return;
}
}
// Rewrite references to placeholder "locals".
body = (BoundStatement)PlaceholderLocalRewriter.Rewrite(compilation, _container, declaredLocals, body, diagnostics);
if (diagnostics.HasAnyErrors())
{
return;
}
}
finally
{
declaredLocals.Free();
}
var syntax = body.Syntax;
var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance();
statementsBuilder.Add(body);
// Insert an implicit return statement if necessary.
if (body.Kind != BoundKind.ReturnStatement)
{
statementsBuilder.Add(new BoundReturnStatement(syntax, RefKind.None, expressionOpt: null));
}
var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
var localsSet = PooledHashSet<LocalSymbol>.GetInstance();
foreach (var local in this.LocalsForBinding)
{
Debug.Assert(!localsSet.Contains(local));
localsBuilder.Add(local);
localsSet.Add(local);
}
foreach (var local in this.Locals)
{
if (!localsSet.Contains(local))
{
Debug.Assert(!localsSet.Contains(local));
localsBuilder.Add(local);
localsSet.Add(local);
}
}
localsSet.Free();
body = new BoundBlock(syntax, localsBuilder.ToImmutableAndFree(), statementsBuilder.ToImmutableAndFree()) { WasCompilerGenerated = true };
Debug.Assert(!diagnostics.HasAnyErrors());
Debug.Assert(!body.HasErrors);
bool sawLambdas;
bool sawLocalFunctions;
bool sawAwaitInExceptionHandler;
ImmutableArray<SourceSpan> dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty;
body = LocalRewriter.Rewrite(
compilation: this.DeclaringCompilation,
method: this,
methodOrdinal: _methodOrdinal,
containingType: _container,
statement: body,
compilationState: compilationState,
previousSubmissionFields: null,
allowOmissionOfConditionalCalls: false,
instrumentForDynamicAnalysis: false,
debugDocumentProvider: null,
dynamicAnalysisSpans: ref dynamicAnalysisSpans,
diagnostics: diagnostics,
sawLambdas: out sawLambdas,
sawLocalFunctions: out sawLocalFunctions,
sawAwaitInExceptionHandler: out sawAwaitInExceptionHandler);
Debug.Assert(!sawAwaitInExceptionHandler);
Debug.Assert(dynamicAnalysisSpans.Length == 0);
if (body.HasErrors)
{
return;
}
// Variables may have been captured by lambdas in the original method
// or in the expression, and we need to preserve the existing values of
// those variables in the expression. This requires rewriting the variables
// in the expression based on the closure classes from both the original
// method and the expression, and generating a preamble that copies
// values into the expression closure classes.
//
// Consider the original method:
// static void M()
// {
// int x, y, z;
// ...
// F(() => x + y);
// }
// and the expression in the EE: "F(() => x + z)".
//
// The expression is first rewritten using the closure class and local <1>
// from the original method: F(() => <1>.x + z)
// Then lambda rewriting introduces a new closure class that includes
// the locals <1> and z, and a corresponding local <2>: F(() => <2>.<1>.x + <2>.z)
// And a preamble is added to initialize the fields of <2>:
// <2> = new <>c__DisplayClass0();
// <2>.<1> = <1>;
// <2>.z = z;
// Rewrite "this" and "base" references to parameter in this method.
// Rewrite variables within body to reference existing display classes.
body = (BoundStatement)CapturedVariableRewriter.Rewrite(
this.SubstitutedSourceMethod.IsStatic ? null : _parameters[0],
compilation.Conversions,
_displayClassVariables,
body,
diagnostics);
if (body.HasErrors)
{
Debug.Assert(false, "Please add a test case capturing whatever caused this assert.");
return;
}
if (diagnostics.HasAnyErrors())
{
return;
}
if (sawLambdas || sawLocalFunctions)
{
var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance();
var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance();
body = LambdaRewriter.Rewrite(
loweredBody: body,
thisType: this.SubstitutedSourceMethod.ContainingType,
thisParameter: _thisParameter,
method: this,
methodOrdinal: _methodOrdinal,
substitutedSourceMethod: this.SubstitutedSourceMethod.OriginalDefinition,
closureDebugInfoBuilder: closureDebugInfoBuilder,
lambdaDebugInfoBuilder: lambdaDebugInfoBuilder,
slotAllocatorOpt: null,
compilationState: compilationState,
diagnostics: diagnostics,
assignLocals: true);
// we don't need this information:
closureDebugInfoBuilder.Free();
lambdaDebugInfoBuilder.Free();
}
// Insert locals from the original method,
// followed by any new locals.
var block = (BoundBlock)body;
var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var local in this.Locals)
{
Debug.Assert(!(local is EELocalSymbol) || (((EELocalSymbol)local).Ordinal == localBuilder.Count));
localBuilder.Add(local);
}
foreach (var local in block.Locals)
{
var oldLocal = local as EELocalSymbol;
if (oldLocal != null)
{
Debug.Assert(localBuilder[oldLocal.Ordinal] == oldLocal);
continue;
}
localBuilder.Add(local);
}
body = block.Update(localBuilder.ToImmutableAndFree(), block.LocalFunctions, block.Statements);
TypeParameterChecker.Check(body, _allTypeParameters);
compilationState.AddSynthesizedMethod(this, body);
}
catch (BoundTreeVisitor.CancelledByStackGuardException ex)
{
ex.AddAnError(diagnostics);
}
}
private static TypeSymbol CalculateReturnType(CSharpCompilation compilation, BoundStatement bodyOpt)
{
if (bodyOpt == null)
{
// If the method doesn't do anything, then it doesn't return anything.
return compilation.GetSpecialType(SpecialType.System_Void);
}
switch (bodyOpt.Kind)
{
case BoundKind.ReturnStatement:
return ((BoundReturnStatement)bodyOpt).ExpressionOpt.Type;
case BoundKind.ExpressionStatement:
case BoundKind.LocalDeclaration:
case BoundKind.MultipleLocalDeclarations:
case BoundKind.LocalDeconstructionDeclaration:
return compilation.GetSpecialType(SpecialType.System_Void);
default:
throw ExceptionUtilities.UnexpectedValue(bodyOpt.Kind);
}
}
internal override void AddSynthesizedReturnTypeAttributes(ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedReturnTypeAttributes(ref attributes);
var compilation = this.DeclaringCompilation;
var returnType = this.ReturnType;
if (returnType.ContainsDynamic() && compilation.HasDynamicEmitAttributes())
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(returnType, ReturnTypeCustomModifiers.Length));
}
if (returnType.ContainsTupleNames() && compilation.HasTupleNamesAttributes)
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(returnType));
}
}
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
return localPosition;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin.WebSocket.Extensions;
using Owin.WebSocket.Handlers;
namespace Owin.WebSocket
{
public abstract class WebSocketConnection
{
private readonly CancellationTokenSource mCancellToken;
private IWebSocket mWebSocket;
/// <summary>
/// Owin context for the web socket
/// </summary>
public IOwinContext Context { get; private set; }
/// <summary>
/// Maximum message size in bytes for the receive buffer
/// </summary>
public int MaxMessageSize { get; private set; }
/// <summary>
/// Arguments captured from URI using Regex
/// </summary>
public Dictionary<string, string> Arguments { get; private set; }
/// <summary>
/// Queue of send operations to the client
/// </summary>
public TaskQueue QueueSend { get { return mWebSocket.SendQueue;} }
protected WebSocketConnection(int maxMessageSize = 1024*64)
{
mCancellToken = new CancellationTokenSource();
MaxMessageSize = maxMessageSize;
}
/// <summary>
/// Closes the websocket connection
/// </summary>
public Task Close(WebSocketCloseStatus status, string reason)
{
return mWebSocket.Close(status, reason, CancellationToken.None);
}
/// <summary>
/// Aborts the websocket connection
/// </summary>
public void Abort()
{
mCancellToken.Cancel();
}
/// <summary>
/// Sends data to the client with binary message type
/// </summary>
/// <param name="buffer">Data to send</param>
/// <param name="endOfMessage">End of the message?</param>
/// <returns>Task to send the data</returns>
public Task SendBinary(byte[] buffer, bool endOfMessage)
{
return SendBinary(new ArraySegment<byte>(buffer), endOfMessage);
}
/// <summary>
/// Sends data to the client with binary message type
/// </summary>
/// <param name="buffer">Data to send</param>
/// <param name="endOfMessage">End of the message?</param>
/// <returns>Task to send the data</returns>
public Task SendBinary(ArraySegment<byte> buffer, bool endOfMessage)
{
return mWebSocket.SendBinary(buffer, endOfMessage, mCancellToken.Token);
}
/// <summary>
/// Sends data to the client with the text message type
/// </summary>
/// <param name="buffer">Data to send</param>
/// <param name="endOfMessage">End of the message?</param>
/// <returns>Task to send the data</returns>
public Task SendText(byte[] buffer, bool endOfMessage)
{
return SendText(new ArraySegment<byte>(buffer), endOfMessage);
}
/// <summary>
/// Sends data to the client with the text message type
/// </summary>
/// <param name="buffer">Data to send</param>
/// <param name="endOfMessage">End of the message?</param>
/// <returns>Task to send the data</returns>
public Task SendText(ArraySegment<byte> buffer, bool endOfMessage)
{
return mWebSocket.SendText(buffer, endOfMessage, mCancellToken.Token);
}
/// <summary>
/// Sends data to the client
/// </summary>
/// <param name="buffer">Data to send</param>
/// <param name="endOfMessage">End of the message?</param>
/// <param name="type">Message type of the data</param>
/// <returns>Task to send the data</returns>
public Task Send(ArraySegment<byte> buffer, bool endOfMessage, WebSocketMessageType type)
{
return mWebSocket.Send(buffer, type, endOfMessage, mCancellToken.Token);
}
/// <summary>
/// Verify the request
/// </summary>
/// <param name="request">Websocket request</param>
/// <returns>True if the request is authenticated else false to throw unauthenticated and deny the connection</returns>
public virtual bool AuthenticateRequest(IOwinRequest request)
{
return true;
}
/// <summary>
/// Verify the request asynchronously. Fires after AuthenticateRequest
/// </summary>
/// <param name="request">Websocket request</param>
/// <returns>True if the request is authenticated else false to throw unauthenticated and deny the connection</returns>
public virtual Task<bool> AuthenticateRequestAsync(IOwinRequest request)
{
return Task.FromResult(true);
}
/// <summary>
/// Fires after the websocket has been opened with the client
/// </summary>
public virtual void OnOpen()
{
}
/// <summary>
/// Fires after the websocket has been opened with the client and after OnOpen
/// </summary>
public virtual Task OnOpenAsync()
{
return Task.Delay(0);
}
/// <summary>
/// Fires when data is received from the client
/// </summary>
/// <param name="message">Data that was received</param>
/// <param name="type">Message type of the data</param>
public virtual Task OnMessageReceived(ArraySegment<byte> message, WebSocketMessageType type)
{
return Task.Delay(0);
}
/// <summary>
/// Fires with the connection with the client has closed
/// </summary>
public virtual void OnClose(WebSocketCloseStatus? closeStatus, string closeStatusDescription)
{
}
/// <summary>
/// Fires with the connection with the client has closed and after OnClose
/// </summary>
public virtual Task OnCloseAsync(WebSocketCloseStatus? closeStatus, string closeStatusDescription)
{
return Task.Delay(0);
}
/// <summary>
/// Fires when an exception occurs in the message reading loop
/// </summary>
/// <param name="error">Error that occured</param>
public virtual void OnReceiveError(Exception error)
{
}
/// <summary>
/// Receive one entire message from the web socket
/// </summary>
internal async Task AcceptSocketAsync(IOwinContext context, IDictionary<string, string> argumentMatches)
{
var accept = context.Get<Action<IDictionary<string, object>, Func<IDictionary<string, object>, Task>>>("websocket.Accept");
if (accept == null)
{
// Bad Request
context.Response.StatusCode = 400;
context.Response.Write("Not a valid websocket request");
return;
}
Arguments = new Dictionary<string, string>(argumentMatches);
var responseBuffering = context.Environment.Get<Action>("server.DisableResponseBuffering");
if (responseBuffering != null)
responseBuffering();
var responseCompression = context.Environment.Get<Action>("systemweb.DisableResponseCompression");
if (responseCompression != null)
responseCompression();
context.Response.Headers.Set("X-Content-Type-Options", "nosniff");
Context = context;
if (AuthenticateRequest(context.Request))
{
var authorized = await AuthenticateRequestAsync(context.Request);
if (authorized)
{
//user was authorized so accept the socket
accept(null, RunWebSocket);
return;
}
}
//see if user was forbidden or unauthorized from previous authenticate request failure
if (context.Request.User != null && context.Request.User.Identity.IsAuthenticated)
{
context.Response.StatusCode = 403;
}
else
{
context.Response.StatusCode = 401;
}
}
private async Task RunWebSocket(IDictionary<string, object> websocketContext)
{
object value;
if (websocketContext.TryGetValue(typeof (WebSocketContext).FullName, out value))
{
mWebSocket = new NetWebSocket(((WebSocketContext) value).WebSocket);
}
else
{
mWebSocket = new OwinWebSocket(websocketContext);
}
OnOpen();
await OnOpenAsync();
var buffer = new byte[MaxMessageSize];
Tuple<ArraySegment<byte>, WebSocketMessageType> received = null;
do
{
try
{
received = await mWebSocket.ReceiveMessage(buffer, mCancellToken.Token);
if (received.Item1.Count > 0)
await OnMessageReceived(received.Item1, received.Item2);
}
catch (TaskCanceledException)
{
break;
}
catch (OperationCanceledException oce)
{
if (!mCancellToken.IsCancellationRequested)
{
OnReceiveError(oce);
}
break;
}
catch (ObjectDisposedException)
{
break;
}
catch (Exception ex)
{
if (IsFatalSocketException(ex))
{
OnReceiveError(ex);
}
break;
}
}
while (received.Item2 != WebSocketMessageType.Close);
try
{
await mWebSocket.Close(WebSocketCloseStatus.NormalClosure, string.Empty, mCancellToken.Token);
}
catch
{ //Ignore
}
if(!mCancellToken.IsCancellationRequested)
mCancellToken.Cancel();
OnClose(mWebSocket.CloseStatus, mWebSocket.CloseStatusDescription);
await OnCloseAsync(mWebSocket.CloseStatus, mWebSocket.CloseStatusDescription);
}
internal static bool IsFatalSocketException(Exception ex)
{
// If this exception is due to the underlying TCP connection going away, treat as a normal close
// rather than a fatal exception.
var ce = ex as COMException;
if (ce != null)
{
switch ((uint)ce.ErrorCode)
{
case 0x800703e3:
case 0x800704cd:
case 0x80070026:
return false;
}
}
// unknown exception; treat as fatal
return true;
}
}
}
| |
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using MeshEngine.Controller;
namespace MeshEngine {
public static class Settings {
public enum ToggleType {
Snap,
TracingMode,
CustomPointerLocation,
AlignmentTools,
}
public static string filePath = @"settings.json";
public static string skybox;
public delegate void SettingsChanged();
public static event SettingsChanged OnSettingsChanged;
public static float rotationSnapIncrements = 15f; // FIXME: not persisted yet
public static float snapIncrements = 0.025f;
public static Vector3 customPointerPosition;
public static Vector3 customPointerRotation;
public static Color fillColor;
private static Dictionary<ToggleType, bool> toggle;
private static bool loaded;
private static bool hasInitialized;
public static void SetSkybox(string name) {
Initialize();
skybox = name;
Save();
UpdateSkybox();
if (OnSettingsChanged != null) OnSettingsChanged();
}
public static void SetToggle(ToggleType toggleType, bool value) {
Initialize();
if (toggle.ContainsKey(toggleType)) toggle[toggleType] = value;
else toggle.Add(toggleType, value);
if (OnSettingsChanged != null) OnSettingsChanged();
}
public static bool GetToggle(ToggleType toggleType) {
Initialize();
if (toggle.ContainsKey(toggleType)) return toggle[toggleType];
else return false;
}
public static bool SnapEnabled() {
Initialize();
return GetToggle(ToggleType.Snap) && snapIncrements != 0;
}
public static void SetSnap(bool value) {
Initialize();
SetToggle(ToggleType.Snap, value);
Save();
}
public static bool AlignmentToolsEnabled() {
Initialize();
return GetToggle(ToggleType.AlignmentTools);
}
public static void SetAlignmentTools(bool value) {
Initialize();
SetToggle(ToggleType.AlignmentTools, value);
Save();
}
public static void SetSnapIncrements(float value) {
Initialize();
snapIncrements = value;
if (OnSettingsChanged != null) OnSettingsChanged();
Save();
}
public static void SetTracingMode(bool value) {
Initialize();
SetToggle(ToggleType.TracingMode, value);
Save();
}
public static bool TracingMode() {
Initialize();
return GetToggle(ToggleType.TracingMode);
}
public static void SetCustomPointerLocation(bool value) {
Initialize();
SetToggle(ToggleType.CustomPointerLocation, value);
Save();
}
public static bool CustomPointerLocation() {
Initialize();
return GetToggle(ToggleType.CustomPointerLocation);
}
public static void SetCustomPointerPosition(Vector3 position) {
Initialize();
customPointerPosition = position;
if (OnSettingsChanged != null) OnSettingsChanged();
Save();
}
public static void SetCustomPointerRotation(Vector3 rotation) {
Initialize();
customPointerRotation = rotation;
if (OnSettingsChanged != null) OnSettingsChanged();
Save();
}
public static void SetFillColor(Color color) {
Initialize();
fillColor = color;
if (OnSettingsChanged != null) OnSettingsChanged();
Save();
}
public static void UpdateSkybox() {
Initialize();
}
private static JSONObject Vector3ToJSONObject(Vector3 position) {
JSONObject j = new JSONObject(JSONObject.Type.OBJECT);
j.AddField("x", position.x);
j.AddField("y", position.y);
j.AddField("z", position.z);
return j;
}
private static Vector3 JSONObjectToVector3(JSONObject j) {
Vector3 position = new Vector3(j["x"].n, j["y"].n, j["z"].n);
return position;
}
public static void Save() {
if (!loaded) return;
JSONObject j = new JSONObject(JSONObject.Type.OBJECT);
j.AddField("skybox", skybox);
j.AddField("snap", GetToggle(ToggleType.Snap));
j.AddField("snapIncrements", snapIncrements);
j.AddField("alignmentTools", GetToggle(ToggleType.AlignmentTools));
j.AddField("tracingMode", GetToggle(ToggleType.TracingMode));
j.AddField("customPointerLocation", GetToggle(ToggleType.TracingMode));
j.AddField("customPointerPosition", Vector3ToJSONObject(customPointerPosition));
j.AddField("customPointerRotation", Vector3ToJSONObject(customPointerRotation));
j.AddField("fillColor", "#" + ColorUtility.ToHtmlStringRGBA(fillColor));
string encodedString = j.ToString();
File.WriteAllText(filePath, encodedString);
}
public static void Load() {
if (!File.Exists(filePath)) {
skybox = "space";
SetToggle(ToggleType.TracingMode, false);
SetToggle(ToggleType.CustomPointerLocation, false);
customPointerPosition = new Vector3(0, 0, 0);
customPointerRotation = new Vector3(0, 0, 0);
fillColor = Color.red;
return;
}
string contents = File.ReadAllText(filePath);
JSONObject obj = new JSONObject(contents);
if (obj["skybox"]) SetSkybox(obj["skybox"].str);
if (obj["snap"]) SetToggle(ToggleType.Snap, obj["snap"].b);
if (obj["snapIncrements"]) SetSnapIncrements(obj["snapIncrements"].n);
if (obj["alignmentTools"]) SetToggle(ToggleType.AlignmentTools, obj["alignmentTools"].b);
if (obj["tracingMode"]) SetToggle(ToggleType.TracingMode, obj["tracingMode"].b);
if (obj["customPointerLocation"]) SetToggle(ToggleType.CustomPointerLocation, obj["customPointerLocation"].b);
if (obj["customPointerPosition"]) SetCustomPointerPosition(JSONObjectToVector3(obj["customPointerPosition"]));
if (obj["customPointerRotation"]) SetCustomPointerRotation(JSONObjectToVector3(obj["customPointerRotation"]));
if (obj["fillColor"]) {
Color outColor;
Debug.Log("fillColor from file=" + obj["fillColor"].str);
ColorUtility.TryParseHtmlString(obj["fillColor"].str, out outColor);
SetFillColor(outColor);
}
}
// Use this for initialization
private static void Initialize() {
if (hasInitialized) return;
hasInitialized = true;
toggle = new Dictionary<ToggleType, bool>();
loaded = false;
skybox = "space";
fillColor = Color.red;
Load();
loaded = true;
SetToggle(ToggleType.Snap, false);
SetToggle(ToggleType.AlignmentTools, true);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
namespace WpfApplication1.Coversion
{
public class PrayTimes
{
#region Static Fields and Constants
private MethodName calcMethod;
public double elv;
public string invalidTime = "-----";
public double jDate;
//----------------------- Local Variables ---------------------
public double lat;
public double lng;
public double numIterations = 1;
public string timeFormat = "24h";
public string[] timeSuffixes =
{
"am", "pm"
};
// coordinates
public double timeZone;
#endregion
#region Constructors
// time variables
//------------------------ Constants --------------------------
public PrayTimes(MethodName method = MethodName.MWL)
{
// Time Names
this.timeNames = new[]
{
TimeName.Imsak, TimeName.Fajr, TimeName.Sunrise, TimeName.Dhuhr, TimeName.Asr, TimeName.Sunset, TimeName.Maghrib, TimeName.Isha,
TimeName.Midnight
};
// Calculation Methods
this.methods = new Dictionary<MethodName, Method>
{
{
MethodName.MWL, new Method
{
name = "Muslim World League",
_params = new Dictionary<TimeName, object>
{
{
TimeName.Fajr, 18
},
{
TimeName.Isha, 17
}
}
}
},
{
MethodName.ISNA, new Method
{
name = "Islamic Society of North America (ISNA)",
_params = new Dictionary<TimeName, object>
{
{
TimeName.Fajr, 15
},
{
TimeName.Isha, 15
}
}
}
},
{
MethodName.Egypt, new Method
{
name = "Egyptian General Authority of Survey",
_params = new Dictionary<TimeName, object>
{
{
TimeName.Fajr, 19.5
},
{
TimeName.Isha, 17.5
}
}
}
},
{
MethodName.Makkah, new Method
{
name = "Umm Al-Qura University, Makkah",
_params = new Dictionary<TimeName, object>
{
{
TimeName.Fajr, 18.5
},
{
TimeName.Isha, "90 min"
}
}
}
}, // fajr was 19 degrees before 1430 hijri
{
MethodName.Karachi, new Method
{
name = "University of Islamic Sciences, Karachi",
_params = new Dictionary<TimeName, object>
{
{
TimeName.Fajr, 18
},
{
TimeName.Isha, 18
}
}
}
},
{
MethodName.Tehran, new Method
{
name = "Institute of Geophysics, University of Tehran",
_params = new Dictionary<TimeName, object>
{
{
TimeName.Fajr, 17.7
},
{
TimeName.Isha, 14
},
{
TimeName.Maghrib, 4.5
},
{
TimeName.Midnight, "Jafari"
}
}
}
},
// isha is not explicitly specified in this method
{
MethodName.Jafari, new Method
{
name = "Shia Ithna-Ashari, Leva Institute, Qum",
_params = new Dictionary<TimeName, object>
{
{
TimeName.Fajr, 16
},
{
TimeName.Isha, 14
},
{
TimeName.Maghrib, 4
},
{
TimeName.Midnight, "Jafari"
}
}
}
}
};
// Default Parameters in Calculation Methods
this.defaultParams = new Dictionary<TimeName, object>
{
{
TimeName.Maghrib, "0 min"
},
{
TimeName.Midnight, "Standard"
}
};
//----------------------- Parameter Values ----------------------
/*
// Asr Juristic Methods
asrJuristics = [
"Standard", // Shafi`i, Maliki, Ja`fari, Hanbali
"Hanafi" // Hanafi
],
// Midnight Mode
midnightMethods = [
"Standard", // Mid Sunset to Sunrise
"Jafari" // Mid Sunset to Fajr
],
// Adjust Methods for Higher Latitudes
highLatMethods = [
"NightMiddle", // middle of night
"AngleBased", // angle/60th of night
"OneSeventh", // 1/7th of night
"None" // No adjustment
],
// Time Formats
timeFormats = [
"24h", // 24-hour format
"12h", // 12-hour format
"12hNS", // 12-hour format with no suffix
"Float" // floating point number
],
*/
//---------------------- Default Settings --------------------
// do not change anything here; use adjust method instead
this.setting = new Dictionary<TimeName, object>
{
{
TimeName.Imsak, "10 min"
},
{
TimeName.Dhuhr, "0 min"
},
{
TimeName.Asr, AsrMethod.Standard
},
{
TimeName.HighLats, "NightMiddle"
}
};
//---------------------- Initialization -----------------------
// set methods defaults
foreach (var method1 in this.methods)
{
var _paramss = method1.Value._params;
var defParams = this.defaultParams.Where(p => !_paramss.ContainsKey(p.Key));
foreach (var keyValuePair in defParams)
{
_paramss.Add(keyValuePair.Key, keyValuePair.Value);
}
}
// initialize settings
var _params = this.methods[method]._params;
foreach (var param in _params)
{
this.setting.Add(param.Key, param.Value);
}
// init time offsets
this.offset = this.timeNames.ToDictionary(i => i, i => 0.0);
}
#endregion
#region Public Properties and Indexers
//--------------------------- Mine ----------------------------
public TimeName[] timeNames { get; set; }
public Dictionary<MethodName, Method> methods { get; set; }
public Dictionary<TimeName, object> defaultParams { get; set; }
public Dictionary<TimeName, object> setting { get; set; }
public Dictionary<TimeName, double> offset { get; set; }
public MethodName CalcMethod
{
get
{
return this.calcMethod;
}
set
{
if (this.calcMethod == value) return;
this.adjust(this.methods[value]._params);
this.calcMethod = value;
}
}
#endregion
// set calculation method
public void setMethod(MethodName method)
{
if (this.methods.ContainsKey(method))
{
this.calcMethod = method;
}
}
// set calculating parameters
public void adjust(Dictionary<TimeName, object> paramss)
{
foreach (var id in paramss)
{
this.setting[id.Key] = id.Value;
}
}
// set time offsets
public void tune(double[] timeOffsets)
{
for (int i = 0; i < timeOffsets.Length; i++)
{
var element = this.offset.ElementAt(i);
this.offset[element.Key] = timeOffsets[i];
}
}
// get current calculation method
public MethodName getMethod()
{
return this.calcMethod;
}
// get current setting
public Dictionary<TimeName, object> getSetting()
{
return this.setting;
}
// get current time offsets
public Dictionary<TimeName, double> getOffsets()
{
return this.offset;
}
// get default calc parametrs
public Dictionary<MethodName, Method> getDefaults()
{
return this.methods;
}
// return prayer times foreach a given date
public Dictionary<TimeName, double> getTimes(DateTime date, GeoCoordinate coords, double? timezone = null, double? dst = null, string format = null)
{
this.lat = 1 * coords.Latitude;
this.lng = 1 * coords.Longitude;
this.elv = 1 * coords.Elevation ?? 0;
this.timeFormat = !string.IsNullOrEmpty(format) ? format : this.timeFormat;
if (!timezone.HasValue) timezone = this.getTimeZone(date);
if (!dst.HasValue) dst = this.getDst(date);
this.timeZone = 1.0 * timezone.Value + 1.0 * dst.Value;
this.jDate = this.julian(date.Year, date.Month, date.Day) - this.lng / (15 * 24);
return this.computeTimes();
}
// convert float time to the given format (see timeFormats)
public string getFormattedTime(double time, string format, string[] suffixes = null)
{
if (double.IsNaN(time)) throw new Exception(this.invalidTime);
if (format == "Float") return time.ToString(CultureInfo.InvariantCulture);
suffixes = suffixes ?? this.timeSuffixes;
time = DMath.fixHour(time + 0.5 / 60); // add 0.5 minutes to round
var hours = Math.Floor(time);
var minutes = Math.Floor((time - hours) * 60);
var suffix = format == "12h" ? suffixes[hours < 12 ? 0 : 1] : string.Empty;
var hour = format == "24h" ? this.twoDigitsFormat(hours) : ((hours + 12 - 1) % 12 + 1).ToString(CultureInfo.InvariantCulture);
return hour + ":" + this.twoDigitsFormat(minutes) + (!string.IsNullOrEmpty(suffix) ? " " + suffix : string.Empty);
}
//---------------------- Calculation Functions -----------------------
// compute mid-day time
public double midDay(double time)
{
var eqt = this.sunPosition(this.jDate + time).equation;
var noon = DMath.fixHour(12 - eqt);
return noon;
}
// compute the time at which sun reaches a specific angle below horizon
public double sunAngleTime(double angle, double time, string direction = null)
{
var decl = this.sunPosition(this.jDate + time).declination;
var noon = this.midDay(time);
var t = 1.0 / 15.0 * DMath.arccos((-DMath.sin(angle) - DMath.sin(decl) * DMath.sin(this.lat)) / (DMath.cos(decl) * DMath.cos(this.lat)));
return noon + (direction == "ccw" ? -t : t);
}
// compute asr time
public double asrTime(double factor, double time)
{
var decl = this.sunPosition(this.jDate + time).declination;
var angle = -DMath.arccot(factor + DMath.tan(Math.Abs(this.lat - decl)));
return this.sunAngleTime(angle, time);
}
// compute declination angle of sun and equation of time
// Ref: http://aa.usno.navy.mil/faq/docs/SunApprox.php
public SunPosition sunPosition(double jd)
{
var D = jd - 2451545.0;
var g = DMath.fixAngle(357.529 + 0.98560028 * D);
var q = DMath.fixAngle(280.459 + 0.98564736 * D);
var L = DMath.fixAngle(q + 1.915 * DMath.sin(g) + 0.020 * DMath.sin(2 * g));
var R = 1.00014 - 0.01671 * DMath.cos(g) - 0.00014 * DMath.cos(2 * g);
var e = 23.439 - 0.00000036 * D;
var RA = DMath.arctan2(DMath.cos(e) * DMath.sin(L), DMath.cos(L)) / 15;
var eqt = q / 15 - DMath.fixHour(RA);
var decl = DMath.arcsin(DMath.sin(e) * DMath.sin(L));
return new SunPosition(decl, eqt);
}
// convert Gregorian date to Julian day
// Ref: Astronomical Algorithms by Jean Meeus
public double julian(double year, double month, double day)
{
if (month <= 2)
{
year -= 1;
month += 12;
}
var A = Math.Floor(year / 100.0);
var B = 2 - A + Math.Floor(A / 4.0);
var JD = Math.Floor(365.25 * (year + 4716)) + Math.Floor(30.6001 * (month + 1.0)) + day + B - 1524.5;
return JD;
}
//---------------------- Compute Prayer Times -----------------------
// compute prayer times at given julian date
public Dictionary<TimeName, double> computePrayerTimes(Dictionary<TimeName, double> times)
{
times = this.dayPortion(times);
var paramss = this.setting;
var imsak = this.sunAngleTime(this.eval(paramss[TimeName.Imsak]), times[TimeName.Imsak], "ccw");
var fajr = this.sunAngleTime(this.eval(paramss[TimeName.Fajr]), times[TimeName.Fajr], "ccw");
var sunrise = this.sunAngleTime(this.riseSetAngle(), times[TimeName.Sunrise], "ccw");
var dhuhr = this.midDay(times[TimeName.Dhuhr]);
var asr = this.asrTime(this.asrFactor((AsrMethod)paramss[TimeName.Asr]), times[TimeName.Asr]);
var sunset = this.sunAngleTime(this.riseSetAngle(), times[TimeName.Sunset]);
var maghrib = this.sunAngleTime(this.eval(paramss[TimeName.Maghrib]), times[TimeName.Maghrib]);
var isha = this.sunAngleTime(this.eval(paramss[TimeName.Isha]), times[TimeName.Isha]);
return new Dictionary<TimeName, double>
{
{
TimeName.Imsak, imsak
},
{
TimeName.Fajr, fajr
},
{
TimeName.Sunrise, sunrise
},
{
TimeName.Dhuhr, dhuhr
},
{
TimeName.Asr, asr
},
{
TimeName.Sunset, sunset
},
{
TimeName.Maghrib, maghrib
},
{
TimeName.Isha, isha
}
};
}
// compute prayer times
public Dictionary<TimeName, double> computeTimes()
{
// default times
var times = new Dictionary<TimeName, double>
{
{
TimeName.Imsak, 5
},
{
TimeName.Fajr, 5
},
{
TimeName.Sunrise, 6
},
{
TimeName.Dhuhr, 12
},
{
TimeName.Asr, 13
},
{
TimeName.Sunset, 18
},
{
TimeName.Maghrib, 18
},
{
TimeName.Isha, 18
}
};
// main iterations
for (var i = 1; i <= this.numIterations; i++)
{
times = this.computePrayerTimes(times);
}
times = this.adjustTimes(times);
// add midnight time
times[TimeName.Midnight] = (string)this.setting[TimeName.Midnight] == "Jafari"
? times[TimeName.Sunset] + this.timeDiff(times[TimeName.Sunset], times[TimeName.Fajr]) / 2
: times[TimeName.Sunset] + this.timeDiff(times[TimeName.Sunset], times[TimeName.Sunrise]) / 2;
times = this.tuneTimes(times);
return this.modifyFormats(times);
}
// adjust times
public Dictionary<TimeName, double> adjustTimes(Dictionary<TimeName, double> times)
{
var paramss = this.setting;
for (int i = 0; i < times.Count; i++)
{
times[times.ElementAt(i).Key] += this.timeZone - this.lng / 15;
}
if ((string)paramss[TimeName.HighLats] != "None") times = this.adjustHighLats(times);
if (this.isMin(paramss[TimeName.Imsak])) times[TimeName.Imsak] = times[TimeName.Fajr] - this.eval(paramss[TimeName.Imsak]) / 60;
if (this.isMin(paramss[TimeName.Maghrib])) times[TimeName.Maghrib] = times[TimeName.Sunset] + this.eval(paramss[TimeName.Maghrib]) / 60;
if (this.isMin(paramss[TimeName.Isha])) times[TimeName.Isha] = times[TimeName.Maghrib] + this.eval(paramss[TimeName.Isha]) / 60;
times[TimeName.Dhuhr] += this.eval(paramss[TimeName.Dhuhr]) / 60;
return times;
}
// get asr shadow factor
public double asrFactor(AsrMethod asrParam)
{
var factor = new Dictionary<AsrMethod, double>
{
{
AsrMethod.Standard, 1
},
{
AsrMethod.Hanafi, 2
}
};
//[asrParam];
//return factor || this.eval(asrParam);
return factor[asrParam];
}
// return sun angle foreach sunset/sunrise
public double riseSetAngle()
{
//var earthRad = 6371009; // in meters
//var angle = DMath.arccos(earthRad/(earthRad+ elv));
var angle = 0.0347 * Math.Sqrt(this.elv); // an approximation
return 0.833 + angle;
}
// apply offsets to the times
public Dictionary<TimeName, double> tuneTimes(Dictionary<TimeName, double> times)
{
for (int i = 0; i < times.Count; i++)
{
var element = times.ElementAt(i);
times[element.Key] += this.offset[element.Key] / 60.0;
}
return times;
}
// convert times to given time format
public Dictionary<TimeName, double> modifyFormats(Dictionary<TimeName, double> times)
{
for (int i = 0; i < times.Count; i++)
{
var element = times.ElementAt(i);
//times[i.Key] = this.getFormattedTime(times[i.Key], timeFormat);
var formattedTime = this.getFormattedTime(times[element.Key], this.timeFormat);
times[element.Key] = Convert.ToDouble(this.getFormattedTime(times[element.Key], this.timeFormat));
}
return times;
}
// adjust times foreach locations in higher latitudes
public Dictionary<TimeName, double> adjustHighLats(Dictionary<TimeName, double> times)
{
var paramss = this.setting;
var nightTime = this.timeDiff(times[TimeName.Sunset], times[TimeName.Sunrise]);
times[TimeName.Imsak] = this.adjustHLTime(times[TimeName.Imsak], times[TimeName.Sunrise], this.eval(paramss[TimeName.Imsak]), nightTime, "ccw");
times[TimeName.Fajr] = this.adjustHLTime(times[TimeName.Fajr], times[TimeName.Sunrise], this.eval(paramss[TimeName.Fajr]), nightTime, "ccw");
times[TimeName.Isha] = this.adjustHLTime(times[TimeName.Isha], times[TimeName.Sunset], this.eval(paramss[TimeName.Isha]), nightTime);
times[TimeName.Maghrib] = this.adjustHLTime(times[TimeName.Maghrib], times[TimeName.Sunset], this.eval(paramss[TimeName.Maghrib]), nightTime);
return times;
}
// adjust a time foreach higher latitudes
public double adjustHLTime(double time, double _base, double angle, double night, string direction = null)
{
var portion = this.nightPortion(angle, night);
var timeDiff = direction == "ccw" ? this.timeDiff(time, _base) : this.timeDiff(_base, time);
if (double.IsNaN(time) || timeDiff > portion) time = _base + (direction == "ccw" ? -portion : portion);
return time;
}
// the night portion used foreach adjusting times in higher latitudes
public double nightPortion(double angle, double night)
{
var method = (string)this.setting[TimeName.HighLats];
var portion = 1.0 / 2.0; // MidNight
if (method == "AngleBased") portion = 1.0 / 60.0 * angle;
if (method == "OneSeventh") portion = 1.0 / 7.0;
return portion * night;
}
// convert hours to day portions
public Dictionary<TimeName, double> dayPortion(Dictionary<TimeName, double> times)
{
for (int i = 0; i < times.Count; i++)
{
times[times.ElementAt(i).Key] /= 24;
}
return times;
}
//---------------------- Time Zone Functions -----------------------
// get local time zone
public double getTimeZone(DateTime date)
{
var year = date.Year;
double t1 = this.gmtOffset(new DateTime(year, 0, 1));
double t2 = this.gmtOffset(new DateTime(year, 6, 1));
return Math.Min(t1, t2);
}
// get daylight saving foreach a given date
public double getDst(DateTime date)
{
//return 1 * (this.gmtOffset(date) != this.getTimeZone(date));
return 1 * this.getTimeZone(date);
}
// GMT offset foreach a given date
public double gmtOffset(DateTime date)
{
var localDate = new DateTime(date.Year, date.Month - 1, date.Day, 12, 0, 0, 0);
var GMTString = localDate.ToUniversalTime().ToString(CultureInfo.InvariantCulture);
var GMTDate = DateTime.Parse(GMTString.Substring(0, GMTString.LastIndexOf(" ", StringComparison.Ordinal) - 1));
var hoursDiff = (localDate - GMTDate).TotalHours / (1000.0 * 60.0 * 60.0);
return hoursDiff;
}
//---------------------- Misc Functions -----------------------
// convert given string into a number
public double eval(object str)
{
return 1 * double.Parse(Regex.Split(str + string.Empty, "[^0-9.+-]")[0]);
}
// detect if input contains "min"
public bool isMin(object arg)
{
return (arg + string.Empty).IndexOf("min", StringComparison.Ordinal) != -1;
}
// compute the difference between two times
public double timeDiff(double time1, double time2)
{
return DMath.fixHour(time2 - time1);
}
// add a leading 0 if necessary
public string twoDigitsFormat(double num)
{
return num < 10 ? "0" + num : num.ToString(CultureInfo.InvariantCulture);
}
}
}
| |
using System;
using System.Linq;
using System.Web;
using Assman.Configuration;
using Assman.DependencyManagement;
using Assman.TestSupport;
using NUnit.Framework;
namespace Assman.Registration
{
public class TestConsolidatingResourceRegistry
{
private AssmanContext _context;
private const string myScript = "~/myscript.js";
private const string mySecondScript = "~/mysecondscript.js";
private const string consolidatedScript = "~/consolidated.js";
private const string excludedScript = "~/excluded.js";
private ScriptGroupElement _groupElement;
private StubResourceFinder _finder;
private StubDependencyProvider _dependencyProvider;
private ConsolidatingResourceRegistry _registry;
[SetUp]
public void Init()
{
_finder = new StubResourceFinder();
_finder.CreateResource(myScript);
_finder.CreateResource(mySecondScript);
_finder.CreateResource(excludedScript);
_dependencyProvider = new StubDependencyProvider();
DependencyManagerFactory.ClearDependencyCache();
_context = AssmanContext.Create(ResourceMode.Debug);
_context.ConsolidateScripts = true;
_context.ConfigurationLastModified = DateTime.MinValue;
_context.AddFinder(_finder);
_context.MapExtensionToDependencyProvider(".js", _dependencyProvider);
_groupElement = new ScriptGroupElement();
_groupElement.ConsolidatedUrl = consolidatedScript;
_groupElement.Exclude.AddPattern(excludedScript);
_context.ScriptGroups.Add(_groupElement);
_registry = new ConsolidatingResourceRegistry(new ResourceRequirementCollection(), "Default", _context.ScriptPathResolver, new ConfiguredVersioningStrategy(() => _context.Version));
}
[Test]
public void IncludesConsolidatedScriptFileWhenScriptConsolidationEnabled()
{
_context.ConsolidateScripts = true;
_registry.Require(myScript);
var scriptToInclude = _registry.GetIncludes().Single();
Assert.That(scriptToInclude, Is.EqualTo(consolidatedScript).IgnoreCase);
}
[Test]
public void IncludesAllFilesInGroupWhenScriptConsolidationDisabled()
{
_context.ConsolidateScripts = false;
_registry.Require(myScript);
var scriptsToInclude = _registry.GetIncludes().ToList();
scriptsToInclude.CountShouldEqual(2);
scriptsToInclude.ShouldContain(p => p.EqualsVirtualPath(myScript));
scriptsToInclude.ShouldContain(p => p.EqualsVirtualPath(mySecondScript));
}
[Test]
public void AppendsVersionNumberToConsolidatedUrl()
{
const string version = "2";
_context.ConsolidateScripts = true;
_context.Version = version;
_registry.Require(myScript);
string scriptToInclude = _registry.GetIncludes().Single();
Assert.AreEqual(consolidatedScript + "?v=" + version, scriptToInclude);
}
[Test]
public void AppendsVersionNumberToUnConsolidatedUrl()
{
const string version = "2";
_context.ConsolidateScripts = false;
_context.Version = version;
_registry.Require(myScript);
var scriptsToInclude = _registry.GetIncludes();
scriptsToInclude.All(path => path.EndsWith("?v=" + version)).ShouldBeTrue();
}
[Test]
public void VersionParameterIsUrlEncoded()
{
const string version = "2 2";
_context.ConsolidateScripts = true;
_context.Version = version;
_registry.Require(myScript);
string scriptToInclude = _registry.GetIncludes().Single();
Assert.AreEqual(consolidatedScript + "?v=" + HttpUtility.UrlEncode(version), scriptToInclude);
}
[Test]
public void IncludesIndividualFileWhenItIsNotPartOfAGroup()
{
_context.ConsolidateScripts = true;
_registry.Require(excludedScript);
string scriptToInclude = _registry.GetIncludes().Single();
Assert.That(scriptToInclude, Is.EqualTo(excludedScript));
}
[Test]
public void ExclusionsAreCaseInsensitive()
{
_context.ConsolidateScripts = true;
_registry.Require(excludedScript.ToUpperInvariant());
string scriptToInclude = _registry.GetIncludes().Single();
Assert.That(scriptToInclude, Is.EqualTo(excludedScript).IgnoreCase);
}
[Test]
public void FilesInSecondGroupAndNotInFirstReturnSecondGroupUrl()
{
const string secondGroupUrl = "~/mysecondconsolidation.js";
_context.ConsolidateScripts = true;
_groupElement.Exclude.AddPattern(mySecondScript);
var secondGroupElement = new ScriptGroupElement();
_context.ScriptGroups.Add(secondGroupElement);
secondGroupElement.ConsolidatedUrl = secondGroupUrl;
_registry.Require(mySecondScript);
string scriptToInclude = _registry.GetIncludes().Single();
Assert.That(scriptToInclude, Is.EqualTo(secondGroupUrl).IgnoreCase);
}
[Test]
public void ScriptUrlIsLazilyCached()
{
_registry.Require(myScript);
var resolvedScriptPath1 = _registry.GetIncludes().Single();
if(resolvedScriptPath1 != consolidatedScript)
Assert.Inconclusive("The first call to GetScriptUrl did not return the expected result");
_context.ScriptGroups.Clear();
_registry.Require(myScript);
var resolvedScriptPath2 = _registry.GetIncludes().Single();
resolvedScriptPath2.ShouldEqual(resolvedScriptPath1);
}
[Test]
public void WhenGroupUrlIsPassedIntoGetResourceUrlAndConsolidationIsEnabled_GroupUrlIsReturned()
{
_groupElement.Include.AddPattern("~/Scripts/.+");
var secondGroup = new ScriptGroupElement();
secondGroup.ConsolidatedUrl = "~/Scripts/Consolidated/SecondGroup.js";
_context.ScriptGroups.Add(secondGroup);
_registry.Require(secondGroup.ConsolidatedUrl);
var resolvedScriptPath = _registry.GetIncludes().Single();
resolvedScriptPath.ShouldEqual(secondGroup.ConsolidatedUrl);
}
[Test]
public void WhenGroupUrlIsRequiredThatMatchesThePatternOfAPreviousGroup_TheGroupUrlIsReturned()
{
var anotherGroup = new ScriptGroupElement();
anotherGroup.ConsolidatedUrl = "~/another_consolidated_url.js";
anotherGroup.Include.AddPath(myScript);
_context.ScriptGroups.Add(anotherGroup);
_groupElement.Include.AddPattern("another_consolidated_url");
_registry.Require(anotherGroup.ConsolidatedUrl);
var resolvedScriptPath = _registry.GetIncludes().Single();
resolvedScriptPath.ShouldEqual(anotherGroup.ConsolidatedUrl);
}
[Test]
public void WhenGroupUrlIsRequiredAndConsolidationForThatGroupIsDisabled_PathToEachResourceInGroupIsReturned()
{
_groupElement.Include.AddPath(myScript);
_groupElement.Include.AddPath(mySecondScript);
_groupElement.Consolidate = ResourceModeCondition.Never;
_registry.Require(consolidatedScript);
var resolvedScriptPaths = _registry.GetIncludes().ToList();
resolvedScriptPaths.CountShouldEqual(2);
resolvedScriptPaths[0].ShouldEqual(myScript);
resolvedScriptPaths[1].ShouldEqual(mySecondScript);
}
[Test]
public void WhenGroupUrlIsPassedInAndConsolidationForThatGroupIsDisabled_PathToEachResourceIsReturnedRespectingDependencies()
{
_dependencyProvider.SetDependencies(myScript, mySecondScript);
_groupElement.Include.AddPath(myScript);
_groupElement.Include.AddPath(mySecondScript);
_groupElement.Consolidate = ResourceModeCondition.Never;
_registry.Require(consolidatedScript);
var resolvedScriptPaths = _registry.GetIncludes().ToList();
resolvedScriptPaths.CountShouldEqual(2);
resolvedScriptPaths[0].ShouldEqual(mySecondScript);
resolvedScriptPaths[1].ShouldEqual(myScript);
}
}
}
| |
using System;
using System.Collections.Generic;
/// <summary>
/// System.Collections.Generic.List.Reverse(int32,int32)
/// </summary>
public class ListReverse2
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is byte");
try
{
byte[] byArray = new byte[100];
TestLibrary.Generator.GetBytes(-55, byArray);
List<byte> listObject = new List<byte>(byArray);
byte[] expected = this.reverse<byte>(byArray);
listObject.Reverse(10, 80);
for (int i = 0; i < 100; i++)
{
if ((i < 10) || (i > 89))
{
if (listObject[i] != byArray[i])
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,i is: " + i);
retVal = false;
}
}
else
{
if (listObject[i] != expected[i])
{
TestLibrary.TestFramework.LogError("002", "The result is not the value as expected,i is: " + i);
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string");
try
{
string[] strArray = { "dog", "apple", "joke", "banana", "chocolate", "dog", "food", "Microsoft" };
List<string> listObject = new List<string>(strArray);
listObject.Reverse(2, 5);
string[] expected = { "dog", "apple", "food", "dog", "chocolate", "banana", "joke", "Microsoft" };
for (int i = 0; i < 8; i++)
{
if (listObject[i] != expected[i])
{
TestLibrary.TestFramework.LogError("004", "The result is not the value as expected,i is: " + i);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type");
try
{
MyClass myclass1 = new MyClass();
MyClass myclass2 = new MyClass();
MyClass myclass3 = new MyClass();
MyClass myclass4 = new MyClass();
MyClass[] mc = new MyClass[4] { myclass1, myclass2, myclass3, myclass4 };
List<MyClass> listObject = new List<MyClass>(mc);
listObject.Reverse(0, 2);
MyClass[] expected = new MyClass[4] { myclass2, myclass1, myclass3, myclass4 };
for (int i = 0; i < 4; i++)
{
if (listObject[i] != expected[i])
{
TestLibrary.TestFramework.LogError("006", "The result is not the value as expected,i is: " + i);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: The list has no element");
try
{
List<int> listObject = new List<int>();
listObject.Reverse(0, 0);
if (listObject.Count != 0)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,count is: " + listObject.Count);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The index is a negative number");
try
{
int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 10, 2, 4 };
List<int> listObject = new List<int>(iArray);
listObject.Reverse(-1, 3);
TestLibrary.TestFramework.LogError("101", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The count is a negative number");
try
{
int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 10, 2, 4 };
List<int> listObject = new List<int>(iArray);
listObject.Reverse(3, -2);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: index and count do not denote a valid range of elements in the List");
try
{
string[] strArray = { "dog", "apple", "joke", "banana", "chocolate", "dog", "food" };
List<string> listObject = new List<string>(strArray);
listObject.Reverse(3, 10);
TestLibrary.TestFramework.LogError("105", "The ArgumentException was not thrown as expected");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ListReverse2 test = new ListReverse2();
TestLibrary.TestFramework.BeginTestCase("ListReverse2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region useful method
private T[] reverse<T>(T[] array)
{
T temp;
T[] arrayT = new T[array.Length];
array.CopyTo(arrayT, 0);
int times = arrayT.Length / 2;
for (int i = 0; i < times; i++)
{
temp = arrayT[i];
arrayT[i] = arrayT[arrayT.Length - 1 - i];
arrayT[arrayT.Length - 1 - i] = temp;
}
return arrayT;
}
#endregion
}
public class MyClass
{
}
| |
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace UnityEditor.UI
{
/// <summary>
/// This script adds the UI menu options to the Unity Editor.
/// </summary>
static internal class MenuOptions
{
private const string kUILayerName = "UI";
private const float kWidth = 160f;
private const float kThickHeight = 30f;
private const float kThinHeight = 20f;
private const string kStandardSpritePath = "UI/Skin/UISprite.psd";
private const string kBackgroundSpriteResourcePath = "UI/Skin/Background.psd";
private const string kInputFieldBackgroundPath = "UI/Skin/InputFieldBackground.psd";
private const string kKnobPath = "UI/Skin/Knob.psd";
private const string kCheckmarkPath = "UI/Skin/Checkmark.psd";
private static Vector2 s_ThickGUIElementSize = new Vector2(kWidth, kThickHeight);
private static Vector2 s_ThinGUIElementSize = new Vector2(kWidth, kThinHeight);
private static Vector2 s_ImageGUIElementSize = new Vector2(100f, 100f);
private static Color s_DefaultSelectableColor = new Color(1f, 1f, 1f, 1f);
private static void SetPositionVisibleinSceneView(RectTransform canvasRTransform, RectTransform itemTransform)
{
// Find the best scene view
SceneView sceneView = SceneView.lastActiveSceneView;
if (sceneView == null && SceneView.sceneViews.Count > 0)
sceneView = SceneView.sceneViews[0] as SceneView;
// Couldn't find a SceneView. Don't set position.
if (sceneView == null || sceneView.camera == null)
return;
// Create world space Plane from canvas position.
Vector2 localPlanePosition;
Camera camera = sceneView.camera;
Vector3 position = Vector3.zero;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRTransform, new Vector2(camera.pixelWidth / 2, camera.pixelHeight / 2), camera, out localPlanePosition))
{
// Adjust for canvas pivot
localPlanePosition.x = localPlanePosition.x + canvasRTransform.sizeDelta.x * canvasRTransform.pivot.x;
localPlanePosition.y = localPlanePosition.y + canvasRTransform.sizeDelta.y * canvasRTransform.pivot.y;
localPlanePosition.x = Mathf.Clamp(localPlanePosition.x, 0, canvasRTransform.sizeDelta.x);
localPlanePosition.y = Mathf.Clamp(localPlanePosition.y, 0, canvasRTransform.sizeDelta.y);
// Adjust for anchoring
position.x = localPlanePosition.x - canvasRTransform.sizeDelta.x * itemTransform.anchorMin.x;
position.y = localPlanePosition.y - canvasRTransform.sizeDelta.y * itemTransform.anchorMin.y;
Vector3 minLocalPosition;
minLocalPosition.x = canvasRTransform.sizeDelta.x * (0 - canvasRTransform.pivot.x) + itemTransform.sizeDelta.x * itemTransform.pivot.x;
minLocalPosition.y = canvasRTransform.sizeDelta.y * (0 - canvasRTransform.pivot.y) + itemTransform.sizeDelta.y * itemTransform.pivot.y;
Vector3 maxLocalPosition;
maxLocalPosition.x = canvasRTransform.sizeDelta.x * (1 - canvasRTransform.pivot.x) - itemTransform.sizeDelta.x * itemTransform.pivot.x;
maxLocalPosition.y = canvasRTransform.sizeDelta.y * (1 - canvasRTransform.pivot.y) - itemTransform.sizeDelta.y * itemTransform.pivot.y;
position.x = Mathf.Clamp(position.x, minLocalPosition.x, maxLocalPosition.x);
position.y = Mathf.Clamp(position.y, minLocalPosition.y, maxLocalPosition.y);
}
itemTransform.anchoredPosition = position;
itemTransform.localRotation = Quaternion.identity;
itemTransform.localScale = Vector3.one;
}
private static GameObject GetParentFromMenuCommandContextOrActiveCanvasInSelection(MenuCommand menuCommand)
{
GameObject parent = menuCommand.context as GameObject;
if (parent == null || FindInParents<Canvas>(parent) == null)
{
parent = GetParentActiveCanvasInSelection(true);
}
return parent;
}
private static GameObject CreateUIElementRoot(string name, MenuCommand menuCommand, Vector2 size)
{
GameObject parent = menuCommand.context as GameObject;
if (parent == null || FindInParents<Canvas>(parent) == null)
{
parent = GetParentActiveCanvasInSelection(true);
}
GameObject child = new GameObject(name);
Undo.RegisterCreatedObjectUndo(child, "Create " + name);
Undo.SetTransformParent(child.transform, parent.transform, "Parent " + child.name);
GameObjectUtility.SetParentAndAlign(child, parent);
RectTransform rectTransform = child.AddComponent<RectTransform>();
rectTransform.sizeDelta = size;
if (parent != menuCommand.context) // not a context click, so center in sceneview
{
SetPositionVisibleinSceneView(parent.GetComponent<RectTransform>(), rectTransform);
}
Selection.activeGameObject = child;
return child;
}
[MenuItem("GameObject/UI/Panel", false, 2000)]
static public void AddPanel(MenuCommand menuCommand)
{
GameObject panelRoot = CreateUIElementRoot("Panel", menuCommand, s_ThickGUIElementSize);
// Set RectTransform to stretch
RectTransform rectTransform = panelRoot.GetComponent<RectTransform>();
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
rectTransform.anchoredPosition = Vector2.zero;
rectTransform.sizeDelta = Vector2.zero;
Image image = panelRoot.AddComponent<Image>();
image.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpriteResourcePath);
image.type = Image.Type.Sliced;
image.color = new Color(1f, 1f, 1f, 0.392f);
}
[MenuItem("GameObject/UI/Button", false, 2001)]
static public void AddButton(MenuCommand menuCommand)
{
GameObject buttonRoot = CreateUIElementRoot("Button", menuCommand, s_ThickGUIElementSize);
GameObject childText = new GameObject("Text");
GameObjectUtility.SetParentAndAlign(childText, buttonRoot);
Image image = buttonRoot.AddComponent<Image>();
image.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePath);
image.type = Image.Type.Sliced;
image.color = s_DefaultSelectableColor;
Button bt = buttonRoot.AddComponent<Button>();
SetDefaultColorTransitionValues(bt);
Text text = childText.AddComponent<Text>();
text.text = "Button";
text.alignment = TextAnchor.MiddleCenter;
text.color = new Color(0.196f, 0.196f, 0.196f);
RectTransform textRectTransform = childText.GetComponent<RectTransform>();
textRectTransform.anchorMin = Vector2.zero;
textRectTransform.anchorMax = Vector2.one;
textRectTransform.sizeDelta = Vector2.zero;
}
[MenuItem("GameObject/UI/Text", false, 2002)]
static public void AddText(MenuCommand menuCommand)
{
GameObject go = CreateUIElementRoot("Text", menuCommand, s_ThickGUIElementSize);
Text lbl = go.AddComponent<Text>();
lbl.text = "New Text";
SetDefaultTextValues(lbl);
}
private static void SetDefaultTextValues(Text lbl)
{
lbl.color = new Color(0.1953125f, 0.1953125f, 0.1953125f, 1f);
}
[MenuItem("GameObject/UI/Image", false, 2003)]
static public void AddImage(MenuCommand menuCommand)
{
GameObject go = CreateUIElementRoot("Image", menuCommand, s_ImageGUIElementSize);
go.AddComponent<Image>();
}
[MenuItem("GameObject/UI/RawImage", false, 2004)]
static public void AddRawImage(MenuCommand menuCommand)
{
GameObject go = CreateUIElementRoot("RawImage", menuCommand, s_ImageGUIElementSize);
go.AddComponent<RawImage>();
}
static GameObject CreateUIObject(string name, GameObject parent)
{
GameObject go = new GameObject(name);
go.AddComponent<RectTransform>();
GameObjectUtility.SetParentAndAlign(go, parent);
return go;
}
[MenuItem("GameObject/UI/Slider", false, 2006)]
static public void AddSlider(MenuCommand menuCommand)
{
// Create GOs Hierarchy
GameObject root = CreateUIElementRoot("Slider", menuCommand, s_ThinGUIElementSize);
GameObject background = CreateUIObject("Background", root);
GameObject fillArea = CreateUIObject("Fill Area", root);
GameObject fill = CreateUIObject("Fill", fillArea);
GameObject handleArea = CreateUIObject("Handle Slide Area", root);
GameObject handle = CreateUIObject("Handle", handleArea);
// Background
Image backgroundImage = background.AddComponent<Image>();
backgroundImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpriteResourcePath);
backgroundImage.type = Image.Type.Sliced;
backgroundImage.color = s_DefaultSelectableColor;
RectTransform backgroundRect = background.GetComponent<RectTransform>();
backgroundRect.anchorMin = new Vector2(0, 0.25f);
backgroundRect.anchorMax = new Vector2(1, 0.75f);
backgroundRect.sizeDelta = new Vector2(0, 0);
// Fill Area
RectTransform fillAreaRect = fillArea.GetComponent<RectTransform>();
fillAreaRect.anchorMin = new Vector2(0, 0.25f);
fillAreaRect.anchorMax = new Vector2(1, 0.75f);
fillAreaRect.anchoredPosition = new Vector2(-5, 0);
fillAreaRect.sizeDelta = new Vector2(-20, 0);
// Fill
Image fillImage = fill.AddComponent<Image>();
fillImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePath);
fillImage.type = Image.Type.Sliced;
fillImage.color = s_DefaultSelectableColor;
RectTransform fillRect = fill.GetComponent<RectTransform>();
fillRect.sizeDelta = new Vector2(10, 0);
// Handle Area
RectTransform handleAreaRect = handleArea.GetComponent<RectTransform>();
handleAreaRect.sizeDelta = new Vector2(-20, 0);
handleAreaRect.anchorMin = new Vector2(0, 0);
handleAreaRect.anchorMax = new Vector2(1, 1);
// Handle
Image handleImage = handle.AddComponent<Image>();
handleImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kKnobPath);
handleImage.color = s_DefaultSelectableColor;
RectTransform handleRect = handle.GetComponent<RectTransform>();
handleRect.sizeDelta = new Vector2(20, 0);
// Setup slider component
Slider slider = root.AddComponent<Slider>();
slider.fillRect = fill.GetComponent<RectTransform>();
slider.handleRect = handle.GetComponent<RectTransform>();
slider.targetGraphic = handleImage;
slider.direction = Slider.Direction.LeftToRight;
SetDefaultColorTransitionValues(slider);
}
private static void SetDefaultColorTransitionValues(Selectable slider)
{
ColorBlock colors = slider.colors;
colors.highlightedColor = new Color(0.882f, 0.882f, 0.882f);
colors.pressedColor = new Color(0.698f, 0.698f, 0.698f);
colors.disabledColor = new Color(0.521f, 0.521f, 0.521f);
}
[MenuItem("GameObject/UI/Scrollbar", false, 2007)]
static public void AddScrollbar(MenuCommand menuCommand)
{
// Create GOs Hierarchy
GameObject scrollbarRoot = CreateUIElementRoot("Scrollbar", menuCommand, s_ThinGUIElementSize);
GameObject sliderArea = CreateUIObject("Sliding Area", scrollbarRoot);
GameObject handle = CreateUIObject("Handle", sliderArea);
Image bgImage = scrollbarRoot.AddComponent<Image>();
bgImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpriteResourcePath);
bgImage.type = Image.Type.Sliced;
bgImage.color = s_DefaultSelectableColor;
Image handleImage = handle.AddComponent<Image>();
handleImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePath);
handleImage.type = Image.Type.Sliced;
handleImage.color = s_DefaultSelectableColor;
RectTransform sliderAreaRect = sliderArea.GetComponent<RectTransform>();
sliderAreaRect.sizeDelta = new Vector2(-20, -20);
sliderAreaRect.anchorMin = Vector2.zero;
sliderAreaRect.anchorMax = Vector2.one;
RectTransform handleRect = handle.GetComponent<RectTransform>();
handleRect.sizeDelta = new Vector2(20, 20);
Scrollbar scrollbar = scrollbarRoot.AddComponent<Scrollbar>();
scrollbar.handleRect = handleRect;
scrollbar.targetGraphic = handleImage;
SetDefaultColorTransitionValues(scrollbar);
}
[MenuItem("GameObject/UI/Toggle", false, 2008)]
static public void AddToggle(MenuCommand menuCommand)
{
// Set up hierarchy
GameObject toggleRoot = CreateUIElementRoot("Toggle", menuCommand, s_ThinGUIElementSize);
GameObject background = CreateUIObject("Background", toggleRoot);
GameObject checkmark = CreateUIObject("Checkmark", background);
GameObject childLabel = CreateUIObject("Label", toggleRoot);
// Set up components
Toggle toggle = toggleRoot.AddComponent<Toggle>();
toggle.isOn = true;
Image bgImage = background.AddComponent<Image>();
bgImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePath);
bgImage.type = Image.Type.Sliced;
bgImage.color = s_DefaultSelectableColor;
Image checkmarkImage = checkmark.AddComponent<Image>();
checkmarkImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kCheckmarkPath);
Text label = childLabel.AddComponent<Text>();
label.text = "Toggle";
label.fontSize = 14;
label.alignment = TextAnchor.UpperLeft;
SetDefaultTextValues(label);
toggle.graphic = checkmarkImage;
toggle.targetGraphic = bgImage;
SetDefaultColorTransitionValues(toggle);
RectTransform bgRect = background.GetComponent<RectTransform>();
bgRect.anchorMin = new Vector2(0f, 1f);
bgRect.anchorMax = new Vector2(0f, 1f);
bgRect.anchoredPosition = new Vector2(10f, -10f);
bgRect.sizeDelta = new Vector2(kThinHeight, kThinHeight);
RectTransform checkmarkRect = checkmark.GetComponent<RectTransform>();
checkmarkRect.anchorMin = new Vector2(0.5f, 0.5f);
checkmarkRect.anchorMax = new Vector2(0.5f, 0.5f);
checkmarkRect.anchoredPosition = Vector2.zero;
checkmarkRect.sizeDelta = new Vector2(20f, 20f);
RectTransform labelRect = childLabel.GetComponent<RectTransform>();
labelRect.anchorMin = new Vector2(0f, 0f);
labelRect.anchorMax = new Vector2(1f, 1f);
labelRect.offsetMin = new Vector2(23f, 1f);
labelRect.offsetMax = new Vector2(-5f, -2f);
}
[MenuItem("GameObject/UI/InputField", false, 2008)]
public static void AddInputField(MenuCommand menuCommand)
{
GameObject root = CreateUIElementRoot("InputField", menuCommand, s_ThickGUIElementSize);
GameObject childPlaceholder = CreateUIObject("Placeholder", root);
GameObject childText = CreateUIObject("Text", root);
Image image = root.AddComponent<Image>();
image.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kInputFieldBackgroundPath);
image.type = Image.Type.Sliced;
image.color = s_DefaultSelectableColor;
InputField inputField = root.AddComponent<InputField>();
SetDefaultColorTransitionValues(inputField);
Text text = childText.AddComponent<Text>();
text.text = "";
text.supportRichText = false;
text.alignment = TextAnchor.UpperLeft;
SetDefaultTextValues(text);
Text placeholder = childPlaceholder.AddComponent<Text>();
placeholder.text = "Enter text...";
placeholder.alignment = TextAnchor.UpperLeft;
placeholder.fontStyle = FontStyle.Italic;
// Make placeholder color half as opaque as normal text color.
Color placeholderColor = text.color;
placeholderColor.a *= 0.5f;
placeholder.color = placeholderColor;
RectTransform textRectTransform = childText.GetComponent<RectTransform>();
textRectTransform.anchorMin = Vector2.zero;
textRectTransform.anchorMax = Vector2.one;
textRectTransform.sizeDelta = Vector2.zero;
textRectTransform.offsetMin = new Vector2(10, 6);
textRectTransform.offsetMax = new Vector2(-10, -7);
RectTransform placeholderRectTransform = childPlaceholder.GetComponent<RectTransform>();
placeholderRectTransform.anchorMin = Vector2.zero;
placeholderRectTransform.anchorMax = Vector2.one;
placeholderRectTransform.sizeDelta = Vector2.zero;
placeholderRectTransform.offsetMin = new Vector2(10, 6);
placeholderRectTransform.offsetMax = new Vector2(-10, -7);
inputField.textComponent = text;
inputField.placeholder = placeholder;
}
[MenuItem("GameObject/UI/Canvas", false, 2009)]
static public void AddCanvas(MenuCommand menuCommand)
{
var go = CreateNewUI();
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject);
if (go.transform.parent as RectTransform)
{
RectTransform rect = go.transform as RectTransform;
rect.anchorMin = Vector2.zero;
rect.anchorMax = Vector2.one;
rect.anchoredPosition = Vector2.zero;
rect.sizeDelta = Vector2.zero;
}
Selection.activeGameObject = go;
}
static public GameObject CreateNewUI()
{
// Root for the UI
var root = new GameObject("Canvas");
root.layer = LayerMask.NameToLayer(kUILayerName);
Canvas canvas = root.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
root.AddComponent<CanvasScaler>();
root.AddComponent<GraphicRaycaster>();
Undo.RegisterCreatedObjectUndo(root, "Create " + root.name);
// if there is no event system add one...
CreateEventSystem(false);
return root;
}
[MenuItem("GameObject/UI/EventSystem", false, 2010)]
public static void CreateEventSystem(MenuCommand menuCommand)
{
GameObject parent = menuCommand.context as GameObject;
CreateEventSystem(true, parent);
}
private static void CreateEventSystem(bool select)
{
CreateEventSystem(select, null);
}
private static void CreateEventSystem(bool select, GameObject parent)
{
var esys = Object.FindObjectOfType<EventSystem>();
if (esys == null)
{
var eventSystem = new GameObject("EventSystem");
GameObjectUtility.SetParentAndAlign(eventSystem, parent);
esys = eventSystem.AddComponent<EventSystem>();
eventSystem.AddComponent<StandaloneInputModule>();
eventSystem.AddComponent<TouchInputModule>();
Undo.RegisterCreatedObjectUndo(eventSystem, "Create " + eventSystem.name);
}
if (select && esys != null)
{
Selection.activeGameObject = esys.gameObject;
}
}
static public T FindInParents<T>(GameObject go) where T : Component
{
if (go == null)
return null;
T comp = null;
Transform t = go.transform;
while (t != null && comp == null)
{
comp = t.GetComponent<T>();
t = t.parent;
}
return comp;
}
// Helper function that returns the selected root object.
static public GameObject GetParentActiveCanvasInSelection(bool createIfMissing)
{
GameObject go = Selection.activeGameObject;
// Try to find a gameobject that is the selected GO or one if ots parents
Canvas p = (go != null) ? FindInParents<Canvas>(go) : null;
// Only use active objects
if (p != null && p.gameObject.activeInHierarchy)
go = p.gameObject;
// No canvas in selection or its parents? Then use just any canvas.
if (go == null)
{
Canvas canvas = Object.FindObjectOfType(typeof(Canvas)) as Canvas;
if (canvas != null)
go = canvas.gameObject;
}
// No canvas present? Create a new one.
if (createIfMissing && go == null)
go = MenuOptions.CreateNewUI();
return go;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using NuGet.Common;
namespace NuGet.Commands
{
[Command(typeof(NuGetCommand), "pack", "PackageCommandDescription", MaxArgs = 1, UsageSummaryResourceName = "PackageCommandUsageSummary",
UsageDescriptionResourceName = "PackageCommandUsageDescription", UsageExampleResourceName = "PackCommandUsageExamples")]
public class PackCommand : Command
{
internal static readonly string SymbolsExtension = ".symbols" + Constants.PackageExtension;
private static readonly string[] _defaultExcludes = new[] {
// Exclude previous package files
@"**\*" + Constants.PackageExtension,
// Exclude all files and directories that begin with "."
@"**\\.**", ".**"
};
// Target file paths to exclude when building the lib package for symbol server scenario
private static readonly string[] _libPackageExcludes = new[] {
@"**\*.pdb",
@"src\**\*"
};
// Target file paths to exclude when building the symbols package for symbol server scenario
private static readonly string[] _symbolPackageExcludes = new[] {
@"content\**\*",
@"tools\**\*.ps1"
};
private readonly HashSet<string> _excludes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, string> _properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private static readonly HashSet<string> _allowedExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
Constants.ManifestExtension,
".csproj",
".vbproj",
".fsproj",
".nproj"
};
private Version _minClientVersionValue;
[Option(typeof(NuGetCommand), "PackageCommandOutputDirDescription")]
public string OutputDirectory { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandBasePathDescription")]
public string BasePath { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandVerboseDescription")]
public bool Verbose { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandVersionDescription")]
public string Version { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandExcludeDescription")]
public ICollection<string> Exclude
{
get { return _excludes; }
}
[Option(typeof(NuGetCommand), "PackageCommandSymbolsDescription")]
public bool Symbols { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandToolDescription")]
public bool Tool { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandBuildDescription")]
public bool Build { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandNoDefaultExcludes")]
public bool NoDefaultExcludes { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandNoRunAnalysis")]
public bool NoPackageAnalysis { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandExcludeEmptyDirectories")]
public bool ExcludeEmptyDirectories { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandIncludeReferencedProjects")]
public bool IncludeReferencedProjects { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandPropertiesDescription")]
public Dictionary<string, string> Properties
{
get
{
return _properties;
}
}
[Option(typeof(NuGetCommand), "PackageCommandMinClientVersion")]
public string MinClientVersion { get; set; }
[ImportMany]
public IEnumerable<IPackageRule> Rules { get; set; }
// TODO: Temporarily hide the real ConfigFile parameter from the help text.
// When we fix #3230, we should remove this property.
public new string ConfigFile { get; set; }
public override void ExecuteCommand()
{
if (Verbose)
{
Console.WriteWarning(LocalizedResourceManager.GetString("Option_VerboseDeprecated"));
Verbosity = Verbosity.Detailed;
}
// Get the input file
string path = GetInputFile();
Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAttemptingToBuildPackage"), Path.GetFileName(path));
// If the BasePath is not specified, use the directory of the input file (nuspec / proj) file
BasePath = String.IsNullOrEmpty(BasePath) ? Path.GetDirectoryName(Path.GetFullPath(path)) : BasePath;
if (!String.IsNullOrEmpty(MinClientVersion))
{
if (!System.Version.TryParse(MinClientVersion, out _minClientVersionValue))
{
throw new CommandLineException(LocalizedResourceManager.GetString("PackageCommandInvalidMinClientVersion"));
}
}
IPackage package = BuildPackage(path);
if (package != null && !NoPackageAnalysis)
{
AnalyzePackage(package);
}
}
private IPackage BuildPackage(PackageBuilder builder, string outputPath = null)
{
if (!String.IsNullOrEmpty(Version))
{
builder.Version = new SemanticVersion(Version);
}
if (_minClientVersionValue != null)
{
builder.MinClientVersion = _minClientVersionValue;
}
outputPath = outputPath ?? GetOutputPath(builder);
ExcludeFiles(builder.Files);
// Track if the package file was already present on disk
bool isExistingPackage = File.Exists(outputPath);
try
{
using (Stream stream = File.Create(outputPath))
{
builder.Save(stream);
}
}
catch
{
if (!isExistingPackage && File.Exists(outputPath))
{
File.Delete(outputPath);
}
throw;
}
if (Verbosity == Verbosity.Detailed)
{
PrintVerbose(outputPath);
}
Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandSuccess"), outputPath);
return new OptimizedZipPackage(outputPath);
}
private void PrintVerbose(string outputPath)
{
Console.WriteLine();
var package = new OptimizedZipPackage(outputPath);
Console.WriteLine("Id: {0}", package.Id);
Console.WriteLine("Version: {0}", package.Version);
Console.WriteLine("Authors: {0}", String.Join(", ", package.Authors));
Console.WriteLine("Description: {0}", package.Description);
if (package.LicenseUrl != null)
{
Console.WriteLine("License Url: {0}", package.LicenseUrl);
}
if (package.ProjectUrl != null)
{
Console.WriteLine("Project Url: {0}", package.ProjectUrl);
}
if (!String.IsNullOrEmpty(package.Tags))
{
Console.WriteLine("Tags: {0}", package.Tags.Trim());
}
if (package.DependencySets.Any())
{
Console.WriteLine("Dependencies: {0}", String.Join(", ", package.DependencySets.SelectMany(d => d.Dependencies).Select(d => d.ToString())));
}
else
{
Console.WriteLine("Dependencies: None");
}
Console.WriteLine();
foreach (var file in package.GetFiles().OrderBy(p => p.Path))
{
Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAddedFile"), file.Path);
}
Console.WriteLine();
}
internal void ExcludeFiles(ICollection<IPackageFile> packageFiles)
{
// Always exclude the nuspec file
// Review: This exclusion should be done by the package builder because it knows which file would collide with the auto-generated
// manifest file.
var wildCards = _excludes.Concat(new[] { @"**\*" + Constants.ManifestExtension });
if (!NoDefaultExcludes)
{
// The user has not explicitly disabled default filtering.
wildCards = wildCards.Concat(_defaultExcludes);
}
PathResolver.FilterPackageFiles(packageFiles, file => file.Path, wildCards);
}
private string GetOutputPath(PackageBuilder builder, bool symbols = false)
{
string version = String.IsNullOrEmpty(Version) ? builder.Version.ToString() : Version;
// Output file is {id}.{version}
string outputFile = builder.Id + "." + version;
// If this is a source package then add .symbols.nupkg to the package file name
if (symbols)
{
outputFile += SymbolsExtension;
}
else
{
outputFile += Constants.PackageExtension;
}
string outputDirectory = OutputDirectory ?? Directory.GetCurrentDirectory();
return Path.Combine(outputDirectory, outputFile);
}
private IPackage BuildPackage(string path)
{
string extension = Path.GetExtension(path);
if (extension.Equals(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase))
{
return BuildFromNuspec(path);
}
else
{
return BuildFromProjectFile(path);
}
}
private IPackage BuildFromNuspec(string path)
{
PackageBuilder packageBuilder = CreatePackageBuilderFromNuspec(path);
if (Symbols)
{
// remove source related files when building the lib package
ExcludeFilesForLibPackage(packageBuilder.Files);
if (!packageBuilder.Files.Any())
{
throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("PackageCommandNoFilesForLibPackage"),
path, CommandLineConstants.NuGetDocs));
}
}
IPackage package = BuildPackage(packageBuilder);
if (Symbols)
{
BuildSymbolsPackage(path);
}
return package;
}
private void BuildSymbolsPackage(string path)
{
PackageBuilder symbolsBuilder = CreatePackageBuilderFromNuspec(path);
// remove unnecessary files when building the symbols package
ExcludeFilesForSymbolPackage(symbolsBuilder.Files);
if (!symbolsBuilder.Files.Any())
{
throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("PackageCommandNoFilesForSymbolsPackage"),
path, CommandLineConstants.NuGetDocs));
}
string outputPath = GetOutputPath(symbolsBuilder, symbols: true);
BuildPackage(symbolsBuilder, outputPath);
}
internal static void ExcludeFilesForLibPackage(ICollection<IPackageFile> files)
{
PathResolver.FilterPackageFiles(files, file => file.Path, _libPackageExcludes);
}
internal static void ExcludeFilesForSymbolPackage(ICollection<IPackageFile> files)
{
PathResolver.FilterPackageFiles(files, file => file.Path, _symbolPackageExcludes);
}
private PackageBuilder CreatePackageBuilderFromNuspec(string path)
{
// Set the version property if the flag is set
if (!String.IsNullOrEmpty(Version))
{
Properties["version"] = Version;
}
// Initialize the property provider based on what was passed in using the properties flag
var propertyProvider = new DictionaryPropertyProvider(Properties);
if (String.IsNullOrEmpty(BasePath))
{
return new PackageBuilder(path, propertyProvider, !ExcludeEmptyDirectories);
}
return new PackageBuilder(path, BasePath, propertyProvider, !ExcludeEmptyDirectories);
}
private IPackage BuildFromProjectFile(string path)
{
var factory = new ProjectFactory(path, Properties)
{
IsTool = Tool,
Logger = Console,
Build = Build,
IncludeReferencedProjects = IncludeReferencedProjects
};
// Add the additional Properties to the properties of the Project Factory
foreach (var property in Properties)
{
if (factory.ProjectProperties.ContainsKey(property.Key))
{
Console.WriteWarning(LocalizedResourceManager.GetString("Warning_DuplicatePropertyKey"), property.Key);
}
factory.ProjectProperties[property.Key] = property.Value;
}
// Create a builder for the main package as well as the sources/symbols package
PackageBuilder mainPackageBuilder = factory.CreateBuilder(BasePath);
// Build the main package
IPackage package = BuildPackage(mainPackageBuilder);
// If we're excluding symbols then do nothing else
if (!Symbols)
{
return package;
}
Console.WriteLine();
Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAttemptingToBuildSymbolsPackage"), Path.GetFileName(path));
factory.IncludeSymbols = true;
PackageBuilder symbolsBuilder = factory.CreateBuilder(BasePath);
symbolsBuilder.Version = mainPackageBuilder.Version;
// Get the file name for the sources package and build it
string outputPath = GetOutputPath(symbolsBuilder, symbols: true);
BuildPackage(symbolsBuilder, outputPath);
// this is the real package, not the symbol package
return package;
}
internal void AnalyzePackage(IPackage package)
{
IEnumerable<IPackageRule> packageRules = Rules;
if (!String.IsNullOrEmpty(package.Version.SpecialVersion))
{
// If a package contains a special token, we'll warn users if it does not strictly follow semver guidelines.
packageRules = packageRules.Concat(new[] { new StrictSemanticVersionValidationRule() });
}
IList<PackageIssue> issues = package.Validate(packageRules).OrderBy(p => p.Title, StringComparer.CurrentCulture).ToList();
if (issues.Count > 0)
{
Console.WriteLine();
Console.WriteWarning(LocalizedResourceManager.GetString("PackageCommandPackageIssueSummary"), issues.Count, package.Id);
foreach (var issue in issues)
{
PrintPackageIssue(issue);
}
}
}
private void PrintPackageIssue(PackageIssue issue)
{
Console.WriteLine();
Console.WriteWarning(
prependWarningText: false,
value: LocalizedResourceManager.GetString("PackageCommandIssueTitle"),
args: issue.Title);
Console.WriteWarning(
prependWarningText: false,
value: LocalizedResourceManager.GetString("PackageCommandIssueDescription"),
args: issue.Description);
if (!String.IsNullOrEmpty(issue.Solution))
{
Console.WriteWarning(
prependWarningText: false,
value: LocalizedResourceManager.GetString("PackageCommandIssueSolution"),
args: issue.Solution);
}
}
private string GetInputFile()
{
IEnumerable<string> files = Arguments.Any() ? Arguments : Directory.GetFiles(Directory.GetCurrentDirectory());
return GetInputFile(files);
}
internal static string GetInputFile(IEnumerable<string> files)
{
var candidates = files.Where(file => _allowedExtensions.Contains(Path.GetExtension(file)))
.ToList();
switch (candidates.Count)
{
case 1:
return candidates.Single();
case 2:
// Remove all nuspec files
candidates.RemoveAll(file => Path.GetExtension(file).Equals(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase));
if (candidates.Count == 1)
{
return candidates.Single();
}
goto default;
default:
throw new CommandLineException(LocalizedResourceManager.GetString("PackageCommandSpecifyInputFileError"));
}
}
private class DictionaryPropertyProvider : IPropertyProvider
{
private readonly IDictionary<string, string> _properties;
public DictionaryPropertyProvider(IDictionary<string, string> properties)
{
_properties = properties;
}
public dynamic GetPropertyValue(string propertyName)
{
string value;
if (_properties.TryGetValue(propertyName, out value))
{
return value;
}
return null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.IndicesGetAlias1
{
public partial class IndicesGetAlias1YamlTests
{
public class IndicesGetAlias110BasicYamlBase : YamlTestsBase
{
public IndicesGetAlias110BasicYamlBase() : base()
{
//do indices.create
this.Do(()=> _client.IndicesCreate("test_index", null));
//do indices.create
this.Do(()=> _client.IndicesCreate("test_index_2", null));
//do indices.put_alias
this.Do(()=> _client.IndicesPutAlias("test_index", "test_alias", null));
//do indices.put_alias
this.Do(()=> _client.IndicesPutAlias("test_index", "test_blias", null));
//do indices.put_alias
this.Do(()=> _client.IndicesPutAlias("test_index_2", "test_alias", null));
//do indices.put_alias
this.Do(()=> _client.IndicesPutAlias("test_index_2", "test_blias", null));
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAllAliasesViaAlias2Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAllAliasesViaAlias2Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAliasForAll());
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//match _response.test_index.aliases.test_blias:
this.IsMatch(_response.test_index.aliases.test_blias, new {});
//match _response.test_index_2.aliases.test_alias:
this.IsMatch(_response.test_index_2.aliases.test_alias, new {});
//match _response.test_index_2.aliases.test_blias:
this.IsMatch(_response.test_index_2.aliases.test_blias, new {});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAllAliasesViaIndexAlias3Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAllAliasesViaIndexAlias3Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("test_index"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//match _response.test_index.aliases.test_blias:
this.IsMatch(_response.test_index.aliases.test_blias, new {});
//is_false _response.test_index_2;
this.IsFalse(_response.test_index_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetSpecificAliasViaIndexAliasName4Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetSpecificAliasViaIndexAliasName4Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("test_index", "test_alias"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//is_false _response.test_index.aliases.test_blias;
this.IsFalse(_response.test_index.aliases.test_blias);
//is_false _response.test_index_2;
this.IsFalse(_response.test_index_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAliasesViaIndexAliasAll5Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAliasesViaIndexAliasAll5Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("test_index", "_all"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//match _response.test_index.aliases.test_blias:
this.IsMatch(_response.test_index.aliases.test_blias, new {});
//is_false _response.test_index_2;
this.IsFalse(_response.test_index_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAliasesViaIndexAlias6Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAliasesViaIndexAlias6Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("test_index", "*"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//match _response.test_index.aliases.test_blias:
this.IsMatch(_response.test_index.aliases.test_blias, new {});
//is_false _response.test_index_2;
this.IsFalse(_response.test_index_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAliasesViaIndexAliasPrefix7Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAliasesViaIndexAliasPrefix7Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("test_index", "test_a*"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//is_false _response.test_index.aliases.test_blias;
this.IsFalse(_response.test_index.aliases.test_blias);
//is_false _response.test_index_2;
this.IsFalse(_response.test_index_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAliasesViaIndexAliasNameName8Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAliasesViaIndexAliasNameName8Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("test_index", "test_alias,test_blias"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//match _response.test_index.aliases.test_blias:
this.IsMatch(_response.test_index.aliases.test_blias, new {});
//is_false _response.test_index_2;
this.IsFalse(_response.test_index_2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAliasesViaAliasName9Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAliasesViaAliasName9Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAliasForAll("test_alias"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//match _response.test_index_2.aliases.test_alias:
this.IsMatch(_response.test_index_2.aliases.test_alias, new {});
//is_false _response.test_index.aliases.test_blias;
this.IsFalse(_response.test_index.aliases.test_blias);
//is_false _response.test_index_2.aliases.test_blias;
this.IsFalse(_response.test_index_2.aliases.test_blias);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAliasesViaAllAliasName10Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAliasesViaAllAliasName10Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("_all", "test_alias"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//match _response.test_index_2.aliases.test_alias:
this.IsMatch(_response.test_index_2.aliases.test_alias, new {});
//is_false _response.test_index.aliases.test_blias;
this.IsFalse(_response.test_index.aliases.test_blias);
//is_false _response.test_index_2.aliases.test_blias;
this.IsFalse(_response.test_index_2.aliases.test_blias);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAliasesViaAliasName11Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAliasesViaAliasName11Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("*", "test_alias"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//match _response.test_index_2.aliases.test_alias:
this.IsMatch(_response.test_index_2.aliases.test_alias, new {});
//is_false _response.test_index.aliases.test_blias;
this.IsFalse(_response.test_index.aliases.test_blias);
//is_false _response.test_index_2.aliases.test_blias;
this.IsFalse(_response.test_index_2.aliases.test_blias);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAliasesViaPrefAliasName12Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAliasesViaPrefAliasName12Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("*2", "test_alias"));
//match _response.test_index_2.aliases.test_alias:
this.IsMatch(_response.test_index_2.aliases.test_alias, new {});
//is_false _response.test_index.aliases.test_alias;
this.IsFalse(_response.test_index.aliases.test_alias);
//is_false _response.test_index.aliases.test_blias;
this.IsFalse(_response.test_index.aliases.test_blias);
//is_false _response.test_index_2.aliases.test_blias;
this.IsFalse(_response.test_index_2.aliases.test_blias);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAliasesViaNameNameAliasName13Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAliasesViaNameNameAliasName13Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("test_index,test_index_2", "test_alias"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//match _response.test_index_2.aliases.test_alias:
this.IsMatch(_response.test_index_2.aliases.test_alias, new {});
//is_false _response.test_index.aliases.test_blias;
this.IsFalse(_response.test_index.aliases.test_blias);
//is_false _response.test_index_2.aliases.test_blias;
this.IsFalse(_response.test_index_2.aliases.test_blias);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class NonExistentAliasOnAnExistingIndexReturnsAnEmptyBody14Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void NonExistentAliasOnAnExistingIndexReturnsAnEmptyBody14Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("test_index", "non-existent"));
//match this._status:
this.IsMatch(this._status, new {});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class ExistentAndNonExistentAliasReturnsJustTheExisting15Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void ExistentAndNonExistentAliasReturnsJustTheExisting15Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("test_index", "test_alias,non-existent"));
//match _response.test_index.aliases.test_alias:
this.IsMatch(_response.test_index.aliases.test_alias, new {});
//is_false _response[@"test_index"][@"aliases"][@"non-existent"];
this.IsFalse(_response[@"test_index"][@"aliases"][@"non-existent"]);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GettingAliasOnAnNonExistentIndexShouldReturn40416Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GettingAliasOnAnNonExistentIndexShouldReturn40416Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAlias("non-existent", "foo"), shouldCatch: @"missing");
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class GetAliasWithLocalFlag17Tests : IndicesGetAlias110BasicYamlBase
{
[Test]
public void GetAliasWithLocalFlag17Test()
{
//do indices.get_alias
this.Do(()=> _client.IndicesGetAliasForAll(nv=>nv
.Add("local", @"true")
));
//is_true _response.test_index;
this.IsTrue(_response.test_index);
//is_true _response.test_index_2;
this.IsTrue(_response.test_index_2);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SqlProfileProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Samples {
using System.Web;
using System.Web.UI;
using System;
using System.Web.Profile;
using System.Web.Configuration;
using System.Security.Principal;
using System.Security.Permissions;
using System.Globalization;
using System.Runtime.Serialization;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
using System.Text;
using System.Configuration.Provider;
using System.Configuration;
using System.Web.Hosting;
using System.Web.DataAccess;
using System.Web.Util;
using System.Security;
/* TODO:
*
* REVIEW:
* - Strings that are too long will throw an exception saying data will be truncated...
* - State where I couldn't log in?? ASPXANONYMOUS set
*
*/
public class SqlStoredProcedureProfileProvider : ProfileProvider {
private string _appName;
private string _sqlConnectionString;
private string _readSproc;
private string _setSproc;
private int _commandTimeout;
public override void Initialize(string name, NameValueCollection config) {
if (config == null)
throw new ArgumentNullException("config");
if (String.IsNullOrEmpty(name))
name = "StoredProcedureDBProfileProvider";
if (string.IsNullOrEmpty(config["description"])) {
config.Remove("description");
config.Add("description", "StoredProcedureDBProfileProvider");
}
base.Initialize(name, config);
string temp = config["connectionStringName"];
if (String.IsNullOrEmpty(temp))
throw new ProviderException("connectionStringName not specified");
_sqlConnectionString = GetConnectionString(temp);
if (String.IsNullOrEmpty(_sqlConnectionString)) {
throw new ProviderException("connectionStringName not specified");
}
_appName = config["applicationName"];
if (string.IsNullOrEmpty(_appName))
_appName = GetDefaultAppName();
if (_appName.Length > 256) {
throw new ProviderException("Application name too long");
}
_setSproc = config["setProcedure"];
if (String.IsNullOrEmpty(_setSproc)) {
throw new ProviderException("setProcedure not specified");
}
_readSproc = config["readProcedure"];
if (String.IsNullOrEmpty(_readSproc)) {
throw new ProviderException("readProcedure not specified");
}
string timeout = config["commandTimeout"];
if (string.IsNullOrEmpty(timeout) || !Int32.TryParse(timeout, out _commandTimeout))
{
_commandTimeout = 30;
}
config.Remove("commandTimeout");
config.Remove("connectionStringName");
config.Remove("applicationName");
config.Remove("readProcedure");
config.Remove("setProcedure");
if (config.Count > 0) {
string attribUnrecognized = config.GetKey(0);
if (!String.IsNullOrEmpty(attribUnrecognized))
throw new ProviderException("Unrecognized config attribute:" + attribUnrecognized);
}
}
internal static string GetDefaultAppName() {
try {
string appName = HostingEnvironment.ApplicationVirtualPath;
if (String.IsNullOrEmpty(appName)) {
appName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
int indexOfDot = appName.IndexOf('.');
if (indexOfDot != -1) {
appName = appName.Remove(indexOfDot);
}
}
if (String.IsNullOrEmpty(appName)) {
return "/";
}
else {
return appName;
}
}
catch (SecurityException) {
return "/";
}
}
internal static string GetConnectionString(string specifiedConnectionString) {
if (String.IsNullOrEmpty(specifiedConnectionString))
return null;
// Check <connectionStrings> config section for this connection string
ConnectionStringSettings connObj = ConfigurationManager.ConnectionStrings[specifiedConnectionString];
if (connObj != null)
return connObj.ConnectionString;
return null;
}
public override string ApplicationName {
get { return _appName; }
set {
if (value == null) throw new ArgumentNullException("ApplicationName");
if (value.Length > 256) {
throw new ProviderException("Application name too long");
}
_appName = value;
}
}
private int CommandTimeout {
get { return _commandTimeout; }
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// customProviderData = "Varname;SqlDbType;size"
private void GetProfileDataFromSproc(SettingsPropertyCollection properties, SettingsPropertyValueCollection svc, string username, SqlConnection conn, bool userIsAuthenticated)
{
SqlCommand cmd = CreateSprocSqlCommand(_readSproc, conn, username, userIsAuthenticated);
try {
cmd.Parameters.RemoveAt("@IsUserAnonymous"); //anonymous flag not needed on get
List<ProfileColumnData> columnData = new List<ProfileColumnData>(properties.Count);
foreach (SettingsProperty prop in properties) {
SettingsPropertyValue value = new SettingsPropertyValue(prop);
svc.Add(value);
string persistenceData = prop.Attributes["CustomProviderData"] as string;
// If we can't find the table/column info we will ignore this data
if (String.IsNullOrEmpty(persistenceData)) {
// REVIEW: Perhaps we should throw instead?
continue;
}
string[] chunk = persistenceData.Split(new char[] { ';' });
if (chunk.Length != 3) {
// REVIEW: Perhaps we should throw instead?
continue;
}
string varname = chunk[0];
// REVIEW: Should we ignore case?
SqlDbType datatype = (SqlDbType)Enum.Parse(typeof(SqlDbType), chunk[1], true);
int size = 0;
if (!Int32.TryParse(chunk[2], out size)) {
throw new ArgumentException("Unable to parse as integer: " + chunk[2]);
}
columnData.Add(new ProfileColumnData(varname, value, null /* not needed for get */, datatype));
cmd.Parameters.Add(CreateOutputParam(varname,datatype,size));
}
cmd.ExecuteNonQuery();
for (int i = 0; i < columnData.Count; ++i) {
ProfileColumnData colData = columnData[i];
object val = cmd.Parameters[colData.VariableName].Value;
SettingsPropertyValue propValue = colData.PropertyValue;
//Only initialize a SettingsPropertyValue for non-null values
if (!(val is DBNull || val == null))
{
propValue.PropertyValue = val;
propValue.IsDirty = false;
propValue.Deserialized = true;
}
}
}
finally {
cmd.Dispose();
}
}
public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) {
SettingsPropertyValueCollection svc = new SettingsPropertyValueCollection();
if (collection == null || collection.Count < 1 || context == null)
return svc;
string username = (string)context["UserName"];
bool userIsAuthenticated = (bool)context["IsAuthenticated"];
if (String.IsNullOrEmpty(username))
return svc;
SqlConnection conn = null;
try {
conn = new SqlConnection(_sqlConnectionString);
conn.Open();
GetProfileDataFromSproc(collection, svc, username, conn, userIsAuthenticated);
}
finally {
if (conn != null) {
conn.Close();
}
}
return svc;
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Container struct for use in aggregating columns for queries
private struct ProfileColumnData {
public string VariableName;
public SettingsPropertyValue PropertyValue;
public object Value;
public SqlDbType DataType;
public ProfileColumnData(string var, SettingsPropertyValue pv, object val, SqlDbType type) {
VariableName = var;
PropertyValue = pv;
Value = val;
DataType = type;
}
}
// Helper that just sets up the usual sproc sqlcommand parameters and adds the applicationname/username
private SqlCommand CreateSprocSqlCommand(string sproc, SqlConnection conn, string username, bool isAnonymous) {
SqlCommand cmd = new SqlCommand(sproc, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = CommandTimeout;
cmd.Parameters.AddWithValue("@ApplicationName", ApplicationName);
cmd.Parameters.AddWithValue("@Username", username);
cmd.Parameters.AddWithValue("@IsUserAnonymous", isAnonymous);
return cmd;
}
public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) {
string username = (string)context["UserName"];
bool userIsAuthenticated = (bool)context["IsAuthenticated"];
if (username == null || username.Length < 1 || collection.Count < 1)
return;
SqlConnection conn = null;
SqlCommand cmd = null;
try {
bool anyItemsToSave = false;
// First make sure we have at least one item to save
foreach (SettingsPropertyValue pp in collection) {
if (pp.IsDirty) {
if (!userIsAuthenticated) {
bool allowAnonymous = (bool)pp.Property.Attributes["AllowAnonymous"];
if (!allowAnonymous)
continue;
}
anyItemsToSave = true;
break;
}
}
if (!anyItemsToSave)
return;
conn = new SqlConnection(_sqlConnectionString);
conn.Open();
List<ProfileColumnData> columnData = new List<ProfileColumnData>(collection.Count);
foreach (SettingsPropertyValue pp in collection) {
if (!userIsAuthenticated) {
bool allowAnonymous = (bool)pp.Property.Attributes["AllowAnonymous"];
if (!allowAnonymous)
continue;
}
//Unlike the table provider, the sproc provider works against a fixed stored procedure
//signature, and must provide values for each stored procedure parameter
//
//if (!pp.IsDirty && pp.UsingDefaultValue) // Not fetched from DB and not written to
// continue;
string persistenceData = pp.Property.Attributes["CustomProviderData"] as string;
// If we can't find the table/column info we will ignore this data
if (String.IsNullOrEmpty(persistenceData)) {
// REVIEW: Perhaps we should throw instead?
continue;
}
string[] chunk = persistenceData.Split(new char[] { ';' });
if (chunk.Length != 3) {
// REVIEW: Perhaps we should throw instead?
continue;
}
string varname = chunk[0];
// REVIEW: Should we ignore case?
SqlDbType datatype = (SqlDbType)Enum.Parse(typeof(SqlDbType), chunk[1], true);
// chunk[2] = size, which we ignore
object value = null;
if (!pp.IsDirty && pp.UsingDefaultValue) // Not fetched from DB and not written to
value = DBNull.Value;
else if (pp.Deserialized && pp.PropertyValue == null) { // value was explicitly set to null
value = DBNull.Value;
}
else {
value = pp.PropertyValue;
}
// REVIEW: Might be able to ditch datatype
columnData.Add(new ProfileColumnData(varname, pp, value, datatype));
}
cmd = CreateSprocSqlCommand(_setSproc, conn, username, userIsAuthenticated);
foreach (ProfileColumnData data in columnData) {
cmd.Parameters.AddWithValue(data.VariableName, data.Value);
cmd.Parameters[data.VariableName].SqlDbType = data.DataType;
}
cmd.ExecuteNonQuery();
}
finally {
if (cmd != null)
cmd.Dispose();
if (conn != null)
conn.Close();
}
}
////////////////////////////////////////////////////////////
private static SqlParameter CreateOutputParam(string paramName, SqlDbType dbType, int size)
{
SqlParameter param = new SqlParameter(paramName, dbType);
param.Direction = ParameterDirection.Output;
param.Size = size;
return param;
}
/////////////////////////////////////////////////////////////////////////////
// Mangement APIs from ProfileProvider class
public override int DeleteProfiles(ProfileInfoCollection profiles) {
throw new NotSupportedException("This method is not supported for this provider.");
}
public override int DeleteProfiles(string[] usernames) {
throw new NotSupportedException("This method is not supported for this provider.");
}
public override int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) {
throw new NotSupportedException("This method is not supported for this provider.");
}
public override int GetNumberOfInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) {
throw new NotSupportedException("This method is not supported for this provider.");
}
public override ProfileInfoCollection GetAllProfiles(ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords) {
throw new NotSupportedException("This method is not supported for this provider.");
}
public override ProfileInfoCollection GetAllInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) {
throw new NotSupportedException("This method is not supported for this provider.");
}
public override ProfileInfoCollection FindProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) {
throw new NotSupportedException("This method is not supported for this provider.");
}
public override ProfileInfoCollection FindInactiveProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) {
throw new NotSupportedException("This method is not supported for this provider.");
}
}
}
| |
using System;
/// <summary>
/// ToInt32(System.Decimal)
/// </summary>
public class ConvertToInt32_4
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ToInt32(0<decimal<0.5)");
try
{
double random;
do
random = TestLibrary.Generator.GetDouble(-55);
while (random >= 0.5);
decimal d = decimal.Parse(random.ToString());
int actual = Convert.ToInt32(d);
int expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt32(1>decimal>=0.5)");
try
{
double random;
do
random = TestLibrary.Generator.GetDouble(-55);
while (random < 0.5);
decimal d = decimal.Parse(random.ToString());
int actual = Convert.ToInt32(d);
int expected = 1;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt32(0)");
try
{
decimal d = 0m;
int actual = Convert.ToInt32(d);
int expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt32(int16.max)");
try
{
decimal d = Int32.MaxValue;
int actual = Convert.ToInt32(d);
int expected = Int32.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt32(int32.min)");
try
{
decimal d = Int32.MinValue;
int actual = Convert.ToInt32(d);
int expected = Int32.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("005.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is not thrown.");
try
{
decimal d = (decimal)Int32.MaxValue + 1;
int i = Convert.ToInt32(d);
TestLibrary.TestFramework.LogError("101.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is not thrown.");
try
{
decimal d = (decimal)Int32.MinValue - 1;
int i = Convert.ToInt32(d);
TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToInt32_4 test = new ConvertToInt32_4();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt32_4");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
//
// ********************************************************************************************************
//
// The Original Code is DotSpatial
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in January, 2008.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using DotSpatial.Projections;
using DotSpatial.Serialization;
namespace DotSpatial.Data
{
/// <summary>
/// This is a generic shapefile that is inherited by other specific shapefile types.
/// </summary>
public class Shapefile : FeatureSet
{
#region Private Variables
// Stores extents and some very basic info common to all shapefiles
private AttributeTable _attributeTable;
private int _bufferSize = 1; // The buffer is approximately how much memory in bytes will be loaded at any one time
private ShapefileHeader _header;
#endregion
#region Constructors
/// <summary>
/// When creating a new shapefile, this simply prevents the basic values from being null.
/// </summary>
public Shapefile()
{
Configure();
}
/// <summary>
/// Creates a new shapefile that has a specific feature type
/// </summary>
/// <param name="featureType"></param>
protected Shapefile(FeatureType featureType)
: base(featureType)
{
}
/// <summary>
/// Creates a new instance of a shapefile based on a fileName
/// </summary>
/// <param name="fileName"></param>
protected Shapefile(string fileName)
{
base.Filename = fileName;
Configure();
}
private void Configure()
{
Attributes = new AttributeTable();
_header = new ShapefileHeader();
IndexMode = true;
}
#endregion
/// <summary>
/// The buffer size is an integer value in bytes specifying how large a piece of memory can be used at any one time.
/// Reading and writing from the disk is faster when done all at once. The larger this number the more effective
/// the disk management, but the more ram will be required (and the more likely to trip an out of memory error).
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int BufferSize
{
get { return _bufferSize; }
set { _bufferSize = value; }
}
/// <summary>
/// Gets whether or not the attributes have all been loaded into the data table.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override bool AttributesPopulated
{
get
{
return _attributeTable.AttributesPopulated;
}
set
{
_attributeTable.AttributesPopulated = value;
}
}
/// <summary>
/// This re-directs the DataTable to work with the attribute Table instead.
/// </summary>
public override DataTable DataTable
{
get
{
return _attributeTable.Table;
}
set
{
_attributeTable.Table = value;
}
}
/// <summary>
/// A general header structure that stores some basic information about the shapefile.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ShapefileHeader Header
{
get { return _header; }
set { _header = value; }
}
/// <summary>
/// Gets or sets the attribute Table used by this shapefile.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public AttributeTable Attributes
{
get { return _attributeTable; }
set
{
if (_attributeTable == value) return;
if (_attributeTable != null)
{
_attributeTable.AttributesFilled -= AttributeTableAttributesFilled;
}
_attributeTable = value;
if (_attributeTable != null)
{
_attributeTable.AttributesFilled += AttributeTableAttributesFilled;
}
}
}
/// <summary>
/// Gets the count of members that match the expression
/// </summary>
/// <param name="expressions">The string expression to test</param>
/// <param name="progressHandler">THe progress handler that can also cancel the counting</param>
/// <param name="maxSampleSize">The integer maximum sample size from which to draw counts. If this is negative, it will not be used.</param>
/// <returns>The integer count of the members that match the expression.</returns>
public override int[] GetCounts(string[] expressions, ICancelProgressHandler progressHandler, int maxSampleSize)
{
if (AttributesPopulated) return base.GetCounts(expressions, progressHandler, maxSampleSize);
int[] counts = new int[expressions.Length];
// The most common case would be no filter expression, in which case the count is simply the number of shapes.
bool requiresRun = false;
for (int iex = 0; iex < expressions.Length; iex++)
{
if (!string.IsNullOrEmpty(expressions[iex]))
{
requiresRun = true;
}
else
{
counts[iex] = NumRows();
}
}
if (!requiresRun) return counts;
AttributePager ap = new AttributePager(this, 5000);
ProgressMeter pm = new ProgressMeter(progressHandler, "Calculating Counts", ap.NumPages());
// Don't bother to use a sampling approach if the number of rows is on the same order of magnitude as the number of samples.
if (maxSampleSize > 0 && maxSampleSize < NumRows() / 2)
{
DataTable sample = new DataTable();
sample.Columns.AddRange(GetColumns());
Dictionary<int, int> usedRows = new Dictionary<int, int>();
int samplesPerPage = maxSampleSize / ap.NumPages();
Random rnd = new Random(DateTime.Now.Millisecond);
for (int page = 0; page < ap.NumPages(); page++)
{
for (int i = 0; i < samplesPerPage; i++)
{
int row;
do
{
row = rnd.Next(ap.StartIndex, ap.StartIndex + ap.PageSize);
} while (usedRows.ContainsKey(row));
usedRows.Add(row, row);
sample.Rows.Add(ap.Row(row).ItemArray);
}
ap.MoveNext();
pm.CurrentValue = page;
if (progressHandler.Cancel) break;
//Application.DoEvents();
}
for (int i = 0; i < expressions.Length; i++)
{
try
{
DataRow[] dr = sample.Select(expressions[i]);
counts[i] += dr.Length;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
pm.Reset();
return counts;
}
for (int page = 0; page < ap.NumPages(); page++)
{
for (int i = 0; i < expressions.Length; i++)
{
DataRow[] dr = ap[page].Select(expressions[i]);
counts[i] += dr.Length;
}
pm.CurrentValue = page;
if (progressHandler.Cancel) break;
//Application.DoEvents();
}
pm.Reset();
return counts;
}
/// <summary>
/// This makes the assumption that the organization of the feature list has not
/// changed since loading the attribute content.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AttributeTableAttributesFilled(object sender, EventArgs e)
{
if (IndexMode) return;
for (int fid = 0; fid < Features.Count; fid++)
{
if (fid < _attributeTable.Table.Rows.Count)
{
Features[fid].DataRow = _attributeTable.Table.Rows[fid];
}
}
SetupFeatureLookup();
}
/// <summary>
/// This will return the correct shapefile type by reading the fileName.
/// </summary>
/// <param name="fileName">A string specifying the file with the extension .shp to open.</param>
/// <returns>A correct shapefile object which is exclusively for reading the .shp data</returns>
public static new Shapefile OpenFile(string fileName)
{
return OpenFile(fileName, DataManager.DefaultDataManager.ProgressHandler);
}
/// <summary>
/// This will return the correct shapefile type by reading the fileName.
/// </summary>
/// <param name="fileName">A string specifying the file with the extension .shp to open.</param>
/// <param name="progressHandler">receives progress messages and overrides the ProgressHandler on the DataManager.DefaultDataManager</param>
/// <returns>A correct shapefile object which is exclusively for reading the .shp data</returns>
public static new Shapefile OpenFile(string fileName, IProgressHandler progressHandler)
{
var ext = Path.GetExtension(fileName);
if (ext != null) ext = ext.ToLower();
if (ext != ".shp" && ext != ".shx" && ext != ".dbf")
throw new ArgumentException(String.Format("The file extension {0} is not supported by Shapefile data provider.", ext));
string name = Path.ChangeExtension(fileName, ".shp");
var head = new ShapefileHeader();
head.Open(name);
switch (head.ShapeType)
{
case ShapeType.MultiPatch:
throw new NotImplementedException("This shape type is not yet supported.");
case ShapeType.MultiPoint:
case ShapeType.MultiPointM:
case ShapeType.MultiPointZ:
var mpsf = new MultiPointShapefile();
mpsf.Open(name, progressHandler);
return mpsf;
case ShapeType.NullShape:
throw new NotImplementedException("This shape type is not yet supported.");
case ShapeType.Point:
case ShapeType.PointM:
case ShapeType.PointZ:
var psf = new PointShapefile();
psf.Open(name, progressHandler);
return psf;
case ShapeType.Polygon:
case ShapeType.PolygonM:
case ShapeType.PolygonZ:
var pgsf = new PolygonShapefile();
pgsf.Open(name, progressHandler);
return pgsf;
case ShapeType.PolyLine:
case ShapeType.PolyLineM:
case ShapeType.PolyLineZ:
var lsf = new LineShapefile();
lsf.Open(name, progressHandler);
return lsf;
}
return null;
}
/// <summary>
/// saves a single row to the data source.
/// </summary>
/// <param name="index">the integer row (or FID) index</param>
/// <param name="values">The object array holding the new values to store.</param>
public override void Edit(int index, Dictionary<string, object> values)
{
_attributeTable.Edit(index, values);
}
/// <summary>
/// saves a single row to the data source.
/// </summary>
/// <param name="index">the integer row (or FID) index</param>
/// <param name="values">The object array holding the new values to store.</param>
public override void Edit(int index, DataRow values)
{
_attributeTable.Edit(index, values);
}
/// <summary>
/// Saves the new row to the data source and updates the file with new content.
/// </summary>
/// <param name="values">The values organized against the dictionary of field names.</param>
public override void AddRow(Dictionary<string, object> values)
{
_attributeTable.AddRow(values);
}
/// <summary>
/// Saves the new row to the data source and updates the file with new content.
/// </summary>
/// <param name="values">The values organized against the dictionary of field names.</param>
public override void AddRow(DataRow values)
{
_attributeTable.AddRow(values);
}
/// <inheritdoc />
public override DataTable GetAttributes(int startIndex, int numRows)
{
return _attributeTable.SupplyPageOfData(startIndex, numRows);
}
/// <summary>
/// Converts a page of content from a DataTable format, saving it back to the source.
/// </summary>
/// <param name="startIndex">The 0 based integer index representing the first row in the file (corresponding to the 0 row of the data table)</param>
/// <param name="pageValues">The DataTable representing the rows to set. If the row count is larger than the dataset, this will add the rows instead.</param>
public new void SetAttributes(int startIndex, DataTable pageValues)
{
// overridden in sub-classes
_attributeTable.SetAttributes(startIndex, pageValues);
}
/// <inheritdoc />
public override List<IFeature> SelectByAttribute(string filterExpression)
{
if (!_attributeTable.AttributesPopulated)
{
_attributeTable.Fill(_attributeTable.NumRecords);
}
if (FeatureLookup.Count == 0)
{
SetupFeatureLookup();
}
return base.SelectByAttribute(filterExpression);
}
/// <summary>
/// Reads the attributes from the specified attribute Table.
/// </summary>
public override void FillAttributes()
{
_attributeTable.AttributesPopulated = false; // attributeTable.Table fills itself if attributes are not populated
DataTable = _attributeTable.Table;
base.AttributesPopulated = true;
// Link the data rows to the vectors in this object
}
/// <summary>
/// Sets up the feature lookup, if it has not been already.
/// </summary>
private void SetupFeatureLookup()
{
for (var i = 0; i < _attributeTable.Table.Rows.Count; i++)
{
Features[i].DataRow = _attributeTable.Table.Rows[i];
FeatureLookup[Features[i].DataRow] = Features[i];
}
}
/// <summary>
/// This doesn't rewrite the entire header or erase the existing content. This simply replaces the file length
/// in the file with the new file length. This is generally because we want to write the header first,
/// but don't know the total length of a new file until cycling through the entire file. It is easier, therefore
/// to update the length after editing.
/// </summary>
/// <param name="fileName">A string fileName</param>
/// <param name="length">The integer length of the file in 16-bit words</param>
public static void WriteFileLength(string fileName, int length)
{
byte[] headerData = new byte[28];
WriteBytes(headerData, 0, 9994, false); // Byte 0 File Code 9994 Integer Big
// Bytes 4 - 20 are unused
WriteBytes(headerData, 24, length, false); // Byte 24 File Length File Length Integer Big
using (var bw = new BinaryWriter(new FileStream(fileName, FileMode.Open)))
{
// Actually write our byte array to the file
bw.Write(headerData);
}
}
/// <summary>
/// Reads 4 bytes from the specified byte array starting with offset.
/// If IsBigEndian = true, then this flips the order of the byte values.
/// </summary>
/// <param name="value">An array of bytes that is at least 4 bytes in length from the startIndex</param>
/// <param name="startIndex">A 0 based integer index where the double value begins</param>
/// <param name="isLittleEndian">If this is true, then the order of the bytes is reversed before being converted to a double</param>
/// <returns>A double created from reading the byte array</returns>
public static int ToInt(byte[] value, ref int startIndex, bool isLittleEndian)
{
// Some systems run BigEndian by default, others run little endian.
// The parameter specifies the byte order that should exist on the file.
// The BitConverter tells us what our system will do by default.
if (isLittleEndian != BitConverter.IsLittleEndian)
{
// The byte order of the value to post doesn't match our system, so reverse the byte order.
byte[] flipBytes = new byte[4];
Array.Copy(value, startIndex, flipBytes, 0, 4);
Array.Reverse(flipBytes);
startIndex += 4;
return BitConverter.ToInt32(flipBytes, 0);
}
startIndex += 4;
return BitConverter.ToInt32(value, startIndex);
}
/// <summary>
/// Reads 8 bytes from the specified byte array starting with offset.
/// If IsBigEndian = true, then this flips the order of the byte values.
/// </summary>
/// <param name="value">An array of bytes that is at least 8 bytes in length from the startIndex</param>
/// <param name="startIndex">A 0 based integer index where the double value begins</param>
/// <param name="isLittleEndian">If this is true, then the order of the bytes is reversed before being converted to a double</param>
/// <returns>A double created from reading the byte array</returns>
public static double ToDouble(byte[] value, ref int startIndex, bool isLittleEndian)
{
// Some systems run BigEndian by default, others run little endian.
// The parameter specifies the byte order that should exist on the file.
// The BitConverter tells us what our system will do by default.
if (isLittleEndian != BitConverter.IsLittleEndian)
{
byte[] flipBytes = new byte[8];
Array.Copy(value, startIndex, flipBytes, 0, 8);
Array.Reverse(flipBytes);
startIndex += 8;
return BitConverter.ToDouble(flipBytes, 0);
}
startIndex += 8;
return BitConverter.ToDouble(value, startIndex);
}
/// <summary>
/// Converts the double value into bytes and inserts them starting at startIndex into the destArray
/// </summary>
/// <param name="destArray">A byte array where the values should be written</param>
/// <param name="startIndex">The starting index where the values should be inserted</param>
/// <param name="value">The double value to convert</param>
/// <param name="isLittleEndian">Specifies whether the value should be written as big or little endian</param>
public static void WriteBytes(byte[] destArray, int startIndex, double value, bool isLittleEndian)
{
// Some systems run BigEndian by default, others run little endian.
// The parameter specifies the byte order that should exist on the file.
// The BitConverter tells us what our system will do by default.
if (isLittleEndian != BitConverter.IsLittleEndian)
{
byte[] flipBytes = BitConverter.GetBytes(value);
Array.Reverse(flipBytes);
Array.Copy(flipBytes, 0, destArray, startIndex, 8);
}
else
{
byte[] flipBytes = BitConverter.GetBytes(value);
Array.Copy(flipBytes, 0, destArray, startIndex, 8);
}
}
/// <summary>
/// Converts the double value into bytes and inserts them starting at startIndex into the destArray.
/// This will correct this system's natural byte order to reflect what is required to match the
/// shapefiles specification.
/// </summary>
/// <param name="destArray">A byte array where the values should be written</param>
/// <param name="startIndex">The starting index where the values should be inserted</param>
/// <param name="value">The integer value to convert</param>
/// <param name="isLittleEndian">Specifies whether the value should be written as big or little endian</param>
public static void WriteBytes(byte[] destArray, int startIndex, int value, bool isLittleEndian)
{
// Some systems run BigEndian by default, others run little endian.
// The parameter specifies the byte order that should exist on the file.
// The BitConverter tells us what our system will do by default.
if (isLittleEndian != BitConverter.IsLittleEndian)
{
byte[] flipBytes = BitConverter.GetBytes(value);
Array.Reverse(flipBytes);
Array.Copy(flipBytes, 0, destArray, startIndex, 4);
}
else
{
byte[] flipBytes = BitConverter.GetBytes(value);
Array.Copy(flipBytes, 0, destArray, startIndex, 4);
}
}
/// <summary>
/// Reads the entire index file in order to get a breakdown of how shapes are broken up.
/// </summary>
/// <param name="fileName">A string fileName of the .shx file to read.</param>
/// <returns>A List of ShapeHeaders that give offsets and lengths so that reading can be optimized</returns>
public List<ShapeHeader> ReadIndexFile(string fileName)
{
string shxFilename = fileName;
string ext = Path.GetExtension(fileName);
if (ext != ".shx")
{
shxFilename = Path.ChangeExtension(fileName, ".shx");
}
if (shxFilename == null)
{
throw new NullReferenceException(DataStrings.ArgumentNull_S.Replace("%S", fileName));
}
if (!File.Exists(shxFilename))
{
throw new FileNotFoundException(DataStrings.FileNotFound_S.Replace("%S", shxFilename));
}
var fileLen = new FileInfo(shxFilename).Length;
if (fileLen == 100)
{
// the file is empty so we are done reading
return Enumerable.Empty<ShapeHeader>().ToList();
}
// Use a the length of the file to dimension the byte array
using (var bbReader = new FileStream(shxFilename, FileMode.Open, FileAccess.Read, FileShare.Read, 65536))
{
// Skip the header and begin reading from the first record
bbReader.Seek(100, SeekOrigin.Begin);
_header.ShxLength = (int)(fileLen / 2);
var length = (int)(fileLen - 100);
var numRecords = length / 8;
// Each record consists of 2 Big-endian integers for a total of 8 bytes.
// This will store the header elements that we read from the file.
var result = new List<ShapeHeader>(numRecords);
for (var i = 0; i < numRecords; i++)
{
result.Add(new ShapeHeader
{
Offset = bbReader.ReadInt32(Endian.BigEndian),
ContentLength = bbReader.ReadInt32(Endian.BigEndian),
});
}
return result;
}
}
/// <summary>
/// Ensures that the attribute Table will have information that matches the current Table of attribute information
/// </summary>
public void UpdateAttributes()
{
string newFile = Path.ChangeExtension(Filename, "dbf");
if (!AttributesPopulated)
{
if (File.Exists(Attributes.Filename))
{
if (newFile.Equals(Attributes.Filename))
{ // Already using existing file
}
else
{
if (File.Exists(newFile)) File.Delete(newFile);
File.Copy(Attributes.Filename, newFile);
Attributes.Filename = newFile;
}
return;
}
}
if (Attributes != null && Attributes.Table != null && Attributes.Table.Columns.Count > 0)
{
// The attributes have been loaded and will now replace the ones in the file.
}
else
{
// Only add an FID field if there are no attributes at all.
DataTable newTable = new DataTable();
newTable.Columns.Add("FID");
//for (int i = 0; i < Features.Count; i++)
//Added by JamesP@esdm.co.uk - Index mode has no attributes and no features - so Features.count is Null and so was not adding any rows and failing
int iNumRows = IndexMode ? ShapeIndices.Count : Features.Count;
for (int i = 0; i < iNumRows; i++)
{
DataRow dr = newTable.NewRow();
dr["FID"] = i;
newTable.Rows.Add(dr);
}
if (Attributes != null) Attributes.Table = newTable;
}
//System.Data.DataRow drtemp = Attributes.Table.Rows[0];
if (Attributes != null) Attributes.SaveAs(Path.ChangeExtension(Filename, "dbf"), true);
}
/// <summary>
/// This uses the fileName of this shapefile to read the prj file of the same name
/// and stores the result in the Projection class.
/// </summary>
public void ReadProjection()
{
string prjFile = Path.ChangeExtension(Filename, ".prj");
if (File.Exists(prjFile))
{
Projection = ProjectionInfo.Open(prjFile);
}
else
{
Projection = new ProjectionInfo();
}
}
/// <summary>
/// Automatically uses the fileName of this shapefile to save the projection
/// </summary>
public void SaveProjection()
{
string prjFile = Path.ChangeExtension(Filename, ".prj");
if (File.Exists(prjFile))
{
File.Delete(prjFile);
}
if (Projection != null) Projection.SaveAs(prjFile);
}
/// <summary>
/// Reads just the content requested in order to satisfy the paging ability of VirtualMode for the DataGridView
/// </summary>
/// <param name="startIndex">The integer lower page boundary</param>
/// <param name="numRows">The integer number of attribute rows to return for the page</param>
/// <param name="fieldNames">The list or array of fieldnames to return.</param>
/// <returns>A DataTable populated with data rows with only the specified values.</returns>
public override DataTable GetAttributes(int startIndex, int numRows, IEnumerable<string> fieldNames)
{
if (AttributesPopulated) return base.GetAttributes(startIndex, numRows, fieldNames);
DataTable result = new DataTable();
DataColumn[] columns = GetColumns();
// Always add FID in this paging scenario.
result.Columns.Add("FID", typeof(int));
foreach (string name in fieldNames)
{
foreach (var col in columns)
{
if (String.Equals(col.ColumnName, name, StringComparison.CurrentCultureIgnoreCase))
{
result.Columns.Add(col);
break;
}
}
}
for (int i = 0; i < numRows; i++)
{
DataRow dr = result.NewRow();
dr["FID"] = startIndex + i;
result.Rows.Add(dr);
}
// Most use cases with an expression use only one or two fieldnames. Tailor for better
// performance in that case, at the cost of performance in the "read all " case.
// The other overload without fieldnames specified is designed for that case.
foreach (string field in fieldNames)
{
if (field == "FID") continue;
object[] values = _attributeTable.SupplyPageOfData(startIndex, numRows, field);
for (int i = 0; i < numRows; i++)
{
result.Rows[i][field] = values[i];
}
}
return result;
}
/// <summary>
/// The number of rows
/// </summary>
/// <returns></returns>
public override int NumRows()
{
// overridden in sub-classes
return _attributeTable.NumRecords;
}
/// <summary>
/// This gets a copy of the actual internal list of columns.
/// This should never be used to make changes to the column collection.
/// </summary>
public override DataColumn[] GetColumns()
{
return _attributeTable.Columns
.Select(_ => (DataColumn) new Field(_.ColumnName, _.TypeCharacter, _.Length, _.DecimalCount))
.ToArray();
}
/// <summary>
/// Checks that shape file can be saved to given fileName.
/// </summary>
/// <param name="fileName">File name to save.</param>
/// <param name="overwrite">Overwrite file or not.</param>
protected void EnsureValidFileToSave(string fileName, bool overwrite)
{
string dir = Path.GetDirectoryName(fileName);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
else if (File.Exists(fileName))
{
if (fileName != Filename && overwrite == false) throw new ArgumentOutOfRangeException("fileName", "File exists and overwrite = False.");
File.Delete(fileName);
var shx = Path.ChangeExtension(fileName, ".shx");
if (File.Exists(shx)) File.Delete(shx);
}
}
/// <summary>
/// Saves header
/// </summary>
/// <param name="fileName">File to save.</param>
protected void HeaderSaveAs(string fileName)
{
InvalidateEnvelope();
Header.SetExtent(Extent);
Header.ShxLength = IndexMode ? ShapeIndices.Count * 4 + 50 : Features.Count * 4 + 50;
Header.SaveAs(fileName);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using SR = System.Reflection;
using System.Runtime.CompilerServices;
using Mono.Cecil.Cil;
using NUnit.Framework;
namespace Mono.Cecil.Tests {
[TestFixture]
public class ImportCecilTests : BaseTestFixture {
[Test]
public void ImportStringByRef ()
{
var get_string = Compile<Func<string, string>> ((module, body) => {
var type = module.Types [1];
var method_by_ref = new MethodDefinition {
Name = "ModifyString",
IsPrivate = true,
IsStatic = true,
};
type.Methods.Add (method_by_ref);
method_by_ref.MethodReturnType.ReturnType = module.ImportReference (typeof (void).ToDefinition ());
method_by_ref.Parameters.Add (new ParameterDefinition (module.ImportReference (typeof (string).ToDefinition ())));
method_by_ref.Parameters.Add (new ParameterDefinition (module.ImportReference (new ByReferenceType (typeof (string).ToDefinition ()))));
var m_il = method_by_ref.Body.GetILProcessor ();
m_il.Emit (OpCodes.Ldarg_1);
m_il.Emit (OpCodes.Ldarg_0);
m_il.Emit (OpCodes.Stind_Ref);
m_il.Emit (OpCodes.Ret);
var v_0 = new VariableDefinition (module.ImportReference (typeof (string).ToDefinition ()));
body.Variables.Add (v_0);
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldnull);
il.Emit (OpCodes.Stloc, v_0);
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldloca, v_0);
il.Emit (OpCodes.Call, method_by_ref);
il.Emit (OpCodes.Ldloc_0);
il.Emit (OpCodes.Ret);
});
Assert.AreEqual ("foo", get_string ("foo"));
}
[Test]
public void ImportStringArray ()
{
var identity = Compile<Func<string [,], string [,]>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ret);
});
var array = new string [2, 2];
Assert.AreEqual (array, identity (array));
}
[Test]
public void ImportFieldStringEmpty ()
{
var get_empty = Compile<Func<string>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldsfld, module.ImportReference (typeof (string).GetField ("Empty").ToDefinition ()));
il.Emit (OpCodes.Ret);
});
Assert.AreEqual ("", get_empty ());
}
[Test]
public void ImportStringConcat ()
{
var concat = Compile<Func<string, string, string>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Call, module.ImportReference (typeof (string).GetMethod ("Concat", new [] { typeof (string), typeof (string) }).ToDefinition ()));
il.Emit (OpCodes.Ret);
});
Assert.AreEqual ("FooBar", concat ("Foo", "Bar"));
}
public class Generic<T> {
public T Field;
public T Method (T t)
{
return t;
}
public TS GenericMethod<TS> (T t, TS s)
{
return s;
}
public Generic<TS> ComplexGenericMethod<TS> (T t, TS s)
{
return new Generic<TS> { Field = s };
}
}
[Test]
public void ImportGenericField ()
{
var get_field = Compile<Func<Generic<string>, string>> ((module, body) => {
var generic_def = module.ImportReference (typeof (Generic<>)).Resolve ();
var field_def = generic_def.Fields.Where (f => f.Name == "Field").First ();
var field_string = field_def.MakeGeneric (module.ImportReference (typeof (string)));
var field_ref = module.ImportReference (field_string);
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldfld, field_ref);
il.Emit (OpCodes.Ret);
});
var generic = new Generic<string> {
Field = "foo",
};
Assert.AreEqual ("foo", get_field (generic));
}
[Test]
public void ImportGenericMethod ()
{
var generic_identity = Compile<Func<Generic<int>, int, int>> ((module, body) => {
var generic_def = module.ImportReference (typeof (Generic<>)).Resolve ();
var method_def = generic_def.Methods.Where (m => m.Name == "Method").First ();
var method_int = method_def.MakeGeneric (module.ImportReference (typeof (int)));
var method_ref = module.ImportReference (method_int);
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Callvirt, method_ref);
il.Emit (OpCodes.Ret);
});
Assert.AreEqual (42, generic_identity (new Generic<int> (), 42));
}
[Test]
public void ImportGenericMethodSpec ()
{
var gen_spec_id = Compile<Func<Generic<string>, int, int>> ((module, body) => {
var generic_def = module.ImportReference (typeof (Generic<>)).Resolve ();
var method_def = generic_def.Methods.Where (m => m.Name == "GenericMethod").First ();
var method_string = method_def.MakeGeneric (module.ImportReference (typeof (string)));
var method_instance = method_string.MakeGenericMethod (module.ImportReference (typeof (int)));
var method_ref = module.ImportReference (method_instance);
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldnull);
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Callvirt, method_ref);
il.Emit (OpCodes.Ret);
});
Assert.AreEqual (42, gen_spec_id (new Generic<string> (), 42));
}
[Test]
public void ImportComplexGenericMethodSpec ()
{
var gen_spec_id = Compile<Func<Generic<string>, int, int>> ((module, body) => {
var generic_def = module.ImportReference (typeof (Generic<>)).Resolve ();
var method_def = generic_def.Methods.Where (m => m.Name == "ComplexGenericMethod").First ();
var method_string = method_def.MakeGeneric (module.ImportReference (typeof (string)));
var method_instance = method_string.MakeGenericMethod (module.ImportReference (typeof (int)));
var method_ref = module.ImportReference (method_instance);
var field_def = generic_def.Fields.Where (f => f.Name == "Field").First ();
var field_int = field_def.MakeGeneric (module.ImportReference (typeof (int)));
var field_ref = module.ImportReference (field_int);
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldnull);
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Callvirt, method_ref);
il.Emit (OpCodes.Ldfld, field_ref);
il.Emit (OpCodes.Ret);
});
Assert.AreEqual (42, gen_spec_id (new Generic<string> (), 42));
}
[Test]
public void ImportMethodOnOpenGeneric ()
{
var generic = typeof (Generic<>).ToDefinition ();
var module = ModuleDefinition.CreateModule ("foo", ModuleKind.Dll);
var method = module.ImportReference (generic.GetMethod ("Method"));
Assert.AreEqual ("T Mono.Cecil.Tests.ImportCecilTests/Generic`1::Method(T)", method.FullName);
}
public class ContextGeneric1Method2<G1>
{
public G1 GenericMethod<R1, S1> (R1 r, S1 s)
{
return default (G1);
}
}
public class ContextGeneric2Method1<G2, H2>
{
public R2 GenericMethod<R2> (G2 g, H2 h)
{
return default (R2);
}
}
public class NestedGenericsA<A>
{
public class NestedGenericsB<B>
{
public class NestedGenericsC<C>
{
public A GenericMethod (B b, C c)
{
return default (A);
}
}
}
}
[Test]
public void ContextGenericTest ()
{
var module = ModuleDefinition.ReadModule (typeof (ContextGeneric1Method2<>).Module.FullyQualifiedName);
// by mixing open generics with 2 & 1 parameters, we make sure the right context is used (because otherwise, an exception will be thrown)
var type = typeof (ContextGeneric1Method2<>).MakeGenericType (typeof (ContextGeneric2Method1<,>));
var meth = type.GetMethod ("GenericMethod");
var imported_type = module.ImportReference (type);
var method = module.ImportReference (meth, imported_type);
Assert.AreEqual ("G1 Mono.Cecil.Tests.ImportCecilTests/ContextGeneric1Method2`1<Mono.Cecil.Tests.ImportCecilTests/ContextGeneric2Method1`2<G2,H2>>::GenericMethod<R1,S1>(R1,S1)", method.FullName);
// and the other way around
type = typeof (ContextGeneric2Method1<,>).MakeGenericType (typeof (ContextGeneric1Method2<>), typeof (IList<>));
meth = type.GetMethod ("GenericMethod");
imported_type = module.ImportReference (type);
method = module.ImportReference (meth, imported_type);
Assert.AreEqual ("R2 Mono.Cecil.Tests.ImportCecilTests/ContextGeneric2Method1`2<Mono.Cecil.Tests.ImportCecilTests/ContextGeneric1Method2`1<G1>,System.Collections.Generic.IList`1<T>>::GenericMethod<R2>(G2,H2)", method.FullName);
// not sure about this one
type = typeof (NestedGenericsA<string>.NestedGenericsB<int>.NestedGenericsC<float>);
meth = type.GetMethod ("GenericMethod");
imported_type = module.ImportReference (type);
method = module.ImportReference (meth, imported_type);
Assert.AreEqual ("A Mono.Cecil.Tests.ImportCecilTests/NestedGenericsA`1/NestedGenericsB`1/NestedGenericsC`1<System.String,System.Int32,System.Single>::GenericMethod(B,C)", method.FullName);
// We need both the method & type !
type = typeof (Generic<>).MakeGenericType (typeof (string));
meth = type.GetMethod ("ComplexGenericMethod");
imported_type = module.ImportReference (type);
method = module.ImportReference (meth, imported_type);
Assert.AreEqual ("Mono.Cecil.Tests.ImportCecilTests/Generic`1<TS> Mono.Cecil.Tests.ImportCecilTests/Generic`1<System.String>::ComplexGenericMethod<TS>(T,TS)", method.FullName);
}
delegate void Emitter (ModuleDefinition module, MethodBody body);
[MethodImpl (MethodImplOptions.NoInlining)]
static TDelegate Compile<TDelegate> (Emitter emitter)
where TDelegate : class
{
var name = GetTestCaseName ();
var module = CreateTestModule<TDelegate> (name, emitter);
var assembly = LoadTestModule (module);
return CreateRunDelegate<TDelegate> (GetTestCase (name, assembly));
}
static TDelegate CreateRunDelegate<TDelegate> (Type type)
where TDelegate : class
{
return (TDelegate) (object) Delegate.CreateDelegate (typeof (TDelegate), type.GetMethod ("Run"));
}
static Type GetTestCase (string name, SR.Assembly assembly)
{
return assembly.GetType (name);
}
static SR.Assembly LoadTestModule (ModuleDefinition module)
{
using (var stream = new MemoryStream ()) {
module.Write (stream);
File.WriteAllBytes (Path.Combine (Path.Combine (Path.GetTempPath (), "cecil"), module.Name + ".dll"), stream.ToArray ());
return SR.Assembly.Load (stream.ToArray ());
}
}
static ModuleDefinition CreateTestModule<TDelegate> (string name, Emitter emitter)
{
var module = CreateModule (name);
var type = new TypeDefinition (
"",
name,
TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract,
module.ImportReference (typeof (object)));
module.Types.Add (type);
var method = CreateMethod (type, typeof (TDelegate).GetMethod ("Invoke"));
emitter (module, method.Body);
return module;
}
static MethodDefinition CreateMethod (TypeDefinition type, SR.MethodInfo pattern)
{
var module = type.Module;
var method = new MethodDefinition {
Name = "Run",
IsPublic = true,
IsStatic = true,
};
type.Methods.Add (method);
method.MethodReturnType.ReturnType = module.ImportReference (pattern.ReturnType);
foreach (var parameter_pattern in pattern.GetParameters ())
method.Parameters.Add (new ParameterDefinition (module.ImportReference (parameter_pattern.ParameterType)));
return method;
}
static ModuleDefinition CreateModule (string name)
{
return ModuleDefinition.CreateModule (name, ModuleKind.Dll);
}
[MethodImpl (MethodImplOptions.NoInlining)]
static string GetTestCaseName ()
{
var stack_trace = new StackTrace ();
var stack_frame = stack_trace.GetFrame (2);
return "ImportCecil_" + stack_frame.GetMethod ().Name;
}
internal static T GenericMethod<T>(T[,] array)
{
return array[0,0];
}
[Test]
public void MethodContextGenericTest()
{
var module = ModuleDefinition.ReadModule(typeof(ContextGeneric1Method2<>).Module.FullyQualifiedName);
var type_def = GetType().ToDefinition();
var meth_def = type_def.GetMethod("GenericMethod");
var meth_ref = module.Import(meth_def);
var instr = meth_def.Body.Instructions.First(i => i.OpCode.OperandType == OperandType.InlineMethod);
var method = module.Import((MethodReference)instr.Operand, meth_ref);
Assert.AreEqual("T T[0...,0...]::Get(System.Int32,System.Int32)", method.FullName);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/check_in/reservation_check_in_notification.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 HOLMS.Types.Booking.CheckIn {
/// <summary>Holder for reflection information generated from booking/check_in/reservation_check_in_notification.proto</summary>
public static partial class ReservationCheckInNotificationReflection {
#region Descriptor
/// <summary>File descriptor for booking/check_in/reservation_check_in_notification.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ReservationCheckInNotificationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cjhib29raW5nL2NoZWNrX2luL3Jlc2VydmF0aW9uX2NoZWNrX2luX25vdGlm",
"aWNhdGlvbi5wcm90bxIcaG9sbXMudHlwZXMuYm9va2luZy5jaGVja19pbhou",
"Ym9va2luZy9pbmRpY2F0b3JzL3Jlc2VydmF0aW9uX2luZGljYXRvci5wcm90",
"bxodcHJpbWl0aXZlL3BiX2xvY2FsX2RhdGUucHJvdG8aIGNybS9ndWVzdHMv",
"Z3Vlc3RfaW5kaWNhdG9yLnByb3RvGh9wcmltaXRpdmUvbW9uZXRhcnlfYW1v",
"dW50LnByb3RvGiVvcGVyYXRpb25zL3Jvb21zL3Jvb21faW5kaWNhdG9yLnBy",
"b3RvIrQDCh5SZXNlcnZhdGlvbkNoZWNrSW5Ob3RpZmljYXRpb24SEQoJal93",
"X3Rva2VuGAEgASgJEkkKC3Jlc2VydmF0aW9uGAIgASgLMjQuaG9sbXMudHlw",
"ZXMuYm9va2luZy5pbmRpY2F0b3JzLlJlc2VydmF0aW9uSW5kaWNhdG9yEjkK",
"DWNoZWNrX2luX2RhdGUYAyABKAsyIi5ob2xtcy50eXBlcy5wcmltaXRpdmUu",
"UGJMb2NhbERhdGUSPAoHcm9vbV9pZBgEIAEoCzIrLmhvbG1zLnR5cGVzLm9w",
"ZXJhdGlvbnMucm9vbXMuUm9vbUluZGljYXRvchI4CghndWVzdF9pZBgFIAEo",
"CzImLmhvbG1zLnR5cGVzLmNybS5ndWVzdHMuR3Vlc3RJbmRpY2F0b3ISOwoM",
"YXZlcmFnZV9yYXRlGAYgASgLMiUuaG9sbXMudHlwZXMucHJpbWl0aXZlLk1v",
"bmV0YXJ5QW1vdW50EiIKGnJlc2VydmF0aW9uX2Jvb2tpbmdfbnVtYmVyGAcg",
"ASgJEiAKGGtlZXBfZ3VhcmFudGVlX3JlcXVlc3RlZBgIIAEoCEIvWg9ib29r",
"aW5nL2NoZWNraW6qAhtIT0xNUy5UeXBlcy5Cb29raW5nLkNoZWNrSW5iBnBy",
"b3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.CRM.Guests.GuestIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.CheckIn.ReservationCheckInNotification), global::HOLMS.Types.Booking.CheckIn.ReservationCheckInNotification.Parser, new[]{ "JWToken", "Reservation", "CheckInDate", "RoomId", "GuestId", "AverageRate", "ReservationBookingNumber", "KeepGuaranteeRequested" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ReservationCheckInNotification : pb::IMessage<ReservationCheckInNotification> {
private static readonly pb::MessageParser<ReservationCheckInNotification> _parser = new pb::MessageParser<ReservationCheckInNotification>(() => new ReservationCheckInNotification());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReservationCheckInNotification> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.CheckIn.ReservationCheckInNotificationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCheckInNotification() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCheckInNotification(ReservationCheckInNotification other) : this() {
jWToken_ = other.jWToken_;
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
CheckInDate = other.checkInDate_ != null ? other.CheckInDate.Clone() : null;
RoomId = other.roomId_ != null ? other.RoomId.Clone() : null;
GuestId = other.guestId_ != null ? other.GuestId.Clone() : null;
AverageRate = other.averageRate_ != null ? other.AverageRate.Clone() : null;
reservationBookingNumber_ = other.reservationBookingNumber_;
keepGuaranteeRequested_ = other.keepGuaranteeRequested_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCheckInNotification Clone() {
return new ReservationCheckInNotification(this);
}
/// <summary>Field number for the "j_w_token" field.</summary>
public const int JWTokenFieldNumber = 1;
private string jWToken_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JWToken {
get { return jWToken_; }
set {
jWToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 2;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "check_in_date" field.</summary>
public const int CheckInDateFieldNumber = 3;
private global::HOLMS.Types.Primitive.PbLocalDate checkInDate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate CheckInDate {
get { return checkInDate_; }
set {
checkInDate_ = value;
}
}
/// <summary>Field number for the "room_id" field.</summary>
public const int RoomIdFieldNumber = 4;
private global::HOLMS.Types.Operations.Rooms.RoomIndicator roomId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.Rooms.RoomIndicator RoomId {
get { return roomId_; }
set {
roomId_ = value;
}
}
/// <summary>Field number for the "guest_id" field.</summary>
public const int GuestIdFieldNumber = 5;
private global::HOLMS.Types.CRM.Guests.GuestIndicator guestId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.CRM.Guests.GuestIndicator GuestId {
get { return guestId_; }
set {
guestId_ = value;
}
}
/// <summary>Field number for the "average_rate" field.</summary>
public const int AverageRateFieldNumber = 6;
private global::HOLMS.Types.Primitive.MonetaryAmount averageRate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount AverageRate {
get { return averageRate_; }
set {
averageRate_ = value;
}
}
/// <summary>Field number for the "reservation_booking_number" field.</summary>
public const int ReservationBookingNumberFieldNumber = 7;
private string reservationBookingNumber_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ReservationBookingNumber {
get { return reservationBookingNumber_; }
set {
reservationBookingNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "keep_guarantee_requested" field.</summary>
public const int KeepGuaranteeRequestedFieldNumber = 8;
private bool keepGuaranteeRequested_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool KeepGuaranteeRequested {
get { return keepGuaranteeRequested_; }
set {
keepGuaranteeRequested_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReservationCheckInNotification);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReservationCheckInNotification other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (JWToken != other.JWToken) return false;
if (!object.Equals(Reservation, other.Reservation)) return false;
if (!object.Equals(CheckInDate, other.CheckInDate)) return false;
if (!object.Equals(RoomId, other.RoomId)) return false;
if (!object.Equals(GuestId, other.GuestId)) return false;
if (!object.Equals(AverageRate, other.AverageRate)) return false;
if (ReservationBookingNumber != other.ReservationBookingNumber) return false;
if (KeepGuaranteeRequested != other.KeepGuaranteeRequested) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (JWToken.Length != 0) hash ^= JWToken.GetHashCode();
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (checkInDate_ != null) hash ^= CheckInDate.GetHashCode();
if (roomId_ != null) hash ^= RoomId.GetHashCode();
if (guestId_ != null) hash ^= GuestId.GetHashCode();
if (averageRate_ != null) hash ^= AverageRate.GetHashCode();
if (ReservationBookingNumber.Length != 0) hash ^= ReservationBookingNumber.GetHashCode();
if (KeepGuaranteeRequested != false) hash ^= KeepGuaranteeRequested.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 (JWToken.Length != 0) {
output.WriteRawTag(10);
output.WriteString(JWToken);
}
if (reservation_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Reservation);
}
if (checkInDate_ != null) {
output.WriteRawTag(26);
output.WriteMessage(CheckInDate);
}
if (roomId_ != null) {
output.WriteRawTag(34);
output.WriteMessage(RoomId);
}
if (guestId_ != null) {
output.WriteRawTag(42);
output.WriteMessage(GuestId);
}
if (averageRate_ != null) {
output.WriteRawTag(50);
output.WriteMessage(AverageRate);
}
if (ReservationBookingNumber.Length != 0) {
output.WriteRawTag(58);
output.WriteString(ReservationBookingNumber);
}
if (KeepGuaranteeRequested != false) {
output.WriteRawTag(64);
output.WriteBool(KeepGuaranteeRequested);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (JWToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JWToken);
}
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (checkInDate_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(CheckInDate);
}
if (roomId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomId);
}
if (guestId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(GuestId);
}
if (averageRate_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(AverageRate);
}
if (ReservationBookingNumber.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ReservationBookingNumber);
}
if (KeepGuaranteeRequested != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReservationCheckInNotification other) {
if (other == null) {
return;
}
if (other.JWToken.Length != 0) {
JWToken = other.JWToken;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.checkInDate_ != null) {
if (checkInDate_ == null) {
checkInDate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
CheckInDate.MergeFrom(other.CheckInDate);
}
if (other.roomId_ != null) {
if (roomId_ == null) {
roomId_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator();
}
RoomId.MergeFrom(other.RoomId);
}
if (other.guestId_ != null) {
if (guestId_ == null) {
guestId_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator();
}
GuestId.MergeFrom(other.GuestId);
}
if (other.averageRate_ != null) {
if (averageRate_ == null) {
averageRate_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
AverageRate.MergeFrom(other.AverageRate);
}
if (other.ReservationBookingNumber.Length != 0) {
ReservationBookingNumber = other.ReservationBookingNumber;
}
if (other.KeepGuaranteeRequested != false) {
KeepGuaranteeRequested = other.KeepGuaranteeRequested;
}
}
[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: {
JWToken = input.ReadString();
break;
}
case 18: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 26: {
if (checkInDate_ == null) {
checkInDate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(checkInDate_);
break;
}
case 34: {
if (roomId_ == null) {
roomId_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator();
}
input.ReadMessage(roomId_);
break;
}
case 42: {
if (guestId_ == null) {
guestId_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator();
}
input.ReadMessage(guestId_);
break;
}
case 50: {
if (averageRate_ == null) {
averageRate_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(averageRate_);
break;
}
case 58: {
ReservationBookingNumber = input.ReadString();
break;
}
case 64: {
KeepGuaranteeRequested = input.ReadBool();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
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 _1._4.SPA.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;
}
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// Validation attribute that executes a user-supplied method at runtime, using one of these signatures:
/// <para>
/// public static <see cref="ValidationResult" /> Method(object value) { ... }
/// </para>
/// <para>
/// public static <see cref="ValidationResult" /> Method(object value, <see cref="ValidationContext" /> context) {
/// ... }
/// </para>
/// <para>
/// The value can be strongly typed as type conversion will be attempted.
/// </para>
/// </summary>
/// <remarks>
/// This validation attribute is used to invoke custom logic to perform validation at runtime.
/// Like any other <see cref="ValidationAttribute" />, its <see cref="IsValid(object, ValidationContext)" />
/// method is invoked to perform validation. This implementation simply redirects that call to the method
/// identified by <see cref="Method" /> on a type identified by <see cref="ValidatorType" />
/// <para>
/// The supplied <see cref="ValidatorType" /> cannot be null, and it must be a public type.
/// </para>
/// <para>
/// The named <see cref="Method" /> must be public, static, return <see cref="ValidationResult" /> and take at
/// least one input parameter for the value to be validated. This value parameter may be strongly typed.
/// Type conversion will be attempted if clients pass in a value of a different type.
/// </para>
/// <para>
/// The <see cref="Method" /> may also declare an additional parameter of type <see cref="ValidationContext" />.
/// The <see cref="ValidationContext" /> parameter provides additional context the method may use to determine
/// the context in which it is being used.
/// </para>
/// <para>
/// If the method returns <see cref="ValidationResult" />.<see cref="ValidationResult.Success" />, that indicates
/// the given value is acceptable and validation passed.
/// Returning an instance of <see cref="ValidationResult" /> indicates that the value is not acceptable
/// and validation failed.
/// </para>
/// <para>
/// If the method returns a <see cref="ValidationResult" /> with a <c>null</c>
/// <see cref="ValidationResult.ErrorMessage" />
/// then the normal <see cref="ValidationAttribute.FormatErrorMessage" /> method will be called to compose the
/// error message.
/// </para>
/// </remarks>
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method |
AttributeTargets.Parameter, AllowMultiple = true)]
public sealed class CustomValidationAttribute : ValidationAttribute
{
#region Member Fields
private readonly Lazy<string> _malformedErrorMessage;
private bool _isSingleArgumentMethod;
private string _lastMessage;
private MethodInfo _methodInfo;
private Type _firstParameterType;
#endregion
#region All Constructors
/// <summary>
/// Instantiates a custom validation attribute that will invoke a method in the
/// specified type.
/// </summary>
/// <remarks>
/// An invalid <paramref name="validatorType" /> or <paramref name="method" /> will be cause
/// <see cref="IsValid(object, ValidationContext)" />> to return a <see cref="ValidationResult" />
/// and <see cref="ValidationAttribute.FormatErrorMessage" /> to return a summary error message.
/// </remarks>
/// <param name="validatorType">
/// The type that will contain the method to invoke. It cannot be null. See
/// <see cref="Method" />.
/// </param>
/// <param name="method">The name of the method to invoke in <paramref name="validatorType" />.</param>
public CustomValidationAttribute(Type validatorType, string method)
: base(() => SR.CustomValidationAttribute_ValidationError)
{
ValidatorType = validatorType;
Method = method;
_malformedErrorMessage = new Lazy<string>(CheckAttributeWellFormed);
}
#endregion
#region Properties
/// <summary>
/// Gets the type that contains the validation method identified by <see cref="Method" />.
/// </summary>
public Type ValidatorType { get; }
/// <summary>
/// Gets the name of the method in <see cref="ValidatorType" /> to invoke to perform validation.
/// </summary>
public string Method { get; }
public override bool RequiresValidationContext
{
get
{
// If attribute is not valid, throw an exception right away to inform the developer
ThrowIfAttributeNotWellFormed();
// We should return true when 2-parameter form of the validation method is used
return !_isSingleArgumentMethod;
}
}
#endregion
/// <summary>
/// Override of validation method. See <see cref="ValidationAttribute.IsValid(object, ValidationContext)" />.
/// </summary>
/// <param name="value">The value to validate.</param>
/// <param name="validationContext">
/// A <see cref="ValidationContext" /> instance that provides
/// context about the validation operation, such as the object and member being validated.
/// </param>
/// <returns>Whatever the <see cref="Method" /> in <see cref="ValidatorType" /> returns.</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// If attribute is not valid, throw an exception right away to inform the developer
ThrowIfAttributeNotWellFormed();
var methodInfo = _methodInfo;
// If the value is not of the correct type and cannot be converted, fail
// to indicate it is not acceptable. The convention is that IsValid is merely a probe,
// and clients are not expecting exceptions.
object convertedValue;
if (!TryConvertValue(value, out convertedValue))
{
return new ValidationResult(SR.Format(SR.CustomValidationAttribute_Type_Conversion_Failed,
(value != null ? value.GetType().ToString() : "null"),
_firstParameterType,
ValidatorType,
Method));
}
// Invoke the method. Catch TargetInvocationException merely to unwrap it.
// Callers don't know Reflection is being used and will not typically see
// the real exception
try
{
// 1-parameter form is ValidationResult Method(object value)
// 2-parameter form is ValidationResult Method(object value, ValidationContext context),
var methodParams = _isSingleArgumentMethod
? new object[] { convertedValue }
: new[] { convertedValue, validationContext };
var result = (ValidationResult)methodInfo.Invoke(null, methodParams);
// We capture the message they provide us only in the event of failure,
// otherwise we use the normal message supplied via the ctor
_lastMessage = null;
if (result != null)
{
_lastMessage = result.ErrorMessage;
}
return result;
}
catch (TargetInvocationException tie)
{
throw tie.InnerException;
}
}
/// <summary>
/// Override of <see cref="ValidationAttribute.FormatErrorMessage" />
/// </summary>
/// <param name="name">The name to include in the formatted string</param>
/// <returns>A localized string to describe the problem.</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
public override string FormatErrorMessage(string name)
{
// If attribute is not valid, throw an exception right away to inform the developer
ThrowIfAttributeNotWellFormed();
if (!string.IsNullOrEmpty(_lastMessage))
{
return string.Format(CultureInfo.CurrentCulture, _lastMessage, name);
}
// If success or they supplied no custom message, use normal base class behavior
return base.FormatErrorMessage(name);
}
/// <summary>
/// Checks whether the current attribute instance itself is valid for use.
/// </summary>
/// <returns>The error message why it is not well-formed, null if it is well-formed.</returns>
private string CheckAttributeWellFormed() => ValidateValidatorTypeParameter() ?? ValidateMethodParameter();
/// <summary>
/// Internal helper to determine whether <see cref="ValidatorType" /> is legal for use.
/// </summary>
/// <returns><c>null</c> or the appropriate error message.</returns>
private string ValidateValidatorTypeParameter()
{
if (ValidatorType == null)
{
return SR.CustomValidationAttribute_ValidatorType_Required;
}
if (!ValidatorType.IsVisible)
{
return SR.Format(SR.CustomValidationAttribute_Type_Must_Be_Public, ValidatorType.Name);
}
return null;
}
/// <summary>
/// Internal helper to determine whether <see cref="Method" /> is legal for use.
/// </summary>
/// <returns><c>null</c> or the appropriate error message.</returns>
private string ValidateMethodParameter()
{
if (string.IsNullOrEmpty(Method))
{
return SR.CustomValidationAttribute_Method_Required;
}
// Named method must be public and static
var methodInfo = ValidatorType.GetRuntimeMethods()
.SingleOrDefault(m => string.Equals(m.Name, Method, StringComparison.Ordinal)
&& m.IsPublic && m.IsStatic);
if (methodInfo == null)
{
return SR.Format(SR.CustomValidationAttribute_Method_Not_Found, Method, ValidatorType.Name);
}
// Method must return a ValidationResult or derived class
if (!typeof(ValidationResult).IsAssignableFrom(methodInfo.ReturnType))
{
return SR.Format(SR.CustomValidationAttribute_Method_Must_Return_ValidationResult, Method, ValidatorType.Name);
}
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
// Must declare at least one input parameter for the value and it cannot be ByRef
if (parameterInfos.Length == 0 || parameterInfos[0].ParameterType.IsByRef)
{
return SR.Format(SR.CustomValidationAttribute_Method_Signature, Method, ValidatorType.Name);
}
// We accept 2 forms:
// 1-parameter form is ValidationResult Method(object value)
// 2-parameter form is ValidationResult Method(object value, ValidationContext context),
_isSingleArgumentMethod = (parameterInfos.Length == 1);
if (!_isSingleArgumentMethod)
{
if ((parameterInfos.Length != 2) || (parameterInfos[1].ParameterType != typeof(ValidationContext)))
{
return SR.Format(SR.CustomValidationAttribute_Method_Signature, Method, ValidatorType.Name);
}
}
_methodInfo = methodInfo;
_firstParameterType = parameterInfos[0].ParameterType;
return null;
}
/// <summary>
/// Throws InvalidOperationException if the attribute is not valid.
/// </summary>
private void ThrowIfAttributeNotWellFormed()
{
string errorMessage = _malformedErrorMessage.Value;
if (errorMessage != null)
{
throw new InvalidOperationException(errorMessage);
}
}
/// <summary>
/// Attempts to convert the given value to the type needed to invoke the method for the current
/// CustomValidationAttribute.
/// </summary>
/// <param name="value">The value to check/convert.</param>
/// <param name="convertedValue">If successful, the converted (or copied) value.</param>
/// <returns><c>true</c> if type value was already correct or was successfully converted.</returns>
private bool TryConvertValue(object value, out object convertedValue)
{
convertedValue = null;
var expectedValueType = _firstParameterType;
// Null is permitted for reference types or for Nullable<>'s only
if (value == null)
{
if (expectedValueType.IsValueType
&& (!expectedValueType.IsGenericType
|| expectedValueType.GetGenericTypeDefinition() != typeof(Nullable<>)))
{
return false;
}
return true; // convertedValue already null, which is correct for this case
}
// If the type is already legally assignable, we're good
if (expectedValueType.IsInstanceOfType(value))
{
convertedValue = value;
return true;
}
// Value is not the right type -- attempt a convert.
// Any expected exception returns a false
try
{
convertedValue = Convert.ChangeType(value, expectedValueType, CultureInfo.CurrentCulture);
return true;
}
catch (FormatException)
{
return false;
}
catch (InvalidCastException)
{
return false;
}
catch (NotSupportedException)
{
return false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableQueueTest : SimpleElementImmutablesTestBase
{
private void EnqueueDequeueTestHelper<T>(params T[] items)
{
Assert.NotNull(items);
var queue = ImmutableQueue<T>.Empty;
int i = 0;
foreach (T item in items)
{
var nextQueue = queue.Enqueue(item);
Assert.NotSame(queue, nextQueue); //, "Enqueue returned this instead of a new instance.");
Assert.Equal(i, queue.Count()); //, "Enqueue mutated the queue.");
Assert.Equal(++i, nextQueue.Count());
queue = nextQueue;
}
i = 0;
foreach (T element in queue)
{
AssertAreSame(items[i++], element);
}
i = 0;
foreach (T element in (System.Collections.IEnumerable)queue)
{
AssertAreSame(items[i++], element);
}
i = items.Length;
foreach (T expectedItem in items)
{
T actualItem = queue.Peek();
AssertAreSame(expectedItem, actualItem);
var nextQueue = queue.Dequeue();
Assert.NotSame(queue, nextQueue); //, "Dequeue returned this instead of a new instance.");
Assert.Equal(i, queue.Count());
Assert.Equal(--i, nextQueue.Count());
queue = nextQueue;
}
}
[Fact]
public void EnumerationOrder()
{
var queue = ImmutableQueue<int>.Empty;
// Push elements onto the backwards stack.
queue = queue.Enqueue(1).Enqueue(2).Enqueue(3);
Assert.Equal(1, queue.Peek());
// Force the backwards stack to be reversed and put into forwards.
queue = queue.Dequeue();
// Push elements onto the backwards stack again.
queue = queue.Enqueue(4).Enqueue(5);
// Now that we have some elements on the forwards and backwards stack,
// 1. enumerate all elements to verify order.
Assert.Equal<int>(new[] { 2, 3, 4, 5 }, queue.ToArray());
// 2. dequeue all elements to verify order
var actual = new int[queue.Count()];
for (int i = 0; i < actual.Length; i++)
{
actual[i] = queue.Peek();
queue = queue.Dequeue();
}
}
[Fact]
public void GetEnumeratorText()
{
var queue = ImmutableQueue.Create(5);
var enumeratorStruct = queue.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
Assert.True(enumeratorStruct.MoveNext());
Assert.Equal(5, enumeratorStruct.Current);
Assert.False(enumeratorStruct.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
var enumerator = ((IEnumerable<int>)queue).GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var queue = ImmutableQueue.Create(5);
var enumerator = ((IEnumerable<int>)queue).GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
// As pure structs with no disposable reference types inside it,
// we have nothing to track across struct copies, and this just works.
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = ((IEnumerable<int>)queue).GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(queue.Peek(), enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void EnqueueDequeueTest()
{
this.EnqueueDequeueTestHelper(new GenericParameterHelper(1), new GenericParameterHelper(2), new GenericParameterHelper(3));
this.EnqueueDequeueTestHelper<GenericParameterHelper>();
// interface test
IImmutableQueue<GenericParameterHelper> queueInterface = ImmutableQueue.Create<GenericParameterHelper>();
IImmutableQueue<GenericParameterHelper> populatedQueueInterface = queueInterface.Enqueue(new GenericParameterHelper(5));
Assert.Equal(new GenericParameterHelper(5), populatedQueueInterface.Peek());
}
[Fact]
public void DequeueOutValue()
{
var queue = ImmutableQueue<int>.Empty.Enqueue(5).Enqueue(6);
int head;
queue = queue.Dequeue(out head);
Assert.Equal(5, head);
var emptyQueue = queue.Dequeue(out head);
Assert.Equal(6, head);
Assert.True(emptyQueue.IsEmpty);
// Also check that the interface extension method works.
IImmutableQueue<int> interfaceQueue = queue;
Assert.Same(emptyQueue, interfaceQueue.Dequeue(out head));
Assert.Equal(6, head);
}
[Fact]
public void ClearTest()
{
var emptyQueue = ImmutableQueue.Create<GenericParameterHelper>();
AssertAreSame(emptyQueue, emptyQueue.Clear());
var nonEmptyQueue = emptyQueue.Enqueue(new GenericParameterHelper(3));
AssertAreSame(emptyQueue, nonEmptyQueue.Clear());
// Interface test
IImmutableQueue<GenericParameterHelper> queueInterface = nonEmptyQueue;
AssertAreSame(emptyQueue, queueInterface.Clear());
}
[Fact]
public void EqualsTest()
{
Assert.False(ImmutableQueue<int>.Empty.Equals(null));
Assert.False(ImmutableQueue<int>.Empty.Equals("hi"));
Assert.True(ImmutableQueue<int>.Empty.Equals(ImmutableQueue<int>.Empty));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(5).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(5).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Equals(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(5)));
// Also be sure to compare equality of partially dequeued queues since that moves data to different fields.
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(1).Enqueue(2).Dequeue().Equals(ImmutableQueue<int>.Empty.Enqueue(1).Enqueue(2)));
}
[Fact]
public void PeekEmptyThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableQueue<GenericParameterHelper>.Empty.Peek());
}
[Fact]
public void DequeueEmptyThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableQueue<GenericParameterHelper>.Empty.Dequeue());
}
[Fact]
public void Create()
{
ImmutableQueue<int> queue = ImmutableQueue.Create<int>();
Assert.True(queue.IsEmpty);
queue = ImmutableQueue.Create(1);
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1 }, queue);
queue = ImmutableQueue.Create(1, 2);
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1, 2 }, queue);
queue = ImmutableQueue.CreateRange((IEnumerable<int>)new[] { 1, 2 });
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1, 2 }, queue);
queue = ImmutableQueue.CreateRange(new List<int> { 1, 2 });
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1, 2 }, queue);
AssertExtensions.Throws<ArgumentNullException>("items", () => ImmutableQueue.CreateRange((IEnumerable<int>)null));
AssertExtensions.Throws<ArgumentNullException>("items", () => ImmutableQueue.Create((int[])null));
}
[Fact]
public void Empty()
{
// We already test Create(), so just prove that Empty has the same effect.
Assert.Same(ImmutableQueue.Create<int>(), ImmutableQueue<int>.Empty);
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableQueue.Create<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableQueue.Create<string>());
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
var queue = ImmutableQueue<T>.Empty;
foreach (var item in contents)
{
queue = queue.Enqueue(item);
}
return queue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using SIL.PlatformUtilities;
using static System.Char;
namespace SIL.Extensions
{
public static class StringExtensions
{
public const char kObjReplacementChar = '\uFFFC';
public static List<string> SplitTrimmed(this string s, char separator)
{
if (s.Trim() == string.Empty)
return new List<string>();
var x = s.Split(separator);
var r = new List<string>();
foreach (var part in x)
{
var trim = part.Trim();
if (trim != string.Empty)
{
r.Add(trim);
}
}
return r;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets an int array from a comma-delimited string of numbers.
/// </summary>
/// ------------------------------------------------------------------------------------
public static int[] ToIntArray(this string str)
{
List<int> array = new List<int>();
if (str != null)
{
string[] pieces = str.Split(',');
foreach (string piece in pieces)
{
int i;
if (int.TryParse(piece, out i))
array.Add(i);
}
}
return array.ToArray();
}
/// <summary>
/// normal string.format will throw if it can't do the format; this is dangerous if you're, for example
/// just logging stuff that might contain messed up strings (myWorkSafe paths)
/// </summary>
public static string FormatWithErrorStringInsteadOfException(this string format, params object[] args)
{
try
{
if (args.Length == 0)
return format;
else
return string.Format(format, args);
}
catch (Exception e)
{
string argList = "";
foreach (var arg in args)
{
argList = argList + arg + ",";
}
argList = argList.Trim(new char[] {','});
return "FormatWithErrorStringInsteadOfException(" + format + "," + argList + ") Exception: " + e.Message;
}
}
public static string EscapeAnyUnicodeCharactersIllegalInXml(this string text)
{
//we actually want to preserve html markup, just escape the disallowed unicode characters
text = text.Replace("<", "_lt;");
text = text.Replace(">", "_gt;");
text = text.Replace("&", "_amp;");
text = text.Replace("\"", "_quot;");
text = text.Replace("'", "_apos;");
text = EscapeSoXmlSeesAsPureTextAndEscapeCharactersIllegalInXml(text);
//put it back, now
text = text.Replace("_lt;", "<");
text = text.Replace("_gt;", ">");
text = text.Replace("_amp;", "&");
text = text.Replace("_quot;", "\"");
text = text.Replace("_apos;", "'");
// Also ensure NFC form for XML output.
return text.Normalize(NormalizationForm.FormC);
}
private static object _lockUsedForEscaping = new object();
private static StringBuilder _bldrUsedForEscaping;
private static XmlWriterSettings _settingsUsedForEscaping;
private static XmlWriter _writerUsedForEscaping;
public static string EscapeSoXmlSeesAsPureTextAndEscapeCharactersIllegalInXml(this string text)
{
lock (_lockUsedForEscaping)
{
if (_bldrUsedForEscaping == null)
_bldrUsedForEscaping = new StringBuilder();
else
_bldrUsedForEscaping.Clear();
if (_settingsUsedForEscaping == null)
{
_settingsUsedForEscaping = new XmlWriterSettings();
_settingsUsedForEscaping.NewLineHandling = NewLineHandling.None; // don't fiddle with newlines
_settingsUsedForEscaping.ConformanceLevel = ConformanceLevel.Fragment; // allow just text by itself
_settingsUsedForEscaping.CheckCharacters = false; // allow invalid characters in
}
if (_writerUsedForEscaping == null)
_writerUsedForEscaping = XmlWriter.Create(_bldrUsedForEscaping, _settingsUsedForEscaping);
_writerUsedForEscaping.WriteString(text);
_writerUsedForEscaping.Flush();
return _bldrUsedForEscaping.ToString();
}
}
/// <summary>
/// Similar to Path.Combine, but it combines as may parts as you have into a single, platform-appropriate path.
/// </summary>
/// <example> string path = "my".Combine("stuff", "toys", "ball.txt")</example>
public static string CombineForPath(this string rootPath, params string[] partsOfThePath)
{
string result = rootPath;
foreach (var s in partsOfThePath)
{
result = Path.Combine(result, s);
}
return result;
}
/// <summary>
/// Finds and replaces invalid characters in a filename
/// </summary>
/// <param name="input">the string to clean</param>
/// <param name="errorChar">the character which replaces bad characters</param>
/// <param name="replaceNbsp">Flag indicating whether to replace non-breaking spaces with
/// normal spaces</param>
public static string SanitizeFilename(this string input, char errorChar, bool replaceNbsp)
{
var invalidFilenameChars = Path.GetInvalidFileNameChars();
Array.Sort(invalidFilenameChars);
return Sanitize(input, invalidFilenameChars, errorChar, replaceNbsp, false);
}
// ENHANCE: Make versions of these methods that can guarantee a file/path that would be
// valid across all known/likely operating systems to ensure better portability.
/// <summary>
/// Finds and replaces invalid characters in a filename
/// </summary>
/// <param name="input">the string to clean</param>
/// <param name="errorChar">the character which replaces bad characters</param>
/// <remarks>This is platform-specific.</remarks>
public static string SanitizeFilename(this string input, char errorChar) =>
SanitizeFilename(input, errorChar, false);
/// <summary>
/// Finds and replaces invalid characters in a path
/// </summary>
/// <param name="input">the string to clean</param>
/// <param name="errorChar">the character which replaces bad characters</param>
public static string SanitizePath(this string input, char errorChar)
{
var invalidPathChars = Path.GetInvalidPathChars();
Array.Sort(invalidPathChars);
var sanitized = Sanitize(input, invalidPathChars, errorChar, false, true);
if (Platform.IsWindows)
{
sanitized = Regex.Replace(sanitized, "^(:)(.*)", $"{errorChar}$3");
sanitized = Regex.Replace(sanitized, "^([^a-zA-Z])(:)(.*)", $"$1{errorChar}$3");
sanitized = new String(sanitized.Take(2).ToArray()) + new String(sanitized.Skip(2).ToArray()).Replace(':', errorChar);
}
return sanitized;
}
private static string Sanitize(string input, char[] invalidChars, char errorChar, bool replaceNbsp,
bool allowTrailingUpHierarchyDots)
{
// Caller ensures invalidChars is sorted, so we can use a binary search, which should be lightning fast.
// null always sanitizes to null
if (input == null)
{
return null;
}
if (Array.BinarySearch(invalidChars, errorChar) >= 0)
throw new ArgumentException("The character used to replace bad characters must not itself be an invalid character.", nameof(errorChar));
var result = new StringBuilder();
foreach (var characterToTest in input)
{
if (Array.BinarySearch(invalidChars, characterToTest) >= 0 ||
characterToTest < ' ' || // eliminate all control characters
// Apparently Windows allows the ORC in *some* positions in filenames, but
// that can't be good, so we'll replace that too.
characterToTest == '\uFFFC')
{
if (result.Length > 0 || errorChar != ' ')
result.Append(errorChar);
}
else if (result.Length > 0 || !characterToTest.IsInvalidFilenameLeadingOrTrailingSpaceChar())
{
result.Append((replaceNbsp && characterToTest == '\u00A0') ? ' ' : characterToTest);
}
}
var lastCharPos = result.Length - 1;
while (lastCharPos >= 0)
{
var lastChar = result[lastCharPos];
if ((lastChar == '.' && (!allowTrailingUpHierarchyDots ||
!TrailingDotIsValidHierarchySpecifier(result, lastCharPos))) ||
lastChar.IsInvalidFilenameLeadingOrTrailingSpaceChar())
{
if (!IsWhiteSpace(lastChar))
{
// Once we've stripped off anything besides whitespace, we
// can't legitimately treat any remaining trailing dots as
// valid hierarchy specifiers.
allowTrailingUpHierarchyDots = false;
}
result.Remove(lastCharPos, 1);
lastCharPos--;
}
else
break;
}
return result.Length == 0 ? errorChar.ToString() : result.ToString();
}
private static bool TrailingDotIsValidHierarchySpecifier(StringBuilder result, int lastCharPos)
{
Debug.Assert(lastCharPos == result.Length - 1 && result[lastCharPos] == '.');
if (lastCharPos == 0)
{
// REVIEW: This is an iffy case. Technically, a single dot is a valid path,
// referring to the current directory, though it's not likely to be
// useful. If the caller wants that, they could just not specify anything.
return true;
}
if (result[lastCharPos - 1] == '.')
{
// This is a probably a valid up-one-level specifier.
if (lastCharPos == 1 ||
result[lastCharPos - 2] == Path.DirectorySeparatorChar ||
result[lastCharPos - 2] == Path.AltDirectorySeparatorChar)
return true;
}
return false;
}
/// <summary>
/// In addition to all the "normal" space characters covered by Char.IsWhitespace, this
/// also returns true for certain formatting characters which have no visible effect on
/// a string when used as a leading or trailing character and would likely be confusing
/// if allowed at the start or end of a filename.
/// </summary>
/// <remarks>Originally, I implemented the second check as
/// GetUnicodeCategory(c) == UnicodeCategory.Format, but this seemed to be too aggressive
/// since significant formatting marks such as those used to control bidi text could be
/// removed.
/// </remarks>
private static bool IsInvalidFilenameLeadingOrTrailingSpaceChar(this char c) =>
IsWhiteSpace(c) || c == '\uFEFF' || c == '\u200B' || c == '\u200C' || c == '\u200D';
/// <summary>
/// Make the first letter of the string upper-case, and the rest lower case. Does not consider words.
/// </summary>
public static string ToUpperFirstLetter(this string source)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
var letters = source.ToLowerInvariant().ToCharArray();
letters[0] = ToUpperInvariant(letters[0]);
return new string(letters);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Removes the ampersand accelerator prefix from the specified text.
/// </summary>
/// ------------------------------------------------------------------------------------
public static string RemoveAcceleratorPrefix(this string text)
{
text = text.Replace("&&", kObjReplacementChar.ToString(CultureInfo.InvariantCulture));
text = text.Replace("&", string.Empty);
return text.Replace(kObjReplacementChar.ToString(CultureInfo.InvariantCulture), "&");
}
/// <summary>
/// Trims the string, and returns null if the result is zero length
/// </summary>
/// <param name="value"></param>
/// <param name="trimChars"></param>
/// <returns></returns>
public static string NullTrim(this string value, char[] trimChars)
{
if (string.IsNullOrEmpty(value))
return null;
value = value.Trim(trimChars);
return string.IsNullOrEmpty(value) ? null : value;
}
/// <summary>
/// Trims the string, and returns null if the result is zero length
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string NullTrim(this string value)
{
return value.NullTrim(null);
}
/// <summary>
/// Determines whether the string contains the specified string using the specified comparison.
/// </summary>
public static bool Contains(this String stringToSearch, String stringToFind, StringComparison comparison)
{
int ind = stringToSearch.IndexOf(stringToFind, comparison); //This comparer should be extended to be "-"/"_" insensitive as well.
return ind != -1;
}
/// <summary>
/// Determines whether the list of string contains the specified string using the specified comparison.
/// </summary>
public static bool Contains(this IEnumerable<string> listToSearch, string itemToFind, StringComparison comparison)
{
foreach (string s in listToSearch)
{
if (s.Equals(itemToFind, comparison))
{
return true;
}
}
return false;
}
/// <summary>
/// Removes diacritics from the specified string
/// </summary>
public static string RemoveDiacritics(this string stIn)
{
string stFormD = stIn.Normalize(NormalizationForm.FormD);
StringBuilder sb = new StringBuilder();
foreach (char t in stFormD)
{
UnicodeCategory uc = GetUnicodeCategory(t);
if (uc != UnicodeCategory.NonSpacingMark)
sb.Append(t);
}
return sb.ToString().Normalize(NormalizationForm.FormC);
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Summary description for PlatformHelperTests.
/// </summary>
[TestFixture]
public class PlatformDetectionTests
{
private static readonly PlatformHelper win95Helper = new PlatformHelper(
new OSPlatform( PlatformID.Win32Windows , new Version( 4, 0 ) ),
new RuntimeFramework( RuntimeType.NetFramework, new Version( 1, 1, 4322, 0 ) ) );
private static readonly PlatformHelper winXPHelper = new PlatformHelper(
new OSPlatform( PlatformID.Win32NT , new Version( 5,1 ) ),
new RuntimeFramework( RuntimeType.NetFramework, new Version( 1, 1, 4322, 0 ) ) );
private void CheckOSPlatforms( OSPlatform os,
string expectedPlatforms )
{
Assert.That(expectedPlatforms, Is.SubsetOf(PlatformHelper.OSPlatforms).IgnoreCase,
"Error in test: one or more expected platforms is not a valid OSPlatform.");
CheckPlatforms(
new PlatformHelper( os, RuntimeFramework.CurrentFramework ),
expectedPlatforms,
PlatformHelper.OSPlatforms );
}
private void CheckRuntimePlatforms( RuntimeFramework runtimeFramework,
string expectedPlatforms )
{
CheckPlatforms(
new PlatformHelper( OSPlatform.CurrentPlatform, runtimeFramework ),
expectedPlatforms,
PlatformHelper.RuntimePlatforms + ",NET-1.0,NET-1.1,NET-2.0,NET-3.0,NET-3.5,NET-4.0,NET-4.5,MONO-1.0,MONO-2.0,MONO-3.0,MONO-3.5,MONO-4.0,MONOTOUCH");
}
private void CheckPlatforms( PlatformHelper helper,
string expectedPlatforms, string checkPlatforms )
{
string[] expected = expectedPlatforms.Split( new char[] { ',' } );
string[] check = checkPlatforms.Split( new char[] { ',' } );
foreach( string testPlatform in check )
{
bool shouldPass = false;
foreach( string platform in expected )
if ( shouldPass = platform.ToLower() == testPlatform.ToLower() )
break;
bool didPass = helper.IsPlatformSupported( testPlatform );
if ( shouldPass && !didPass )
Assert.Fail( "Failed to detect {0}", testPlatform );
else if ( didPass && !shouldPass )
Assert.Fail( "False positive on {0}", testPlatform );
else if ( !shouldPass && !didPass )
Assert.AreEqual( "Only supported on " + testPlatform, helper.Reason );
}
}
[Test]
public void DetectWin95()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 0 ) ),
"Win95,Win32Windows,Win32,Win" );
}
[Test]
public void DetectWin98()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 10 ) ),
"Win98,Win32Windows,Win32,Win" );
}
[Test]
public void DetectWinMe()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 90 ) ),
"WinMe,Win32Windows,Win32,Win" );
}
[Test]
public void DetectNT3()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 3, 51 ) ),
"NT3,Win32NT,Win32,Win" );
}
[Test]
public void DetectNT4()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 4, 0 ) ),
"NT4,Win32NT,Win32,Win" );
}
[Test]
public void DetectWin2K()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 0 ) ),
"Win2K,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWinXP()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 1 ) ),
"WinXP,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWinXPProfessionalX64()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 2 ), OSPlatform.ProductType.WorkStation ),
"WinXP,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWin2003Server()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(5, 2), OSPlatform.ProductType.Server),
"Win2003Server,NT5,Win32NT,Win32,Win");
}
[Test]
public void DetectVista()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.WorkStation),
"Vista,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWin2008ServerOriginal()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.Server),
"Win2008Server,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWin2008ServerR2()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.Server),
"Win2008Server,Win2008ServerR2,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows7()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.WorkStation),
"Win7,Windows7,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows2012ServerOriginal()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.Server),
"Win2012Server,Win2012ServerR1,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows2012ServerR2()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.Server),
"Win2012Server,Win2012ServerR2,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows8()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.WorkStation),
"Win8,Windows8,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows81()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.WorkStation),
"Win8.1,Windows8.1,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows10()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.WorkStation),
"Win10,Windows10,Win32NT,Win32,Win");
}
[Test]
public void DetectWindowsServer()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.Server),
"WindowsServer10,Win32NT,Win32,Win");
}
[Test]
public void DetectUnixUnderMicrosoftDotNet()
{
CheckOSPlatforms(
new OSPlatform(OSPlatform.UnixPlatformID_Microsoft, new Version(0,0)),
"UNIX,Linux");
}
[Test]
public void DetectUnixUnderMono()
{
CheckOSPlatforms(
new OSPlatform(OSPlatform.UnixPlatformID_Mono, new Version(0,0)),
"UNIX,Linux");
}
[Test]
public void DetectXbox()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Xbox, new Version(0, 0)),
"Xbox");
}
[Test]
public void DetectMacOSX()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.MacOSX, new Version(0, 0)),
"MacOSX");
}
[Test]
public void DetectNet35()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.NetFramework, new Version(3, 5)),
"Net,Net-2.0,Net-3.0,Net-3.5");
}
[Test]
public void DetectNet40()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.NetFramework, new Version(4, 0, 30319, 0)),
"Net,Net-4.0");
}
[Test]
public void DetectNet45()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.NetFramework, new Version(4, 5, 0, 0)),
"Net,Net-4.0,Net-4.5");
}
[Test]
public void DetectSSCLI()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.SSCLI, new Version( 1, 0, 3, 0 ) ),
"SSCLI,Rotor" );
}
[Test]
public void DetectMono10()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Mono, new Version( 1, 1, 4322, 0 ) ),
"Mono,Mono-1.0" );
}
[Test]
public void DetectMono20()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Mono, new Version( 2, 0, 50727, 0 ) ),
"Mono,Mono-2.0" );
}
[Test]
public void DetectMono30()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(3, 0)),
"Mono,Mono-2.0,Mono-3.0");
}
[Test]
public void DetectMono35()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(3, 5)),
"Mono,Mono-2.0,Mono-3.0,Mono-3.5");
}
[Test]
public void DetectMono40()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)),
"Mono,Mono-4.0");
}
[Test]
public void DetectMonoTouch()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.MonoTouch, new Version(4, 0, 30319)),
"MonoTouch");
}
[Test]
public void DetectNetCore()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.NetCore, new Version(0, 0, 0)),
"NetCore");
}
[Test]
public void DetectExactVersion()
{
Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322" ) );
Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322.0" ) );
Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4323.0" ) );
Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4322.1" ) );
}
[Test]
public void ArrayOfPlatforms()
{
string[] platforms = new string[] { "NT4", "Win2K", "WinXP" };
Assert.IsTrue( winXPHelper.IsPlatformSupported( platforms ) );
Assert.IsFalse( win95Helper.IsPlatformSupported( platforms ) );
}
[Test]
public void PlatformAttribute_Include()
{
PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual("Only supported on Win2K,WinXP,NT4", win95Helper.Reason);
}
[Test]
public void PlatformAttribute_Exclude()
{
PlatformAttribute attr = new PlatformAttribute();
attr.Exclude = "Win2K,WinXP,NT4";
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Not supported on Win2K,WinXP,NT4", winXPHelper.Reason );
Assert.IsTrue( win95Helper.IsPlatformSupported( attr ) );
}
[Test]
public void PlatformAttribute_IncludeAndExclude()
{
PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
attr.Exclude = "Mono";
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
attr.Exclude = "Net";
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Not supported on Net", winXPHelper.Reason );
}
[Test]
public void PlatformAttribute_InvalidPlatform()
{
PlatformAttribute attr = new PlatformAttribute( "Net-1.0,Net11,Mono" );
Assert.Throws<InvalidPlatformException>(
() => winXPHelper.IsPlatformSupported(attr),
"Invalid platform name Net11");
}
[Test]
public void PlatformAttribute_ProcessBitNess()
{
PlatformAttribute attr32 = new PlatformAttribute("32-Bit");
PlatformAttribute attr64 = new PlatformAttribute("64-Bit");
PlatformHelper helper = new PlatformHelper();
// This test verifies that the two labels are known,
// do not cause an error and return consistent results.
bool is32BitProcess = helper.IsPlatformSupported(attr32);
bool is64BitProcess = helper.IsPlatformSupported(attr64);
Assert.False(is32BitProcess & is64BitProcess, "Process cannot be both 32 and 64 bit");
Assert.That(is64BitProcess, Is.EqualTo(Environment.Is64BitProcess));
}
[Test]
public void PlatformAttribute_OperatingSystemBitNess()
{
PlatformAttribute attr32 = new PlatformAttribute("32-Bit-OS");
PlatformAttribute attr64 = new PlatformAttribute("64-Bit-OS");
PlatformHelper helper = new PlatformHelper();
bool is64BitOS = Environment.Is64BitOperatingSystem;
Assert.That(helper.IsPlatformSupported(attr32), Is.Not.EqualTo(is64BitOS));
Assert.That(helper.IsPlatformSupported(attr64), Is.EqualTo(is64BitOS));
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Messaging;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Storage;
using Orleans.Streams;
namespace Orleans
{
internal class OutsideRuntimeClient : IRuntimeClient, IDisposable
{
internal static bool TestOnlyThrowExceptionDuringInit { get; set; }
private readonly Logger logger;
private readonly Logger appLogger;
private readonly ClientConfiguration config;
private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks;
private readonly ConcurrentDictionary<GuidId, LocalObjectData> localObjects;
private readonly ProxiedMessageCenter transport;
private bool listenForMessages;
private CancellationTokenSource listeningCts;
private bool firstMessageReceived;
private readonly ClientProviderRuntime clientProviderRuntime;
private readonly StatisticsProviderManager statisticsProviderManager;
internal ClientStatisticsManager ClientStatistics;
private GrainId clientId;
private readonly GrainId handshakeClientId;
private IGrainTypeResolver grainInterfaceMap;
private readonly ThreadTrackingStatistic incomingMessagesThreadTimeTracking;
// initTimeout used to be AzureTableDefaultPolicies.TableCreationTimeout, which was 3 min
private static readonly TimeSpan initTimeout = TimeSpan.FromMinutes(1);
private static readonly TimeSpan resetTimeout = TimeSpan.FromMinutes(1);
private const string BARS = "----------";
private readonly GrainFactory grainFactory;
public GrainFactory InternalGrainFactory
{
get { return grainFactory; }
}
/// <summary>
/// Response timeout.
/// </summary>
private TimeSpan responseTimeout;
private static readonly Object staticLock = new Object();
Logger IRuntimeClient.AppLogger
{
get { return appLogger; }
}
public ActivationAddress CurrentActivationAddress
{
get;
private set;
}
public SiloAddress CurrentSilo
{
get { return CurrentActivationAddress.Silo; }
}
public string Identity
{
get { return CurrentActivationAddress.ToString(); }
}
public IActivationData CurrentActivationData
{
get { return null; }
}
public IAddressable CurrentGrain
{
get { return null; }
}
public IStorageProvider CurrentStorageProvider
{
get { throw new InvalidOperationException("Storage provider only available from inside grain"); }
}
internal IList<Uri> Gateways
{
get
{
return transport.GatewayManager.ListProvider.GetGateways().GetResult();
}
}
public IStreamProviderManager CurrentStreamProviderManager { get; private set; }
public IStreamProviderRuntime CurrentStreamProviderRuntime
{
get { return clientProviderRuntime; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")]
public OutsideRuntimeClient(ClientConfiguration cfg, GrainFactory grainFactory, bool secondary = false)
{
this.grainFactory = grainFactory;
if (cfg == null)
{
Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object.");
throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg");
}
this.config = cfg;
if (!LogManager.IsInitialized) LogManager.Initialize(config);
StatisticsCollector.Initialize(config);
SerializationManager.Initialize(cfg.SerializationProviders, cfg.FallbackSerializationProvider);
logger = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime);
appLogger = LogManager.GetLogger("Application", LoggerType.Application);
BufferPool.InitGlobalBufferPool(config);
this.handshakeClientId = GrainId.NewClientId();
try
{
LoadAdditionalAssemblies();
PlacementStrategy.Initialize();
callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>();
localObjects = new ConcurrentDictionary<GuidId, LocalObjectData>();
if (!secondary)
{
UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException);
}
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
// Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked
SerializationManager.GetDeserializer(typeof(String));
clientProviderRuntime = new ClientProviderRuntime(grainFactory, null);
statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime);
var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations)
.WaitForResultWithThrow(initTimeout);
if (statsProviderName != null)
{
config.StatisticsProviderName = statsProviderName;
}
responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout;
var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface);
// Client init / sign-on message
logger.Info(ErrorCode.ClientInitializing, string.Format(
"{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}",
BARS, config.DNSHostName, localAddress, handshakeClientId));
string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}",
BARS, RuntimeVersion.Current, PrintAppDomainDetails());
startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config);
logger.Info(ErrorCode.ClientStarting, startMsg);
if (TestOnlyThrowExceptionDuringInit)
{
throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit");
}
config.CheckGatewayProviderSettings();
var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative
var gatewayListProvider = GatewayProviderFactory.CreateGatewayListProvider(config)
.WithTimeout(initTimeout).Result;
transport = new ProxiedMessageCenter(config, localAddress, generation, handshakeClientId, gatewayListProvider);
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver");
}
}
catch (Exception exc)
{
if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc);
ConstructorReset();
throw;
}
}
private void StreamingInitialize()
{
var implicitSubscriberTable = transport.GetImplicitStreamSubscriberTable(grainFactory).Result;
clientProviderRuntime.StreamingInitialize(implicitSubscriberTable);
var streamProviderManager = new Streams.StreamProviderManager();
streamProviderManager
.LoadStreamProviders(
this.config.ProviderConfigurations,
clientProviderRuntime)
.Wait();
CurrentStreamProviderManager = streamProviderManager;
}
private static void LoadAdditionalAssemblies()
{
#if !NETSTANDARD_TODO
var logger = LogManager.GetLogger("AssemblyLoader.Client", LoggerType.Runtime);
var directories =
new Dictionary<string, SearchOption>
{
{
Path.GetDirectoryName(typeof(OutsideRuntimeClient).GetTypeInfo().Assembly.Location),
SearchOption.AllDirectories
}
};
var excludeCriteria =
new AssemblyLoaderPathNameCriterion[]
{
AssemblyLoaderCriteria.ExcludeResourceAssemblies,
AssemblyLoaderCriteria.ExcludeSystemBinaries()
};
var loadProvidersCriteria =
new AssemblyLoaderReflectionCriterion[]
{
AssemblyLoaderCriteria.LoadTypesAssignableFrom(typeof(IProvider))
};
AssemblyLoader.LoadAssemblies(directories, excludeCriteria, loadProvidersCriteria, logger);
#endif
}
private void UnhandledException(ISchedulingContext context, Exception exception)
{
logger.Error(ErrorCode.Runtime_Error_100007, String.Format("OutsideRuntimeClient caught an UnobservedException."), exception);
logger.Assert(ErrorCode.Runtime_Error_100008, context == null, "context should be not null only inside OrleansRuntime and not on the client.");
}
public void Start()
{
lock (staticLock)
{
if (RuntimeClient.Current != null)
throw new InvalidOperationException("Can only have one RuntimeClient per AppDomain");
RuntimeClient.Current = this;
}
StartInternal();
logger.Info(ErrorCode.ProxyClient_StartDone, "{0} Started OutsideRuntimeClient with Global Client ID: {1}", BARS, CurrentActivationAddress.ToString() + ", client GUID ID: " + handshakeClientId);
}
// used for testing to (carefully!) allow two clients in the same process
internal void StartInternal()
{
transport.Start();
LogManager.MyIPEndPoint = transport.MyAddress.Endpoint; // transport.MyAddress is only set after transport is Started.
CurrentActivationAddress = ActivationAddress.NewActivationAddress(transport.MyAddress, handshakeClientId);
ClientStatistics = new ClientStatisticsManager(config);
listeningCts = new CancellationTokenSource();
var ct = listeningCts.Token;
listenForMessages = true;
// Keeping this thread handling it very simple for now. Just queue task on thread pool.
Task.Factory.StartNew(() =>
{
try
{
RunClientMessagePump(ct);
}
catch(Exception exc)
{
logger.Error(ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown exception", exc);
}
}
);
grainInterfaceMap = transport.GetTypeCodeMap(grainFactory).Result;
ClientStatistics.Start(statisticsProviderManager, transport, clientId)
.WaitWithThrow(initTimeout);
StreamingInitialize();
}
private void RunClientMessagePump(CancellationToken ct)
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartExecution();
}
while (listenForMessages)
{
var message = transport.WaitMessage(Message.Categories.Application, ct);
if (message == null) // if wait was cancelled
break;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartProcessing();
}
#endif
// when we receive the first message, we update the
// clientId for this client because it may have been modified to
// include the cluster name
if (!firstMessageReceived)
{
firstMessageReceived = true;
if (!handshakeClientId.Equals(message.TargetGrain))
{
clientId = message.TargetGrain;
transport.UpdateClientId(clientId);
CurrentActivationAddress = ActivationAddress.GetAddress(transport.MyAddress, clientId, CurrentActivationAddress.Activation);
}
else
{
clientId = handshakeClientId;
}
}
switch (message.Direction)
{
case Message.Directions.Response:
{
ReceiveResponse(message);
break;
}
case Message.Directions.OneWay:
case Message.Directions.Request:
{
this.DispatchToLocalObject(message);
break;
}
default:
logger.Error(ErrorCode.Runtime_Error_100327, String.Format("Message not supported: {0}.", message));
break;
}
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopProcessing();
incomingMessagesThreadTimeTracking.IncrementNumberOfProcessed();
}
#endif
}
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}
private void DispatchToLocalObject(Message message)
{
LocalObjectData objectData;
GuidId observerId = message.TargetObserverId;
if (observerId == null)
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound_2,
String.Format("Did not find TargetObserverId header in the message = {0}. A request message to a client is expected to have an observerId.", message));
return;
}
if (localObjects.TryGetValue(observerId, out objectData))
this.InvokeLocalObjectAsync(objectData, message);
else
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound,
String.Format(
"Unexpected target grain in request: {0}. Message={1}",
message.TargetGrain,
message));
}
}
private void InvokeLocalObjectAsync(LocalObjectData objectData, Message message)
{
var obj = (IAddressable)objectData.LocalObject.Target;
if (obj == null)
{
//// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore.
logger.Warn(ErrorCode.Runtime_Error_100162,
String.Format("Object associated with Observer ID {0} has been garbage collected. Deleting object reference and unregistering it. Message = {1}", objectData.ObserverId, message));
LocalObjectData ignore;
// Try to remove. If it's not there, we don't care.
localObjects.TryRemove(objectData.ObserverId, out ignore);
return;
}
bool start;
lock (objectData.Messages)
{
objectData.Messages.Enqueue(message);
start = !objectData.Running;
objectData.Running = true;
}
if (logger.IsVerbose) logger.Verbose("InvokeLocalObjectAsync {0} start {1}", message, start);
if (start)
{
// we use Task.Run() to ensure that the message pump operates asynchronously
// with respect to the current thread. see
// http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74
// at position 54:45.
//
// according to the information posted at:
// http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr
// this idiom is dependent upon the a TaskScheduler not implementing the
// override QueueTask as task inlining (as opposed to queueing). this seems
// implausible to the author, since none of the .NET schedulers do this and
// it is considered bad form (the OrleansTaskScheduler does not do this).
//
// if, for some reason this doesn't hold true, we can guarantee what we
// want by passing a placeholder continuation token into Task.StartNew()
// instead. i.e.:
//
// return Task.StartNew(() => ..., new CancellationToken());
Func<Task> asyncFunc =
async () =>
await this.LocalObjectMessagePumpAsync(objectData);
Task.Run(asyncFunc).Ignore();
}
}
private async Task LocalObjectMessagePumpAsync(LocalObjectData objectData)
{
while (true)
{
try
{
Message message;
lock (objectData.Messages)
{
if (objectData.Messages.Count == 0)
{
objectData.Running = false;
break;
}
message = objectData.Messages.Dequeue();
}
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Invoke))
continue;
RequestContext.Import(message.RequestContextData);
var request = (InvokeMethodRequest)message.BodyObject;
var targetOb = (IAddressable)objectData.LocalObject.Target;
object resultObject = null;
Exception caught = null;
try
{
// exceptions thrown within this scope are not considered to be thrown from user code
// and not from runtime code.
var resultPromise = objectData.Invoker.Invoke(targetOb, request);
if (resultPromise != null) // it will be null for one way messages
{
resultObject = await resultPromise;
}
}
catch (Exception exc)
{
// the exception needs to be reported in the log or propagated back to the caller.
caught = exc;
}
if (caught != null)
this.ReportException(message, caught);
else if (message.Direction != Message.Directions.OneWay)
await this.SendResponseAsync(message, resultObject);
}catch(Exception)
{
// ignore, keep looping.
}
}
}
private static bool ExpireMessageIfExpired(Message message, MessagingStatisticsGroup.Phase phase)
{
if (message.IsExpired)
{
message.DropExpiredMessage(phase);
return true;
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Task
SendResponseAsync(
Message message,
object resultObject)
{
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond))
return TaskDone.Done;
object deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = SerializationManager.DeepCopy(resultObject);
}
catch (Exception exc2)
{
SendResponse(message, Response.ExceptionResponse(exc2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendResponseFailed,
"Exception trying to send a response.", exc2);
return TaskDone.Done;
}
// the deep-copy succeeded.
SendResponse(message, new Response(deepCopy));
return TaskDone.Done;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ReportException(Message message, Exception exception)
{
var request = (InvokeMethodRequest)message.BodyObject;
switch (message.Direction)
{
default:
throw new InvalidOperationException();
case Message.Directions.OneWay:
{
logger.Error(
ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke,
String.Format(
"Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.",
request.MethodId,
request.InterfaceId),
exception);
break;
}
case Message.Directions.Request:
{
Exception deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = (Exception)SerializationManager.DeepCopy(exception);
}
catch (Exception ex2)
{
SendResponse(message, Response.ExceptionResponse(ex2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed,
"Exception trying to send an exception response", ex2);
return;
}
// the deep-copy succeeded.
var response = Response.ExceptionResponse(deepCopy);
SendResponse(message, response);
break;
}
}
}
private void SendResponse(Message request, Response response)
{
var message = request.CreateResponseMessage();
message.BodyObject = response;
transport.SendMessage(message);
}
/// <summary>
/// For testing only.
/// </summary>
public void Disconnect()
{
transport.Disconnect();
}
/// <summary>
/// For testing only.
/// </summary>
public void Reconnect()
{
transport.Reconnect();
}
#region Implementation of IRuntimeClient
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "CallbackData is IDisposable but instances exist beyond lifetime of this method so cannot Dispose yet.")]
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var message = Message.CreateMessage(request, options);
SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments);
}
private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var targetGrainId = target.GrainId;
var oneWay = (options & InvokeMethodOptions.OneWay) != 0;
message.SendingGrain = CurrentActivationAddress.Grain;
message.SendingActivation = CurrentActivationAddress.Activation;
message.TargetGrain = targetGrainId;
if (!String.IsNullOrEmpty(genericArguments))
message.GenericGrainType = genericArguments;
if (targetGrainId.IsSystemTarget)
{
// If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo
message.TargetSilo = target.SystemTargetSilo;
if (target.SystemTargetSilo != null)
{
message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo);
}
}
// Client sending messages to another client (observer). Yes, we support that.
if (target.IsObserverReference)
{
message.TargetObserverId = target.ObserverId;
}
if (debugContext != null)
{
message.DebugContext = debugContext;
}
if (message.IsExpirableMessage(config))
{
// don't set expiration for system target messages.
message.Expiration = DateTime.UtcNow + responseTimeout + Constants.MAXIMUM_CLOCK_SKEW;
}
if (!oneWay)
{
var callbackData = new CallbackData(callback, TryResendMessage, context, message, () => UnRegisterCallback(message.Id), config);
callbacks.TryAdd(message.Id, callbackData);
callbackData.StartTimer(responseTimeout);
}
if (logger.IsVerbose2) logger.Verbose2("Send {0}", message);
transport.SendMessage(message);
}
private bool TryResendMessage(Message message)
{
if (!message.MayResend(config))
{
return false;
}
if (logger.IsVerbose) logger.Verbose("Resend {0}", message);
message.ResendCount = message.ResendCount + 1;
message.TargetHistory = message.GetTargetHistory();
if (!message.TargetGrain.IsSystemTarget)
{
message.TargetActivation = null;
message.TargetSilo = null;
message.ClearTargetAddress();
}
transport.SendMessage(message);
return true;
}
public void ReceiveResponse(Message response)
{
if (logger.IsVerbose2) logger.Verbose2("Received {0}", response);
// ignore duplicate requests
if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.DuplicateRequest)
return;
CallbackData callbackData;
var found = callbacks.TryGetValue(response.Id, out callbackData);
if (found)
{
// We need to import the RequestContext here as well.
// Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task.
// RequestContext.Import(response.RequestContextData);
callbackData.DoCallback(response);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response);
}
}
private void UnRegisterCallback(CorrelationId id)
{
CallbackData ignore;
callbacks.TryRemove(id, out ignore);
}
public void Reset(bool cleanup)
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId);
}
});
Utils.SafeExecute(() =>
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset(cleanup).WaitWithThrow(resetTimeout);
}
}, logger, "Client.clientProviderRuntime.Reset");
Utils.SafeExecute(() =>
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.PrepareToStop();
}
}, logger, "Client.PrepareToStop-Transport");
listenForMessages = false;
Utils.SafeExecute(() =>
{
if (listeningCts != null)
{
listeningCts.Cancel();
}
}, logger, "Client.Stop-ListeningCTS");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.Stop();
}
}, logger, "Client.Stop-Transport");
Utils.SafeExecute(() =>
{
if (ClientStatistics != null)
{
ClientStatistics.Stop();
}
}, logger, "Client.Stop-ClientStatistics");
ConstructorReset();
}
private void ConstructorReset()
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId);
}
});
try
{
UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler();
}
catch (Exception) { }
try
{
AppDomain.CurrentDomain.DomainUnload -= CurrentDomain_DomainUnload;
}
catch (Exception) { }
try
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset().WaitWithThrow(resetTimeout);
}
}
catch (Exception) { }
try
{
LogManager.UnInitialize();
}
catch (Exception) { }
}
public void SetResponseTimeout(TimeSpan timeout)
{
responseTimeout = timeout;
}
public TimeSpan GetResponseTimeout()
{
return responseTimeout;
}
public Task<IGrainReminder> RegisterOrUpdateReminder(string reminderName, TimeSpan dueTime, TimeSpan period)
{
throw new InvalidOperationException("RegisterReminder can only be called from inside a grain");
}
public Task UnregisterReminder(IGrainReminder reminder)
{
throw new InvalidOperationException("UnregisterReminder can only be called from inside a grain");
}
public Task<IGrainReminder> GetReminder(string reminderName)
{
throw new InvalidOperationException("GetReminder can only be called from inside a grain");
}
public Task<List<IGrainReminder>> GetReminders()
{
throw new InvalidOperationException("GetReminders can only be called from inside a grain");
}
public SiloStatus GetSiloStatus(SiloAddress silo)
{
throw new InvalidOperationException("GetSiloStatus can only be called on the silo.");
}
public async Task ExecAsync(Func<Task> asyncFunction, ISchedulingContext context, string activityName)
{
await Task.Run(asyncFunction); // No grain context on client - run on .NET thread pool
}
public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
{
if (obj is GrainReference)
throw new ArgumentException("Argument obj is already a grain reference.");
GrainReference gr = GrainReference.NewObserverGrainReference(clientId, GuidId.GetNewGuidId());
if (!localObjects.TryAdd(gr.ObserverId, new LocalObjectData(obj, gr.ObserverId, invoker)))
{
throw new ArgumentException(String.Format("Failed to add new observer {0} to localObjects collection.", gr), "gr");
}
return gr;
}
public void DeleteObjectReference(IAddressable obj)
{
if (!(obj is GrainReference))
throw new ArgumentException("Argument reference is not a grain reference.");
var reference = (GrainReference) obj;
LocalObjectData ignore;
if (!localObjects.TryRemove(reference.ObserverId, out ignore))
throw new ArgumentException("Reference is not associated with a local object.", "reference");
}
public void DeactivateOnIdle(ActivationId id)
{
throw new InvalidOperationException();
}
#endregion
private void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
try
{
logger.Warn(ErrorCode.ProxyClient_AppDomain_Unload,
String.Format("Current AppDomain={0} is unloading.", PrintAppDomainDetails()));
LogManager.Flush();
}
catch(Exception)
{
// just ignore, make sure not to throw from here.
}
}
private string PrintAppDomainDetails()
{
#if NETSTANDARD_TODO
return "N/A";
#else
return string.Format("<AppDomain.Id={0}, AppDomain.FriendlyName={1}>", AppDomain.CurrentDomain.Id, AppDomain.CurrentDomain.FriendlyName);
#endif
}
private class LocalObjectData
{
internal WeakReference LocalObject { get; private set; }
internal IGrainMethodInvoker Invoker { get; private set; }
internal GuidId ObserverId { get; private set; }
internal Queue<Message> Messages { get; private set; }
internal bool Running { get; set; }
internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker)
{
LocalObject = new WeakReference(obj);
ObserverId = observerId;
Invoker = invoker;
Messages = new Queue<Message>();
Running = false;
}
}
public void Dispose()
{
if (listeningCts != null)
{
listeningCts.Dispose();
listeningCts = null;
}
GC.SuppressFinalize(this);
}
public IGrainTypeResolver GrainTypeResolver
{
get { return grainInterfaceMap; }
}
public string CaptureRuntimeEnvironment()
{
throw new NotImplementedException();
}
public IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType = null)
{
throw new NotImplementedException();
}
public void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo)
{
foreach (var callback in callbacks)
{
if (deadSilo.Equals(callback.Value.Message.TargetSilo))
{
callback.Value.OnTargetSiloFail();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001;
using System;
using System.Collections.Generic;
public class C
{
}
public interface I
{
}
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass<T>
{
#region Instance methods
public bool Method_ReturnBool()
{
return false;
}
public T Method_ReturnsT()
{
return default(T);
}
public T Method_ReturnsT(T t)
{
return t;
}
public T Method_ReturnsT(out T t)
{
t = default(T);
return t;
}
public T Method_ReturnsT(ref T t, T tt)
{
t = default(T);
return t;
}
public T Method_ReturnsT(params T[] t)
{
return default(T);
}
public T Method_ReturnsT(float x, T t)
{
return default(T);
}
public int Method_ReturnsInt(T t)
{
return 1;
}
public float Method_ReturnsFloat(T t, dynamic d)
{
return 3.4f;
}
public float Method_ReturnsFloat(T t, dynamic d, ref decimal dec)
{
dec = 3m;
return 3.4f;
}
public dynamic Method_ReturnsDynamic(T t)
{
return t;
}
public dynamic Method_ReturnsDynamic(T t, dynamic d)
{
return t;
}
public dynamic Method_ReturnsDynamic(T t, int x, dynamic d)
{
return t;
}
// Multiple params
// Constraints
// Nesting
#endregion
#region Static methods
public static bool? StaticMethod_ReturnBoolNullable()
{
return (bool?)false;
}
#endregion
}
public class MemberClassMultipleParams<T, U, V>
{
public T Method_ReturnsT(V v, U u)
{
return default(T);
}
}
public class MemberClassWithClassConstraint<T>
where T : class
{
public int Method_ReturnsInt()
{
return 1;
}
public T Method_ReturnsT(decimal dec, dynamic d)
{
return null;
}
}
public class MemberClassWithNewConstraint<T>
where T : new()
{
public T Method_ReturnsT()
{
return new T();
}
public dynamic Method_ReturnsDynamic(T t)
{
return new T();
}
}
public class MemberClassWithAnotherTypeConstraint<T, U>
where T : U
{
public U Method_ReturnsU(dynamic d)
{
return default(U);
}
public dynamic Method_ReturnsDynamic(int x, U u, dynamic d)
{
return default(T);
}
}
#region Negative tests - you should not be able to construct this with a dynamic object
public class MemberClassWithUDClassConstraint<T>
where T : C, new()
{
public C Method_ReturnsC()
{
return new T();
}
}
public class MemberClassWithStructConstraint<T>
where T : struct
{
public dynamic Method_ReturnsDynamic(int x)
{
return x;
}
}
public class MemberClassWithInterfaceConstraint<T>
where T : I
{
public dynamic Method_ReturnsDynamic(int x, T v)
{
return default(T);
}
}
#endregion
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001;
// <Title> Tests generic class regular method used in regular method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
if (t.TestMethod() == true)
return 1;
return 0;
}
public bool TestMethod()
{
dynamic mc = new MemberClass<string>();
return (bool)mc.Method_ReturnBool();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002;
// <Title> Tests generic class regular method used in arguments of method invocation.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
dynamic mc1 = new MemberClass<int>();
int result1 = t.TestMethod((int)mc1.Method_ReturnsT());
dynamic mc2 = new MemberClass<string>();
int result2 = Test.TestMethod((string)mc2.Method_ReturnsT());
if (result1 == 0 && result2 == 0)
return 0;
else
return 1;
}
public int TestMethod(int i)
{
if (i == default(int))
{
return 0;
}
else
{
return 1;
}
}
public static int TestMethod(string s)
{
if (s == default(string))
{
return 0;
}
else
{
return 1;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003;
// <Title> Tests generic class regular method used in static variable.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static dynamic s_mc = new MemberClass<string>();
private static float s_loc = (float)s_mc.Method_ReturnsFloat(null, 1);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (s_loc != 3.4f)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005;
// <Title> Tests generic class regular method used in unsafe.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//using System;
//[TestClass]public class Test
//{
//[Test][Priority(Priority.Priority1)]public void DynamicCSharpRunTest(){Assert.AreEqual(0, MainMethod());} public static unsafe int MainMethod()
//{
//dynamic dy = new MemberClass<int>();
//int value = 1;
//int* valuePtr = &value;
//int result = dy.Method_ReturnsT(out *valuePtr);
//if (result == 0 && value == 0)
//return 0;
//return 1;
//}
//}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006;
// <Title> Tests generic class regular method used in generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
string s1 = "";
string s2 = "";
string result = t.TestMethod<string>(ref s1, s2);
if (result == null && s1 == null)
return 0;
return 1;
}
public T TestMethod<T>(ref T t1, T t2)
{
dynamic mc = new MemberClass<T>();
return (T)mc.Method_ReturnsT(ref t1, t2);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass008.genclass008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass008.genclass008;
// <Title> Tests generic class regular method used in extension method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public int Field = 10;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = 1.ExReturnTest();
if (t.Field == 1)
return 0;
return 1;
}
}
public static class Extension
{
public static Test ExReturnTest(this int t)
{
dynamic dy = new MemberClass<int>();
float x = 3.3f;
int i = -1;
return new Test()
{
Field = t + (int)dy.Method_ReturnsT(x, i)
}
;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009.genclass009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009.genclass009;
// <Title> Tests generic class regular method used in for loop.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<MyEnum>();
int result = 0;
for (int i = (int)dy.Method_ReturnsInt(MyEnum.Third); i < 10; i++)
{
result += (int)dy.Method_ReturnsInt((MyEnum)(i % 3 + 1));
}
if (result == 9)
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009a.genclass009a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009a.genclass009a;
// <Title> Tests generic class regular method used in for loop.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<MyEnum>();
int result = 0;
for (int i = dy.Method_ReturnsInt(MyEnum.Third); i < 10; i++)
{
result += dy.Method_ReturnsInt((MyEnum)(i % 3 + 1));
}
if (result == 9)
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass010.genclass010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass010.genclass010;
// <Title> Tests generic class regular method used in static constructor.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test : I
{
private static decimal s_dec = 0M;
private static float s_result = 0f;
static Test()
{
dynamic dy = new MemberClass<I>();
s_result = (float)dy.Method_ReturnsFloat(new Test(), dy, ref s_dec);
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (Test.s_dec == 3M && Test.s_result == 3.4f)
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass012.genclass012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass012.genclass012;
// <Title> Tests generic class regular method used in lambda.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<string>();
dynamic d1 = 3;
dynamic d2 = "Test";
Func<string, string, string> fun = (x, y) => (y + x.ToString());
string result = fun((string)dy.Method_ReturnsDynamic("foo", d1), (string)dy.Method_ReturnsDynamic("bar", d2));
if (result == "barfoo")
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass013.genclass013
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass013.genclass013;
// <Title> Tests generic class regular method used in array initializer list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<string>();
string[] array = new string[]
{
(string)dy.Method_ReturnsDynamic(string.Empty, 1, dy), (string)dy.Method_ReturnsDynamic(null, 0, dy), (string)dy.Method_ReturnsDynamic("a", -1, dy)}
;
if (array.Length == 3 && array[0] == string.Empty && array[1] == null && array[2] == "a")
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass014.genclass014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass014.genclass014;
// <Title> Tests generic class regular method used in null coalescing operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = MemberClass<string>.StaticMethod_ReturnBoolNullable();
if (!((bool?)dy ?? false))
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass015.genclass015
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass015.genclass015;
// <Title> Tests generic class regular method used in static method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassMultipleParams<MyEnum, MyStruct, MyClass>();
MyEnum me = dy.Method_ReturnsT(null, new MyStruct());
return (int)me;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass016.genclass016
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass016.genclass016;
// <Title> Tests generic class regular method used in query expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
private class M
{
public int Field1;
public int Field2;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithClassConstraint<MyClass>();
var list = new List<M>()
{
new M()
{
Field1 = 1, Field2 = 2
}
, new M()
{
Field1 = 2, Field2 = 1
}
}
;
return list.Any(p => p.Field1 == (int)dy.Method_ReturnsInt()) ? 0 : 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass017.genclass017
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass017.genclass017;
// <Title> Tests generic class regular method used in ternary operator expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithClassConstraint<string>();
string result = (string)dy.Method_ReturnsT(decimal.MaxValue, dy) == null ? string.Empty : (string)dy.Method_ReturnsT(decimal.MaxValue, dy);
return result == string.Empty ? 0 : 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass018.genclass018
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass018.genclass018;
// <Title> Tests generic class regular method used in lock expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithNewConstraint<C>();
int result = 1;
lock (dy.Method_ReturnsT())
{
result = 0;
}
return result;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass019.genclass019
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass019.genclass019;
// <Title> Tests generic class regular method used in switch section statement list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy1 = new MemberClassWithNewConstraint<C>();
dynamic dy2 = new MemberClassWithAnotherTypeConstraint<int, int>();
C result = new C();
int result2 = -1;
switch ((int)dy2.Method_ReturnsU(dy1)) // 0
{
case 0:
result = (C)dy1.Method_ReturnsDynamic(result); // called
break;
default:
result2 = (int)dy2.Method_ReturnsDynamic(0, 0, dy2); // not called
break;
}
return (result.GetType() == typeof(C) && result2 == -1) ? 0 : 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.implicit01.implicit01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.implicit01.implicit01;
// <Title> Tests generic class regular method used in regular method body.</Title>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Ta
{
public static int i = 2;
}
public class A<T>
{
public static implicit operator A<List<string>>(A<T> x)
{
return new A<List<string>>();
}
}
public class B
{
public static void Foo<T>(A<List<T>> x, string y)
{
Ta.i--;
}
public static void Foo<T>(object x, string y)
{
Ta.i++;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var x = new A<Action<object>>();
Foo<string>(x, "");
Foo<string>(x, (dynamic)"");
return Ta.i;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
{
internal abstract partial class AbstractVisualStudioErrorTaskList : AbstractVisualStudioTaskList
{
// use predefined tagger delay constant for error list reporting threshold
private const int ReportingThresholdInMS = TaggerConstants.ShortDelay;
// this is an arbitary number I chose. we should update this number as we dogfood and
// decide what would be appropriate number of errors to show users.
private const int ErrorReportThreshold = 416;
private static readonly VisualStudioTaskItem[] s_noItems = Array.Empty<VisualStudioTaskItem>();
private readonly SimpleTaskQueue _taskQueue;
private readonly VisualStudioWorkspace _workspace;
private readonly object _gate;
private readonly IDocumentTrackingService _documentTracker;
private readonly Dictionary<object, VisualStudioTaskItem[]> _reportedItemsMap;
private readonly Dictionary<ProjectId, Dictionary<object, VisualStudioTaskItem[]>> _notReportedProjectItemsMap;
private readonly Dictionary<DocumentId, Dictionary<object, VisualStudioTaskItem[]>> _notReportedDocumentItemMap;
// opened files set
private readonly HashSet<DocumentId> _openedFiles;
// cached temporary set that will be used for various temporary operation
private readonly HashSet<object> _inProcessSet;
// time stamp on last time new item is added or removed
private int _lastNewItemAddedOrRemoved;
private int _lastReported;
// indicate whether we are still reporting errors to error list
private bool _reportRequestRunning;
// number of items reported to vs error list
private int _reportedCount;
protected AbstractVisualStudioErrorTaskList(
SVsServiceProvider serviceProvider,
VisualStudioWorkspace workspace,
IForegroundNotificationService notificationService,
IDiagnosticService diagnosticService,
IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) :
base(serviceProvider, notificationService, FeatureAttribute.ErrorList, asyncListeners)
{
_gate = new object();
_workspace = workspace;
// we should have document tracking service in visual studio host
_documentTracker = _workspace.Services.GetService<IDocumentTrackingService>();
Contract.ThrowIfNull(_documentTracker);
_taskQueue = new SimpleTaskQueue(TaskScheduler.Default);
_reportedItemsMap = new Dictionary<object, VisualStudioTaskItem[]>();
_notReportedProjectItemsMap = new Dictionary<ProjectId, Dictionary<object, VisualStudioTaskItem[]>>();
_notReportedDocumentItemMap = new Dictionary<DocumentId, Dictionary<object, VisualStudioTaskItem[]>>();
_openedFiles = new HashSet<DocumentId>();
_inProcessSet = new HashSet<object>();
_lastNewItemAddedOrRemoved = Environment.TickCount;
_lastReported = Environment.TickCount;
_reportRequestRunning = false;
_reportedCount = 0;
if (ErrorListInstalled)
{
return;
}
// this should be called after all fields are initialized
InitializeTaskList();
diagnosticService.DiagnosticsUpdated += this.OnDiagnosticUpdated;
}
public override int EnumTaskItems(out IVsEnumTaskItems enumTaskItems)
{
// this will be called at the end of build.
// return real enumerator, rather than calling async refresh
var items = GetAllReportedTaskItems();
enumTaskItems = new TaskItemsEnum<VisualStudioTaskItem>(items);
return VSConstants.S_OK;
}
private VisualStudioTaskItem[] GetAllReportedTaskItems()
{
lock (_gate)
{
// return sorted list
var list = _reportedItemsMap.Values.SelectMany(i => i).ToArray();
Array.Sort(list);
return list;
}
}
private void OnDiagnosticUpdated(object sender, DiagnosticsUpdatedArgs args)
{
if (args.Workspace != _workspace)
{
return;
}
var asyncToken = this.Listener.BeginAsyncOperation("OnTaskListUpdated");
_taskQueue.ScheduleTask(
() => this.Enqueue(
args.Id, args.ProjectId, args.DocumentId,
args.Diagnostics.Where(d => d.Severity != DiagnosticSeverity.Hidden).Select(d => new DiagnosticTaskItem(d)))).CompletesAsyncOperation(asyncToken);
}
private bool HasPendingTaskItemsToReport
{
get
{
return _notReportedDocumentItemMap.Count > 0 || _notReportedProjectItemsMap.Count > 0;
}
}
private bool IsUnderThreshold
{
get
{
return _reportedCount < ErrorReportThreshold;
}
}
private bool HasPendingOpenDocumentTaskItemsToReport
{
get
{
return _openedFiles.Count > 0;
}
}
public void Enqueue(object key, ProjectId projectId, DocumentId documentId, IEnumerable<ITaskItem> items)
{
lock (_gate)
{
var newItems = CreateVisualStudioTaskItems(items);
var existingItems = GetExistingVisualStudioTaskItems(key);
var hasNewItems = newItems != null;
var hasExistingItems = existingItems != null || HasPendingVisualStudioTaskItems(key, projectId, documentId);
// track items from opened files
if (documentId != null && _workspace.IsDocumentOpen(documentId))
{
_openedFiles.Add(documentId);
}
// nothing to do
if (!hasNewItems && !hasExistingItems)
{
return;
}
// handle 3 operations.
// 1. delete
if (!hasNewItems && hasExistingItems)
{
RemoveExistingTaskItems_NoLock(key, projectId, documentId, existingItems);
ReportPendingTaskItems_NoLock();
return;
}
// 2. insert
if (hasNewItems && !hasExistingItems)
{
EnqueuePendingTaskItems_NoLock(key, projectId, documentId, newItems);
ReportPendingTaskItems_NoLock();
return;
}
// 3. update
Contract.Requires(hasNewItems && hasExistingItems);
EnqueueUpdate_NoLock(key, projectId, documentId, newItems, existingItems);
}
}
private bool HasPendingVisualStudioTaskItems(object key, ProjectId projectId, DocumentId documentId)
{
Dictionary<object, VisualStudioTaskItem[]> taskMap;
if (documentId != null)
{
return _notReportedDocumentItemMap.TryGetValue(documentId, out taskMap) && taskMap.ContainsKey(key);
}
if (projectId != null)
{
return _notReportedProjectItemsMap.TryGetValue(projectId, out taskMap) && taskMap.ContainsKey(key);
}
return false;
}
private void EnqueueUpdate_NoLock(object key, ProjectId projectId, DocumentId documentId, VisualStudioTaskItem[] newItems, VisualStudioTaskItem[] existingItems)
{
existingItems = existingItems ?? s_noItems;
_inProcessSet.Clear();
_inProcessSet.UnionWith(existingItems);
_inProcessSet.IntersectWith(newItems);
if (_inProcessSet.Count == 0)
{
// completely replaced
RemoveExistingTaskItems_NoLock(key, projectId, documentId, existingItems);
EnqueuePendingTaskItems_NoLock(key, projectId, documentId, newItems);
ReportPendingTaskItems_NoLock();
return;
}
if (_inProcessSet.Count == newItems.Length && existingItems.Length == newItems.Length)
{
// nothing has changed.
RemovePendingTaskItems_NoLock(key, projectId, documentId);
_inProcessSet.Clear();
return;
}
if (_inProcessSet.Count == existingItems.Length)
{
// all existing items survived. only added items
var itemsToInsert = GetItemsNotInSet_NoLock(newItems, _inProcessSet.Count);
EnqueuePendingTaskItems_NoLock(key, projectId, documentId, itemsToInsert);
ReportPendingTaskItems_NoLock();
_inProcessSet.Clear();
return;
}
if (_inProcessSet.Count == newItems.Length)
{
// all new items survived. only deleted items
var itemsToDelete = GetItemsNotInSet_NoLock(existingItems, _inProcessSet.Count);
UpdateExistingTaskItems_NoLock(key, projectId, documentId, _inProcessSet.OfType<VisualStudioTaskItem>().ToArray(), itemsToDelete);
ReportPendingTaskItems_NoLock();
_inProcessSet.Clear();
return;
}
// part of existing items are changed
{
var itemsToDelete = GetItemsNotInSet_NoLock(existingItems, _inProcessSet.Count);
var itemsToInsert = GetItemsNotInSet_NoLock(newItems, _inProcessSet.Count);
// update only actually changed items
UpdateExistingTaskItems_NoLock(key, projectId, documentId, _inProcessSet.OfType<VisualStudioTaskItem>().ToArray(), itemsToDelete);
EnqueuePendingTaskItems_NoLock(key, projectId, documentId, itemsToInsert);
ReportPendingTaskItems_NoLock();
_inProcessSet.Clear();
}
}
private VisualStudioTaskItem[] GetItemsNotInSet_NoLock(VisualStudioTaskItem[] items, int sharedCount)
{
var taskItems = new VisualStudioTaskItem[items.Length - sharedCount];
var index = 0;
for (var i = 0; i < items.Length; i++)
{
if (_inProcessSet.Contains(items[i]))
{
continue;
}
taskItems[index++] = items[i];
}
Contract.Requires(items.Where(i => !_inProcessSet.Contains(i)).SetEquals(taskItems));
return taskItems;
}
private VisualStudioTaskItem[] GetExistingVisualStudioTaskItems(object key)
{
VisualStudioTaskItem[] reported;
if (!_reportedItemsMap.TryGetValue(key, out reported))
{
return null;
}
// everything should be in sorted form
ValidateSorted(reported);
return reported;
}
private void ReportPendingTaskItems_NoLock()
{
_lastNewItemAddedOrRemoved = Environment.TickCount;
if (!this.HasPendingTaskItemsToReport || _reportRequestRunning)
{
return;
}
// no task items for opened files and we are over threshold
if (!this.HasPendingOpenDocumentTaskItemsToReport && !this.IsUnderThreshold)
{
return;
}
RegisterNotificationForAddedItems_NoLock();
}
private void RegisterNotificationForAddedItems_NoLock()
{
this.NotificationService.RegisterNotification(() =>
{
lock (_gate)
{
_reportRequestRunning = true;
// when there is high activity on task items, delay reporting it
// but, do not hold it too long
var current = Environment.TickCount;
if (current - _lastNewItemAddedOrRemoved < ReportingThresholdInMS &&
current - _lastReported < ReportingThresholdInMS * 4)
{
RegisterNotificationForAddedItems_NoLock();
return false;
}
_lastReported = current;
ValueTuple<object, VisualStudioTaskItem[]> bestItemToReport;
if (!TryGetNextBestItemToReport_NoLock(out bestItemToReport))
{
return _reportRequestRunning = false;
}
var existingItems = GetExistingVisualStudioTaskItems(bestItemToReport.Item1);
ValidateSorted(bestItemToReport.Item2);
ValidateSorted(existingItems);
VisualStudioTaskItem[] itemsToReport;
if (existingItems == null)
{
itemsToReport = bestItemToReport.Item2;
_reportedItemsMap[bestItemToReport.Item1] = bestItemToReport.Item2;
}
else
{
itemsToReport = existingItems.Concat(bestItemToReport.Item2).ToArray();
Array.Sort(itemsToReport);
_reportedItemsMap[bestItemToReport.Item1] = itemsToReport;
}
_reportedCount += bestItemToReport.Item2.Length;
Contract.Requires(_reportedCount >= 0);
Contract.Requires(_reportedCount == _reportedItemsMap.Values.Sum(a => a.Length));
this.RefreshOrAddTasks(itemsToReport);
return _reportRequestRunning = (this.IsUnderThreshold && this.HasPendingTaskItemsToReport) || this.HasPendingOpenDocumentTaskItemsToReport;
}
}, ReportingThresholdInMS, this.Listener.BeginAsyncOperation("TaskItemQueue_ReportItem"));
}
private bool TryGetNextBestItemToReport_NoLock(out ValueTuple<object, VisualStudioTaskItem[]> bestItemToReport)
{
bestItemToReport = default(ValueTuple<object, VisualStudioTaskItem[]>);
// no item to report
if (!this.HasPendingTaskItemsToReport)
{
return false;
}
// order of process is like this
// 1. active document
var activeDocumentId = _documentTracker.GetActiveDocument();
if (activeDocumentId != null &&
TryGetNextBestItemToReport_NoLock(_notReportedDocumentItemMap, activeDocumentId, out bestItemToReport))
{
return true;
}
// 2. visible documents
foreach (var visibleDocumentId in _documentTracker.GetVisibleDocuments())
{
if (TryGetNextBestItemToReport_NoLock(_notReportedDocumentItemMap, visibleDocumentId, out bestItemToReport))
{
return true;
}
}
// 3. opened documents
if (TryGetNextBestItemToReportFromOpenedFiles_NoLock(out bestItemToReport))
{
return true;
}
if (!this.IsUnderThreshold)
{
return false;
}
// 4. documents in the project where active document is in
if (activeDocumentId != null)
{
if (TryGetNextBestItemToReport_NoLock(
_notReportedDocumentItemMap, keys => keys.FirstOrDefault(k => k.ProjectId == activeDocumentId.ProjectId),
(s, k) => s.ContainsDocument(k), out bestItemToReport))
{
return true;
}
}
// just take random one from the document map
if (_notReportedDocumentItemMap.Count > 0)
{
if (TryGetNextBestItemToReport_NoLock(_notReportedDocumentItemMap, keys => keys.FirstOrDefault(), (s, k) => s.ContainsDocument(k), out bestItemToReport))
{
return true;
}
}
if (_notReportedProjectItemsMap.Count > 0)
{
if (TryGetNextBestItemToReport_NoLock(_notReportedProjectItemsMap, keys => keys.FirstOrDefault(), (s, k) => s.ContainsProject(k), out bestItemToReport))
{
return true;
}
}
return false;
}
private bool TryGetNextBestItemToReportFromOpenedFiles_NoLock(out ValueTuple<object, VisualStudioTaskItem[]> bestItemToReport)
{
bestItemToReport = default(ValueTuple<object, VisualStudioTaskItem[]>);
if (!this.HasPendingOpenDocumentTaskItemsToReport)
{
return false;
}
_inProcessSet.Clear();
var result = false;
foreach (var openedDocumentId in _openedFiles)
{
if (!_workspace.CurrentSolution.ContainsDocument(openedDocumentId))
{
_notReportedDocumentItemMap.Remove(openedDocumentId);
}
if (TryGetNextBestItemToReport_NoLock(_notReportedDocumentItemMap, openedDocumentId, out bestItemToReport))
{
result = true;
break;
}
_inProcessSet.Add(openedDocumentId);
}
if (_inProcessSet.Count > 0)
{
_openedFiles.RemoveAll(_inProcessSet.OfType<DocumentId>());
_inProcessSet.Clear();
}
if (!this.HasPendingTaskItemsToReport)
{
_openedFiles.Clear();
}
return result;
}
private bool TryGetNextBestItemToReport_NoLock<T>(
Dictionary<T, Dictionary<object, VisualStudioTaskItem[]>> map,
Func<IEnumerable<T>, T> key,
Func<Solution, T, bool> predicate,
out ValueTuple<object, VisualStudioTaskItem[]> bestItemToReport) where T : class
{
bestItemToReport = default(ValueTuple<object, VisualStudioTaskItem[]>);
while (true)
{
var id = key(map.Keys);
if (id == null)
{
break;
}
if (!predicate(_workspace.CurrentSolution, id))
{
map.Remove(id);
continue;
}
if (TryGetNextBestItemToReport_NoLock(map, id, out bestItemToReport))
{
return true;
}
}
return false;
}
private bool TryGetNextBestItemToReport_NoLock<T>(
Dictionary<T, Dictionary<object, VisualStudioTaskItem[]>> map, T key,
out ValueTuple<object, VisualStudioTaskItem[]> bestItemToReport)
{
bestItemToReport = default(ValueTuple<object, VisualStudioTaskItem[]>);
Dictionary<object, VisualStudioTaskItem[]> taskMap;
if (!map.TryGetValue(key, out taskMap))
{
return false;
}
Contract.Requires(taskMap.Count > 0);
foreach (var first in taskMap)
{
bestItemToReport = ValueTuple.Create(first.Key, first.Value);
ValidateSorted(bestItemToReport.Item2);
break;
}
taskMap.Remove(bestItemToReport.Item1);
if (taskMap.Count == 0)
{
map.Remove(key);
}
return true;
}
private void EnqueuePendingTaskItems_NoLock(object key, ProjectId projectId, DocumentId documentId, VisualStudioTaskItem[] taskItems)
{
if (taskItems.Length == 0)
{
return;
}
var first = taskItems[0];
Contract.Requires(projectId == first.Info.ProjectId);
Contract.Requires(documentId == first.Info.DocumentId);
if (documentId != null)
{
EnqueuePendingTaskItemsToMap_NoLock(_notReportedDocumentItemMap, documentId, key, taskItems);
return;
}
if (projectId != null)
{
EnqueuePendingTaskItemsToMap_NoLock(_notReportedProjectItemsMap, projectId, key, taskItems);
return;
}
// assert and ignore items that have neither document id or project id
Contract.Requires(false, "how this can happen?");
}
private void EnqueuePendingTaskItemsToMap_NoLock<T>(
Dictionary<T, Dictionary<object, VisualStudioTaskItem[]>> map, T mapKey, object taskKey, VisualStudioTaskItem[] taskItems)
{
var taskMap = map.GetOrAdd(mapKey, _ => new Dictionary<object, VisualStudioTaskItem[]>());
Array.Sort(taskItems);
taskMap[taskKey] = taskItems;
}
private void RemovePendingTaskItems_NoLock(object key, ProjectId projectId, DocumentId documentId)
{
if (documentId != null)
{
// check not reported item in document
RemovePendingTaskItemsFromMap_NoLock(_notReportedDocumentItemMap, documentId, key);
return;
}
if (projectId != null)
{
// check not reported item in project
RemovePendingTaskItemsFromMap_NoLock(_notReportedProjectItemsMap, projectId, key);
return;
}
Contract.Requires(false, "should have at least one of them");
}
private void RemovePendingTaskItemsFromMap_NoLock<T>(Dictionary<T, Dictionary<object, VisualStudioTaskItem[]>> map, T mapKey, object taskKey)
{
// remove task item if we found one
Dictionary<object, VisualStudioTaskItem[]> taskMap;
if (!map.TryGetValue(mapKey, out taskMap))
{
return;
}
if (!taskMap.Remove(taskKey))
{
return;
}
if (taskMap.Count > 0)
{
return;
}
map.Remove(mapKey);
}
private void RemoveReportedTaskItems_NoLock(object key, VisualStudioTaskItem[] existingItems)
{
if (existingItems == null)
{
return;
}
_reportedCount -= existingItems.Length;
_reportedItemsMap.Remove(key);
Contract.Requires(_reportedCount >= 0);
Contract.Requires(_reportedCount == _reportedItemsMap.Values.Sum(a => a.Length));
RegisterNotificationForDeleteItems_NoLock(existingItems);
}
private void UpdateReportedTaskItems_NoLock(object key, VisualStudioTaskItem[] survivedItems, VisualStudioTaskItem[] itemsToDelete)
{
_reportedCount -= itemsToDelete.Length;
Array.Sort(survivedItems);
_reportedItemsMap[key] = survivedItems;
Contract.Requires(_reportedCount >= 0);
Contract.Requires(_reportedCount == _reportedItemsMap.Values.Sum(a => a.Length));
RegisterNotificationForDeleteItems_NoLock(itemsToDelete);
}
private void RegisterNotificationForDeleteItems_NoLock(VisualStudioTaskItem[] itemsToDelete)
{
// if there is actually no items to delete, bail out
if (itemsToDelete.Length == 0)
{
return;
}
this.NotificationService.RegisterNotification(() =>
{
lock (_gate)
{
this.RemoveTasks(itemsToDelete);
}
}, this.Listener.BeginAsyncOperation("TaskItemQueue_RemoveItem"));
}
private void UpdateExistingTaskItems_NoLock(object key, ProjectId projectId, DocumentId documentId, VisualStudioTaskItem[] survivedItems, VisualStudioTaskItem[] itemsToDelete)
{
UpdateReportedTaskItems_NoLock(key, survivedItems, itemsToDelete);
RemovePendingTaskItems_NoLock(key, projectId, documentId);
}
private void RemoveExistingTaskItems_NoLock(object key, ProjectId projectId, DocumentId documentId, VisualStudioTaskItem[] existingItems)
{
RemoveReportedTaskItems_NoLock(key, existingItems);
RemovePendingTaskItems_NoLock(key, projectId, documentId);
}
private static readonly Func<IErrorTaskItem, VisualStudioTaskItem> s_createTaskItem = d => new VisualStudioTaskItem(d);
private VisualStudioTaskItem[] CreateVisualStudioTaskItems(IEnumerable<ITaskItem> items)
{
if (!items.Any())
{
return null;
}
_inProcessSet.Clear();
_inProcessSet.UnionWith(items.OfType<IErrorTaskItem>().Where(d => d.Workspace == _workspace).Select(s_createTaskItem));
// make sure we only return unique items.
// sometimes there can be error items with exact same content. for example, if same tokens are missing at the end of a file,
// compiler will report same errors for all missing tokens. now in those cases, we will unify those errors to one.
var newItems = _inProcessSet.OfType<VisualStudioTaskItem>().ToArray();
if (newItems.Length == 0)
{
return null;
}
_inProcessSet.Clear();
return newItems;
}
[Conditional("DEBUG")]
private static void ValidateSorted(VisualStudioTaskItem[] reported)
{
if (reported == null)
{
return;
}
var copied = reported.ToArray();
Array.Sort(copied);
Contract.Requires(copied.SequenceEqual(reported));
}
}
}
| |
/*
* Copyright (c) 2012-2014 AssimpNet - Nicholas Woodfield
*
* 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 Assimp.Unmanaged;
namespace Assimp
{
/// <summary>
/// A node in the imported model hierarchy.
/// </summary>
public sealed class Node : IMarshalable<Node, AiNode>
{
private String m_name;
private Matrix4x4 m_transform;
private Node m_parent;
private NodeCollection m_children;
private List<int> m_meshes;
private Metadata m_metaData;
/// <summary>
/// Gets or sets the name of the node.
/// </summary>
public String Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
/// <summary>
/// Gets or sets the transformation of the node relative to its parent.
/// </summary>
public Matrix4x4 Transform
{
get
{
return m_transform;
}
set
{
m_transform = value;
}
}
/// <summary>
/// Gets the node's parent, if it exists.
/// </summary>
public Node Parent
{
get
{
return m_parent;
}
}
/// <summary>
/// Gets the number of children that is owned by this node.
/// </summary>
public int ChildCount
{
get
{
return m_children.Count;
}
}
/// <summary>
/// Gets if the node contains children.
/// </summary>
public bool HasChildren
{
get
{
return m_children.Count > 0;
}
}
/// <summary>
/// Gets the node's children.
/// </summary>
public NodeCollection Children
{
get
{
return m_children;
}
}
/// <summary>
/// Gets the number of meshes referenced by this node.
/// </summary>
public int MeshCount
{
get
{
return m_meshes.Count;
}
}
/// <summary>
/// Gets if the node contains mesh references.
/// </summary>
public bool HasMeshes
{
get
{
return m_meshes.Count > 0;
}
}
/// <summary>
/// Gets the indices of the meshes referenced by this node. Meshes can be
/// shared between nodes, so there is a mesh collection owned by the scene
/// that each node can reference.
/// </summary>
public List<int> MeshIndices
{
get
{
return m_meshes;
}
}
/// <summary>
/// Gets the node's metadata container.
/// </summary>
public Metadata Metadata
{
get
{
return m_metaData;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="Node"/> class.
/// </summary>
public Node()
{
m_name = String.Empty;
m_transform = Matrix4x4.Identity;
m_parent = null;
m_children = new NodeCollection(this);
m_meshes = new List<int>();
m_metaData = new Metadata();
}
/// <summary>
/// Constructs a new instance of the <see cref="Node"/> class.
/// </summary>
/// <param name="name">Name of the node</param>
public Node(String name)
: this()
{
m_name = name;
}
/// <summary>
/// Constructs a new instance of the <see cref="Node"/> class.
/// </summary>
/// <param name="name">Name of the node</param>
/// <param name="parent">Parent of the node</param>
public Node(String name, Node parent)
: this()
{
m_name = name;
m_parent = parent;
}
//Internal use - sets the node parent in NodeCollection
internal void SetParent(Node parent)
{
m_parent = parent;
}
/// <summary>
/// Finds a node with the specific name, which may be this node
/// or any children or children's children, and so on, if it exists.
/// </summary>
/// <param name="name">Node name</param>
/// <returns>The node or null if it does not exist</returns>
public Node FindNode(String name)
{
if(name.Equals(m_name))
return this;
if(HasChildren)
{
foreach(Node child in m_children)
{
Node found = child.FindNode(name);
if(found != null)
return found;
}
}
//No child found
return null;
}
private IntPtr ToNativeRecursive(IntPtr parentPtr, Node node)
{
if(node == null)
return IntPtr.Zero;
int sizeofNative = MemoryHelper.SizeOf<AiNode>();
//Allocate the memory that will hold the node
IntPtr nodePtr = MemoryHelper.AllocateMemory(sizeofNative);
//First fill the native struct
AiNode nativeValue;
nativeValue.Name = new AiString(node.m_name);
nativeValue.Transformation = node.m_transform;
nativeValue.Parent = parentPtr;
nativeValue.NumMeshes = (uint) node.m_meshes.Count;
nativeValue.Meshes = MemoryHelper.ToNativeArray<int>(node.m_meshes.ToArray());
nativeValue.MetaData = IntPtr.Zero;
//If has metadata, create it, otherwise it should be NULL
if (m_metaData.Count > 0)
nativeValue.MetaData = MemoryHelper.ToNativePointer<Metadata, AiMetadata>(m_metaData);
//Now descend through the children
nativeValue.NumChildren = (uint) node.m_children.Count;
int numChildren = (int) nativeValue.NumChildren;
int stride = IntPtr.Size;
IntPtr childrenPtr = IntPtr.Zero;
if(numChildren > 0)
{
childrenPtr = MemoryHelper.AllocateMemory(numChildren * IntPtr.Size);
for(int i = 0; i < numChildren; i++)
{
IntPtr currPos = MemoryHelper.AddIntPtr(childrenPtr, stride * i);
Node child = node.m_children[i];
IntPtr childPtr = IntPtr.Zero;
//Recursively create the children and its children
if(child != null)
{
childPtr = ToNativeRecursive(nodePtr, child);
}
//Write the child's node ptr to our array
MemoryHelper.Write<IntPtr>(currPos, ref childPtr);
}
}
//Finall finish writing to the native struct, and write the whole thing to the memory we allocated previously
nativeValue.Children = childrenPtr;
MemoryHelper.Write<AiNode>(nodePtr, ref nativeValue);
return nodePtr;
}
#region IMarshalable Implemention
/// <summary>
/// Gets a value indicating whether this instance is native blittable.
/// </summary>
bool IMarshalable<Node, AiNode>.IsNativeBlittable
{
get { return true; }
}
/// <summary>
/// Writes the managed data to the native value.
/// </summary>
/// <param name="thisPtr">Optional pointer to the memory that will hold the native value.</param>
/// <param name="nativeValue">Output native value</param>
void IMarshalable<Node, AiNode>.ToNative(IntPtr thisPtr, out AiNode nativeValue)
{
nativeValue.Name = new AiString(m_name);
nativeValue.Transformation = m_transform;
nativeValue.Parent = IntPtr.Zero;
nativeValue.NumMeshes = (uint) m_meshes.Count;
nativeValue.Meshes = IntPtr.Zero;
nativeValue.MetaData = IntPtr.Zero;
//If has metadata, create it, otherwise it should be NULL
if(m_metaData.Count > 0)
nativeValue.MetaData = MemoryHelper.ToNativePointer<Metadata, AiMetadata>(m_metaData);
if(nativeValue.NumMeshes > 0)
nativeValue.Meshes = MemoryHelper.ToNativeArray<int>(m_meshes.ToArray());
//Now descend through the children
nativeValue.NumChildren = (uint) m_children.Count;
int numChildren = (int) nativeValue.NumChildren;
int stride = IntPtr.Size;
IntPtr childrenPtr = IntPtr.Zero;
if(numChildren > 0)
{
childrenPtr = MemoryHelper.AllocateMemory(numChildren * IntPtr.Size);
for(int i = 0; i < numChildren; i++)
{
IntPtr currPos = MemoryHelper.AddIntPtr(childrenPtr, stride * i);
Node child = m_children[i];
IntPtr childPtr = IntPtr.Zero;
//Recursively create the children and its children
if(child != null)
{
childPtr = ToNativeRecursive(thisPtr, child);
}
//Write the child's node ptr to our array
MemoryHelper.Write<IntPtr>(currPos, ref childPtr);
}
}
//Finally finish writing to the native struct
nativeValue.Children = childrenPtr;
}
/// <summary>
/// Reads the unmanaged data from the native value.
/// </summary>
/// <param name="nativeValue">Input native value</param>
void IMarshalable<Node, AiNode>.FromNative(ref AiNode nativeValue)
{
m_name = nativeValue.Name.GetString();
m_transform = nativeValue.Transformation;
m_parent = null;
m_children.Clear();
m_meshes.Clear();
m_metaData.Clear();
if(nativeValue.MetaData != IntPtr.Zero)
{
Metadata data = MemoryHelper.FromNativePointer<Metadata, AiMetadata>(nativeValue.MetaData);
foreach(KeyValuePair<String, Metadata.Entry> kv in data)
m_metaData.Add(kv.Key, kv.Value);
}
if(nativeValue.NumMeshes > 0 && nativeValue.Meshes != IntPtr.Zero)
m_meshes.AddRange(MemoryHelper.FromNativeArray<int>(nativeValue.Meshes, (int) nativeValue.NumMeshes));
if(nativeValue.NumChildren > 0 && nativeValue.Children != IntPtr.Zero)
m_children.AddRange(MemoryHelper.FromNativeArray<Node, AiNode>(nativeValue.Children, (int) nativeValue.NumChildren, true));
}
/// <summary>
/// Frees unmanaged memory created by <see cref="IMarshalable{Node, AiNode}.ToNative"/>.
/// </summary>
/// <param name="nativeValue">Native value to free</param>
/// <param name="freeNative">True if the unmanaged memory should be freed, false otherwise.</param>
public static void FreeNative(IntPtr nativeValue, bool freeNative)
{
if(nativeValue == IntPtr.Zero)
return;
AiNode aiNode = MemoryHelper.Read<AiNode>(nativeValue);
if(aiNode.NumMeshes > 0 && aiNode.Meshes != IntPtr.Zero)
MemoryHelper.FreeMemory(aiNode.Meshes);
if(aiNode.NumChildren > 0 && aiNode.Children != IntPtr.Zero)
MemoryHelper.FreeNativeArray<AiNode>(aiNode.Children, (int) aiNode.NumChildren, FreeNative, true);
if(aiNode.MetaData != IntPtr.Zero)
Metadata.FreeNative(aiNode.MetaData, true);
if(freeNative)
MemoryHelper.FreeMemory(nativeValue);
}
#endregion
}
}
| |
//----------------------------------------------//
// Gamelogic Grids //
// http://www.gamelogic.co.za //
// Copyright (c) 2013 Gamelogic (Pty) Ltd //
//----------------------------------------------//
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gamelogic.Grids
{
/**
Defines extension methods for the IGrid interface.
This is implemented as an extension so that implementers need not
extend from a common base class, but provide it to their clients.
@version1_0
@ingroup Interface
*/
public static class GridExtensions
{
/**
Returns a new grid in the same shape as the given grid, with the same contents casted to the new type.
@version1_8
*/
public static IGrid<TNewCell, TPoint> CastValues<TNewCell, TPoint>(this IGrid<TPoint> grid)
where TPoint : IGridPoint<TPoint>
{
if (grid == null)
{
throw new ArgumentNullException("grid");
}
var newGrid = grid as IGrid<TNewCell, TPoint>;
if (newGrid != null) return newGrid;
newGrid = grid.CloneStructure<TNewCell>();
foreach (var point in grid)
{
newGrid[point] = (TNewCell) grid[point];
}
return newGrid;
}
/**
Returns a shallow copy of the given grid.
@version1_8
*/
public static IGrid<TCell, TPoint> Clone<TCell, TPoint>(this IGrid<TCell, TPoint> grid)
where TPoint : IGridPoint<TPoint>
{
if (grid == null)
{
throw new ArgumentNullException("grid");
}
var newGrid = grid.CloneStructure<TCell>();
foreach (var point in grid)
{
newGrid[point] = grid[point];
}
return newGrid;
}
/**
Only return neighbors of the point that are inside the grid, as defined by IsInside,
that also satisfies the predicate includePoint.
It is equivalent to GetNeighbors(point).Where(includePoint).
@version1_7
*/
public static IEnumerable<TPoint> GetNeighbors<TCell, TPoint>(
this IGrid<TCell, TPoint> grid,
TPoint point, Func<TPoint, bool> includePoint)
where TPoint : IGridPoint<TPoint>
{
return
(from neighbor in grid.GetAllNeighbors(point)
where grid.Contains(neighbor) && includePoint(neighbor)
select neighbor);
}
/**
Only return neighbors of the point that are inside the grid, as defined by IsInside,
whose associated cells also satisfy the predicate includeCell.
It is equivalent to GetNeighbors(point).Where(p => includeCell(grid[p])
@version1_7
*/
public static IEnumerable<TPoint> GetNeighbors<TCell, TPoint>(
this IGrid<TCell, TPoint> grid,
TPoint point, Func<TCell, bool> includeCell)
where TPoint : IGridPoint<TPoint>
{
return
(from neighbor in grid.GetAllNeighbors(point)
where grid.Contains(neighbor) && includeCell(grid[neighbor])
select neighbor);
}
/**
Returns all neighbors of this point that satisfies the condition,
regardless of whether they are in the grid or not.
*/
public static IEnumerable<TPoint> GetAllNeighbors<TCell, TPoint>(
this IGrid<TCell, TPoint> grid,
TPoint point, Func<TPoint, bool> includePoint)
where TPoint : IGridPoint<TPoint>
{
return grid.GetAllNeighbors(point).Where(includePoint);
}
/**
Returns a list of all points whose associated cells also satisfy the predicate include.
It is equivalent to GetNeighbors(point).Where(p => includeCell(grid[p])
@version1_7
*/
public static IEnumerable<TPoint> WhereCell<TCell, TPoint>(
this IGrid<TCell, TPoint> grid, Func<TCell, bool> include)
where TPoint : IGridPoint<TPoint>
{
return grid.Where(p => include(grid[p]));
}
/**
Only return neighbors of the point that are inside the grid, as defined by Contains.
*/
public static IEnumerable<TPoint> GetNeighbors<TCell, TPoint>(
this IGrid<TCell, TPoint> grid,
TPoint point)
where TPoint : IGridPoint<TPoint>
{
//return grid.GetNeighbors(point, (TPoint p) => true);
return
from neighbor in grid.GetAllNeighbors(point)
where grid.Contains(neighbor)
select neighbor;
}
/**
Returns whether the point is outside the grid.
\implementers This method must be consistent with IsInside, and hence
is not overridable.
*/
public static bool IsOutside<TCell, TPoint>(
this IGrid<TCell, TPoint> grid,
TPoint point)
where TPoint : IGridPoint<TPoint>
{
return !grid.Contains(point);
}
/**
Returns a list of cells that correspond to the list of points.
*/
public static IEnumerable<TCell> SelectValuesAt<TCell, TPoint>(
this IGrid<TCell, TPoint> grid,
IEnumerable<TPoint> pointList)
where TPoint : IGridPoint<TPoint>
{
return pointList.Select(x => grid[x]);
}
/**
Shuffles the contents of a grid.
@version1_6
*/
public static void Shuffle<TCell, TPoint>(
this IGrid<TCell, TPoint> grid)
where TPoint : IGridPoint<TPoint>
{
var points = grid.ToList();
if (points.Count <= 1)
{
return; //nothing to shuffle
}
var shuffledPoints = grid.ToList();
shuffledPoints.Shuffle();
var tmpGrid = grid.CloneStructure<TCell>();
for (int i = 0; i < points.Count; i++)
{
tmpGrid[points[i]] = grid[shuffledPoints[i]];
}
foreach (var point in grid)
{
grid[point] = tmpGrid[point];
}
}
/**
The same as `grid[point]`. This method is included to make
it easier to construct certain LINQ expressions, for example
grid.Select(grid.GetCell)
grid.Where(p => p.GetColor4_2() == 0).Select(grid.GetCell)
@version1_7
*/
public static TCell GetCell<TCell, TPoint>(
this IGrid<TCell, TPoint> grid, TPoint point)
where TPoint : IGridPoint<TPoint>
{
return grid[point];
}
/**
The same as `grid[point] = value`. This method is provided
to be consistent with GetCell.
@version1_7
*/
public static void SetCell<TCell, TPoint>(
this IGrid<TCell, TPoint> grid, TPoint point, TCell value)
where TPoint : IGridPoint<TPoint>
{
grid[point] = value;
}
/**
Returns the points in a grid neighborhood around the given center.
@version1_8
*/
public static IEnumerable<RectPoint> GetNeighborHood<T>(this RectGrid<T> grid, RectPoint center, int radius)
{
for (int i = center.X - radius; i <= center.X + radius; i++)
{
for (int j = center.Y - radius; j <= center.Y + radius; j++)
{
var neighborhoodPoint = new RectPoint(i, j);
if (grid.Contains(neighborhoodPoint))
{
yield return neighborhoodPoint;
}
}
}
}
/**
Fills all cells of a grid with the given value.
@version1_10
*/
public static void Fill<TCell, TPoint>(this IGrid<TCell, TPoint> grid, TCell value)
where TPoint : IGridPoint<TPoint>
{
foreach (var point in grid)
{
grid[point] = value;
}
}
/**
Fills all cells of a grid with the value returned by createValue.
@version1_10
*/
public static void Fill<TCell, TPoint>(this IGrid<TCell, TPoint> grid, Func<TCell> createValue)
where TPoint : IGridPoint<TPoint>
{
foreach (var point in grid)
{
grid[point] = createValue();
}
}
/**
Fills the cell of each point of a grid with the value returned by createValue when passed the point as a parameter.
@version1_10
*/
public static void Fill<TCell, TPoint>(this IGrid<TCell, TPoint> grid, Func<TPoint, TCell> createValue)
where TPoint : IGridPoint<TPoint>
{
foreach (var point in grid)
{
grid[point] = createValue(point);
}
}
/**
Clones the given grid, and fills all cells of the cloned grid with the given value.
@version1_10
*/
public static IGrid<TNewCell, TPoint> CloneStructure<TNewCell, TPoint>(this IGrid<TPoint> grid, TNewCell value)
where TPoint : IGridPoint<TPoint>
{
var newGrid = grid.CloneStructure<TNewCell>();
newGrid.Fill(value);
return newGrid;
}
/**
Clones the given grid, and fills all cells of the cloned grid
with the value returned by createValue.
@version1_10
*/
public static IGrid<TNewCell, TPoint> CloneStructure<TNewCell, TPoint>(this IGrid<TPoint> grid, Func<TNewCell> createValue)
where TPoint : IGridPoint<TPoint>
{
var newGrid = grid.CloneStructure<TNewCell>();
newGrid.Fill(createValue);
return newGrid;
}
/**
Clones the given grid, and fills the cell at each point of the cloned grid with the value
returned by createValue when the point is passed as a parameter.
@version1_10
*/
public static IGrid<TNewCell, TPoint> CloneStructure<TNewCell, TPoint>(this IGrid<TPoint> grid, Func<TPoint, TNewCell> createValue)
where TPoint : IGridPoint<TPoint>
{
var newGrid = grid.CloneStructure<TNewCell>();
newGrid.Fill(createValue);
return newGrid;
}
/**
Applies the given action to all cells in the grid.
Example:
grid.Apply(cell => cell.Color = Color.red);
@version1_10
*/
public static void Apply<TCell, TPoint>(this IGrid<TCell, TPoint> grid, Action<TCell> action)
where TPoint : IGridPoint<TPoint>
{
foreach (var cell in grid.Values)
{
action(cell);
}
}
/**
Transforms all values in this grid using the given transformation.
Example:
gridOfNumbers.TraformValues(x => x + 1);
@version1_10
*/
public static void TransformValues<TCell, TPoint>(this IGrid<TCell, TPoint> grid, Func<TCell, TCell> transformation)
where TPoint : IGridPoint<TPoint>
{
foreach (var point in grid)
{
grid[point] = transformation(grid[point]);
}
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Reflection;
using Autodesk.Revit;
using Autodesk.Revit.DB;
namespace Revit.SDK.Samples.AutoParameter.CS
{
/// <summary>
/// add parameters(family parameters/shared parameters) to the opened family file
/// the parameters are recorded in txt file following certain formats
/// </summary>
class FamilyParameterAssigner
{
#region Memeber Fields
private Autodesk.Revit.ApplicationServices.Application m_app;
private FamilyManager m_manager = null;
string m_assemblyPath;
// indicate whether the parameter files have been loaded. If yes, no need to load again.
bool m_paramLoaded;
// set the paramName as key of dictionary for exclusiveness (the names of parameters should be unique)
private Dictionary<string /*paramName*/, FamilyParam> m_familyParams;
private DefinitionFile m_sharedFile;
private string m_familyFilePath = string.Empty;
private string m_sharedFilePath = string.Empty;
#endregion
/// <summary>
/// constructor
/// </summary>
/// <param name="app">
/// the active revit application
/// </param>
/// <param name="doc">
/// the family document which will have parameters added in
/// </param>
public FamilyParameterAssigner(Autodesk.Revit.ApplicationServices.Application app, Document doc)
{
m_app = app;
m_manager = doc.FamilyManager;
m_familyParams = new Dictionary<string, FamilyParam>();
m_assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
m_paramLoaded = false;
}
/// <summary>
/// load the family parameter file (if exists) and shared parameter file (if exists)
/// only need to load once
/// </summary>
/// <returns>
/// if succeeded, return true; otherwise false
/// </returns>
public bool LoadParametersFromFile()
{
if (m_paramLoaded)
{
return true;
}
// load family parameter file
bool famParamFileExist;
bool succeeded = LoadFamilyParameterFromFile(out famParamFileExist);
if (!succeeded)
{
return false;
}
// load shared parameter file
bool sharedParamFileExist;
succeeded = LoadSharedParameterFromFile(out sharedParamFileExist);
if (!(famParamFileExist || sharedParamFileExist))
{
MessageManager.MessageBuff.AppendLine("Neither familyParameter.txt nor sharedParameter.txt exists in the assembly folder.");
return false;
}
if (!succeeded)
{
return false;
}
m_paramLoaded = true;
return true;
}
/// <summary>
/// load family parameters from the text file
/// </summary>
/// <returns>
/// return true if succeeded; otherwise false
/// </returns>
private bool LoadFamilyParameterFromFile(out bool exist)
{
exist = true;
// step 1: find the file "FamilyParameter.txt" and open it
string fileName = m_assemblyPath + "\\FamilyParameter.txt";
if (!File.Exists(fileName))
{
exist = false;
return true;
}
FileStream file = null;
StreamReader reader = null;
try
{
file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
reader = new StreamReader(file);
// step 2: read each line, if the line records the family parameter data, store it
// record the content of the current line
string line;
// record the row number of the current line
int lineNumber = 0;
while (null != (line = reader.ReadLine()))
{
++lineNumber;
// step 2.1: verify the line
// check whether the line is blank line (contains only whitespaces)
Match match = Regex.Match(line, @"^\s*$");
if (true == match.Success)
{
continue;
}
// check whether the line starts from "#" or "*" (comment line)
match = Regex.Match(line, @"\s*['#''*'].*");
if (true == match.Success)
{
continue;
}
// step 2.2: get the parameter data
// it's a valid line (has the format of "paramName paramGroup paramType isInstance", separate by tab or by spaces)
// split the line to an array containing parameter items (format of string[] {"paramName", "paramGroup", "paramType", "isInstance"})
string[] lineData = Regex.Split(line, @"\s+");
// check whether the array has blank items (containing only spaces)
List<string> values = new List<string>();
foreach (string data in lineData)
{
match = Regex.Match(data, @"^\s*$");
if (true == match.Success)
{
continue;
}
values.Add(data);
}
// verify the parameter items (should have 4 items exactly: paramName, paramGroup, paramType and isInstance)
if (4 != values.Count)
{
MessageManager.MessageBuff.Append("Loading family parameter data from \"FamilyParam.txt\".");
MessageManager.MessageBuff.Append("Line [\"" + line + "]\"" + "doesn't follow the valid format.\n");
return false;
}
// get the paramName
string paramName = values[0];
// get the paramGroup
string groupString = values[1];
// in case the groupString is format of "BuiltInParameterGroup.PG_Text", need to remove the "BuiltInParameterGroup.",
// keep the "PG_Text" only
int index = -1;
if (0 <= (index = groupString.ToLower().IndexOf("builtinparametergroup")))
{
// why +1? need to remove the "." after "builtinparametergroup"
groupString = groupString.Substring(index + 1 + "builtinparametergroup".Length);
}
BuiltInParameterGroup paramGroup = (BuiltInParameterGroup)Enum.Parse(typeof(BuiltInParameterGroup), groupString);
// get the paramType
string typeString = values[2];
if (0 <= (index = typeString.ToLower().IndexOf("parametertype")))
{
// why +1? need to remove the "." after "builtinparametergroup"
typeString = typeString.Substring(index + 1 + "parametertype".Length);
}
ParameterType paramType = (ParameterType)Enum.Parse(typeof(ParameterType), typeString);
// get data "isInstance"
string isInstanceString = values[3];
bool isInstance = Convert.ToBoolean(isInstanceString);
// step 2.3: store the parameter fetched, check for exclusiveness (as the names of parameters should keep unique)
FamilyParam param = new FamilyParam(paramName, paramGroup, paramType, isInstance, lineNumber);
// the family parameter with the same name has already been stored to the dictionary, raise an error
if (m_familyParams.ContainsKey(paramName))
{
FamilyParam duplicatedParam = m_familyParams[paramName];
string warning = "Line " + param.Line + "has a duplicate parameter name with Line " + duplicatedParam.Line + "\n";
MessageManager.MessageBuff.Append(warning);
continue;
}
m_familyParams.Add(paramName, param);
}
}
catch (System.Exception e)
{
MessageManager.MessageBuff.AppendLine(e.Message);
return false;
}
finally
{
if (null != reader)
{
reader.Close();
}
if (null != file)
{
file.Close();
}
}
return true;
}
/// <summary>
/// load family parameters from the text file
/// </summary>
/// <param name="exist">
/// indicate whether the shared parameter file exists
/// </param>
/// <returns>
/// return true if succeeded; otherwise false
/// </returns>
private bool LoadSharedParameterFromFile(out bool exist)
{
exist = true;
string filePath = m_assemblyPath + "\\SharedParameter.txt";
if (!File.Exists(filePath))
{
exist = false;
return true;
}
m_app.SharedParametersFilename = filePath;
try
{
m_sharedFile = m_app.OpenSharedParameterFile();
}
catch (System.Exception e)
{
MessageManager.MessageBuff.AppendLine(e.Message);
return false;
}
return true;
}
/// <summary>
/// add parameters to the family file
/// </summary>
/// <returns>
/// if succeeded, return true; otherwise false
/// </returns>
public bool AddParameters()
{
// add the loaded family parameters to the family
bool succeeded = AddFamilyParameter();
if (!succeeded)
{
return false;
}
// add the loaded shared parameters to the family
succeeded = AddSharedParameter();
if (!succeeded)
{
return false;
}
return true;
}
/// <summary>
/// add family parameter to the family
/// </summary>
/// <returns>
/// if succeeded, return true; otherwise false
/// </returns>
private bool AddFamilyParameter()
{
bool allParamValid = true;
if (File.Exists(m_familyFilePath) &&
0 == m_familyParams.Count)
{
MessageManager.MessageBuff.AppendLine("No family parameter available for adding.");
return false;
}
foreach (FamilyParameter param in m_manager.Parameters)
{
string name = param.Definition.Name;
if (m_familyParams.ContainsKey(name))
{
allParamValid = false;
FamilyParam famParam = m_familyParams[name];
MessageManager.MessageBuff.Append("Line " + famParam.Line + ": paramName \"" + famParam.Name + "\"already exists in the family document.\n");
}
}
// there're errors in the family parameter text file
if (!allParamValid)
{
return false;
}
foreach (FamilyParam param in m_familyParams.Values)
{
try
{
m_manager.AddParameter(param.Name, param.Group, param.Type, param.IsInstance);
}
catch(Exception e)
{
MessageManager.MessageBuff.AppendLine(e.Message);
return false;
}
}
return true;
}
/// <summary>
/// load shared parameters from shared parameter file and add them to family
/// </summary>
/// <returns>
/// if succeeded, return true; otherwise false
/// </returns>
private bool AddSharedParameter()
{
if (File.Exists(m_sharedFilePath) &&
null == m_sharedFile)
{
MessageManager.MessageBuff.AppendLine("SharedParameter.txt has an invalid format.");
return false;
}
foreach (DefinitionGroup group in m_sharedFile.Groups)
{
foreach (ExternalDefinition def in group.Definitions)
{
// check whether the parameter already exists in the document
FamilyParameter param = m_manager.get_Parameter(def.Name);
if (null != param)
{
continue;
}
try
{
m_manager.AddParameter(def, def.ParameterGroup, true);
}
catch (System.Exception e)
{
MessageManager.MessageBuff.AppendLine(e.Message);
return false;
}
}
}
return true;
}
}// end of class "FamilyParameterAssigner"
/// <summary>
/// record the data of a parameter: its name, its group, etc
/// </summary>
class FamilyParam
{
string m_name;
/// <summary>
/// the caption of the parameter
/// </summary>
public string Name
{
get { return m_name; }
}
BuiltInParameterGroup m_group;
/// <summary>
/// the group of the parameter
/// </summary>
public BuiltInParameterGroup Group
{
get { return m_group; }
}
ParameterType m_type;
/// <summary>
/// the type of the parameter
/// </summary>
public ParameterType Type
{
get { return m_type; }
}
bool m_isInstance;
/// <summary>
/// indicate whether the parameter is an instance parameter or a type parameter
/// </summary>
public bool IsInstance
{
get { return m_isInstance; }
}
int m_line;
/// <summary>
/// record the location of this parameter in the family parameter file
/// </summary>
public int Line
{
get { return m_line; }
}
/// <summary>
/// default constructor, hide this by making it "private"
/// </summary>
private FamilyParam()
{
}
/// <summary>
/// constructor which exposes for invoking
/// </summary>
/// <param name="name">
/// parameter name
/// </param>
/// <param name="group">
/// indicate which group the parameter belongs to
/// </param>
/// <param name="type">
/// the type of the parameter
/// </param>
/// <param name="isInstance">
/// indicate whethe the parameter is an instance parameter
/// </param>
/// <param name="line">
/// record the location of this parameter in the family parameter file
/// </param>
public FamilyParam(string name, BuiltInParameterGroup group, ParameterType type, bool isInstance, int line)
{
m_name = name;
m_group = group;
m_type = type;
m_isInstance = isInstance;
m_line = line;
}
}
}
| |
/*
* Translation into C# and Magnesium interface 2016
* Vulkan Example - Basic indexed triangle rendering by 2016 by Copyright (C) Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
using Magnesium;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace TriangleDemo
{
public class VulkanExample : IDisposable
{
// Vertex buffer and attributes
class VertexBufferInfo
{
public IMgDeviceMemory memory; // Handle to the device memory for this buffer
public IMgBuffer buffer; // Handle to the Vulkan buffer object that the memory is bound to
public MgPipelineVertexInputStateCreateInfo inputState;
public MgVertexInputBindingDescription inputBinding;
public MgVertexInputAttributeDescription[] inputAttributes;
}
VertexBufferInfo vertices = new VertexBufferInfo();
struct IndicesInfo
{
public IMgDeviceMemory memory;
public IMgBuffer buffer;
public UInt32 count;
}
IndicesInfo indices = new IndicesInfo();
private IMgGraphicsConfiguration mConfiguration;
// Uniform block object
struct UniformData
{
public IMgDeviceMemory memory;
public IMgBuffer buffer;
public MgDescriptorBufferInfo descriptor;
}
struct UniformBufferObject
{
public Matrix4 projectionMatrix;
public Matrix4 modelMatrix;
public Matrix4 viewMatrix;
};
UniformBufferObject uboVS;
UniformData uniformDataVS = new UniformData();
// The pipeline layout is used by a pipline to access the descriptor sets
// It defines interface (without binding any actual data) between the shader stages used by the pipeline and the shader resources
// A pipeline layout can be shared among multiple pipelines as long as their interfaces match
IMgPipelineLayout mPipelineLayout;
// Pipelines (often called "pipeline state objects") are used to bake all states that affect a pipeline
// While in OpenGL every state can be changed at (almost) any time, Vulkan requires to layout the graphics (and compute) pipeline states upfront
// So for each combination of non-dynamic pipeline states you need a new pipeline (there are a few exceptions to this not discussed here)
// Even though this adds a new dimension of planing ahead, it's a great opportunity for performance optimizations by the driver
IMgPipeline mPipeline;
// The descriptor set layout describes the shader binding layout (without actually referencing descriptor)
// Like the pipeline layout it's pretty much a blueprint and can be used with different descriptor sets as long as their layout matches
IMgDescriptorSetLayout mDescriptorSetLayout;
// The descriptor set stores the resources bound to the binding points in a shader
// It connects the binding points of the different shaders with the buffers and images used for those bindings
IMgDescriptorSet mDescriptorSet;
// Synchronization primitives
// Synchronization is an important concept of Vulkan that OpenGL mostly hid away. Getting this right is crucial to using Vulkan.
// Semaphores
// Used to coordinate operations within the graphics queue and ensure correct command ordering
IMgSemaphore mPresentCompleteSemaphore;
IMgSemaphore mRenderCompleteSemaphore;
// Fences
// Used to check the completion of queue operations (e.g. command buffer execution)
List<IMgFence> mWaitFences = new List<IMgFence>();
private uint mWidth;
private uint mHeight;
private IMgGraphicsDevice mGraphicsDevice;
private IMgDescriptorPool mDescriptorPool;
private IMgCommandBuffer mPrePresentCmdBuffer;
private IMgCommandBuffer mPostPresentCmdBuffer;
private IMgPresentationLayer mPresentationLayer;
public VulkanExample
(
IMgGraphicsConfiguration configuration,
IMgSwapchainCollection swapchains,
IMgGraphicsDevice graphicsDevice,
IMgPresentationLayer presentationLayer,
ITriangleDemoShaderPath shaderPath
)
{
mConfiguration = configuration;
mSwapchains = swapchains;
mGraphicsDevice = graphicsDevice;
mPresentationLayer = presentationLayer;
mTrianglePath = shaderPath;
mWidth = 1280U;
mHeight = 720U;
try
{
mConfiguration.Initialize(mWidth, mHeight);
initSwapchain(mWidth, mHeight);
prepare();
}
catch(Exception ex)
{
throw ex;
}
}
private IMgSwapchainCollection mSwapchains;
private void initSwapchain(uint width, uint height)
{
Debug.Assert(mConfiguration.Partition != null);
const int NO_OF_BUFFERS = 1;
var buffers = new IMgCommandBuffer[NO_OF_BUFFERS];
var pAllocateInfo = new MgCommandBufferAllocateInfo
{
CommandBufferCount = NO_OF_BUFFERS,
CommandPool = mConfiguration.Partition.CommandPool,
Level = MgCommandBufferLevel.PRIMARY,
};
mConfiguration.Device.AllocateCommandBuffers(pAllocateInfo, buffers);
var createInfo = new MgGraphicsDeviceCreateInfo
{
Samples = MgSampleCountFlagBits.COUNT_1_BIT,
Color = MgFormat.R8G8B8A8_UINT,
DepthStencil = MgFormat.D24_UNORM_S8_UINT,
Width = mWidth,
Height = mHeight,
};
var setupCmdBuffer = buffers[0];
var cmdBufInfo = new MgCommandBufferBeginInfo
{
};
var err = setupCmdBuffer.BeginCommandBuffer(cmdBufInfo);
Debug.Assert(err == Result.SUCCESS);
mGraphicsDevice.Create(setupCmdBuffer, mSwapchains, createInfo);
err = setupCmdBuffer.EndCommandBuffer();
Debug.Assert(err == Result.SUCCESS);
var submission = new[] {
new MgSubmitInfo
{
CommandBuffers = new IMgCommandBuffer[]
{
buffers[0],
},
}
};
err = mConfiguration.Queue.QueueSubmit(submission, null);
Debug.Assert(err == Result.SUCCESS);
mConfiguration.Queue.QueueWaitIdle();
mConfiguration.Device.FreeCommandBuffers(mConfiguration.Partition.CommandPool, buffers);
}
#region prepare
private bool mPrepared = false;
void prepare()
{
BeforePrepare();
prepareSynchronizationPrimitives();
prepareVertices();
prepareUniformBuffers();
setupDescriptorSetLayout();
preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers();
mPrepared = true;
}
private void BeforePrepare()
{
createCommandBuffers();
}
// Create the Vulkan synchronization primitives used in this example
void prepareSynchronizationPrimitives()
{
// Semaphores (Used for correct command ordering)
var semaphoreCreateInfo = new MgSemaphoreCreateInfo { };
Debug.Assert(mConfiguration.Device != null);
// Semaphore used to ensures that image presentation is complete before starting to submit again
var err = mConfiguration.Device.CreateSemaphore(semaphoreCreateInfo, null, out mPresentCompleteSemaphore);
Debug.Assert(err == Result.SUCCESS);
// Semaphore used to ensures that all commands submitted have been finished before submitting the image to the queue
err = mConfiguration.Device.CreateSemaphore(semaphoreCreateInfo, null, out mRenderCompleteSemaphore);
Debug.Assert(err == Result.SUCCESS);
// Fences (Used to check draw command buffer completion)
var fenceCreateInfo = new MgFenceCreateInfo {
Flags = MgFenceCreateFlagBits.SIGNALED_BIT,
};
// Create in signaled state so we don't wait on first render of each command buffer
var noOfCommandBuffers = drawCmdBuffers.Length; // TODO: drawCmdBuffers.Length;
for (var i = 0; i < noOfCommandBuffers; ++i)
{
IMgFence fence;
err = mConfiguration.Device.CreateFence(fenceCreateInfo, null, out fence);
Debug.Assert(err == Result.SUCCESS);
mWaitFences.Add(fence);
}
}
struct TriangleVertex
{
public Vector3 position;
public Vector3 color;
};
class StagingBuffer
{
public IMgDeviceMemory memory;
public IMgBuffer buffer;
};
// Prepare vertex and index buffers for an indexed triangle
// Also uploads them to device local memory using staging and initializes vertex input and attribute binding to match the vertex shader
void prepareVertices()
{
// A note on memory management in Vulkan in general:
// This is a very complex topic and while it's fine for an example application to to small individual memory allocations that is not
// what should be done a real-world application, where you should allocate large chunkgs of memory at once isntead.
// Setup vertices
TriangleVertex[] vertexBuffer =
{
new TriangleVertex{
position =new Vector3(1.0f, 1.0f, 0.0f),
color = new Vector3( 1.0f, 0.0f, 0.0f )
},
new TriangleVertex{
position =new Vector3(-1.0f, 1.0f, 0.0f ),
color = new Vector3( 0.0f, 1.0f, 0.0f )
},
new TriangleVertex{
position =new Vector3( 0.0f, -1.0f, 0.0f ),
color = new Vector3( 0.0f, 0.0f, 1.0f )
},
};
var structSize = Marshal.SizeOf(typeof(TriangleVertex));
var vertexBufferSize = (ulong)(vertexBuffer.Length * structSize);
// Setup indices
UInt32[] indexBuffer = { 0, 1, 2 };
indices.count = (uint)indexBuffer.Length;
var indexBufferSize = indices.count * sizeof(UInt32);
// Static data like vertex and index buffer should be stored on the device memory
// for optimal (and fastest) access by the GPU
//
// To achieve this we use so-called "staging buffers" :
// - Create a buffer that's visible to the host (and can be mapped)
// - Copy the data to this buffer
// - Create another buffer that's local on the device (VRAM) with the same size
// - Copy the data from the host to the device using a command buffer
// - Delete the host visible (staging) buffer
// - Use the device local buffers for rendering
var stagingBuffers = new
{
vertices = new StagingBuffer(),
indices = new StagingBuffer(),
};
// HOST_VISIBLE STAGING Vertex buffer
{
var vertexBufferInfo = new MgBufferCreateInfo
{
Size = vertexBufferSize,
// Buffer is used as the copy source
Usage = MgBufferUsageFlagBits.TRANSFER_SRC_BIT,
};
// Create a host-visible buffer to copy the vertex data to (staging buffer)
var err = mConfiguration.Device.CreateBuffer(vertexBufferInfo, null, out stagingBuffers.vertices.buffer);
Debug.Assert(err == Result.SUCCESS);
MgMemoryRequirements memReqs;
mConfiguration.Device.GetBufferMemoryRequirements(stagingBuffers.vertices.buffer, out memReqs);
// Request a host visible memory type that can be used to copy our data do
// Also request it to be coherent, so that writes are visible to the GPU right after unmapping the buffer
uint typeIndex;
var isValid = mConfiguration.Partition.GetMemoryType(memReqs.MemoryTypeBits,
MgMemoryPropertyFlagBits.HOST_VISIBLE_BIT | MgMemoryPropertyFlagBits.HOST_COHERENT_BIT,
out typeIndex);
Debug.Assert(isValid);
MgMemoryAllocateInfo memAlloc = new MgMemoryAllocateInfo
{
AllocationSize = memReqs.Size,
MemoryTypeIndex = typeIndex,
};
err = mConfiguration.Device.AllocateMemory(memAlloc, null, out stagingBuffers.vertices.memory);
Debug.Assert(err == Result.SUCCESS);
// Map and copy
IntPtr data;
err = stagingBuffers.vertices.memory.MapMemory(mConfiguration.Device, 0, memAlloc.AllocationSize, 0, out data);
Debug.Assert(err == Result.SUCCESS);
var offset = 0;
foreach (var vertex in vertexBuffer)
{
IntPtr dest = IntPtr.Add(data, offset);
Marshal.StructureToPtr(vertex, dest, false);
offset += structSize;
}
stagingBuffers.vertices.memory.UnmapMemory(mConfiguration.Device);
stagingBuffers.vertices.buffer.BindBufferMemory(mConfiguration.Device, stagingBuffers.vertices.memory, 0);
Debug.Assert(err == Result.SUCCESS);
}
// DEVICE_LOCAL Vertex buffer
{
var vertexBufferInfo = new MgBufferCreateInfo
{
Size = vertexBufferSize,
// Create a device local buffer to which the (host local) vertex data will be copied and which will be used for rendering
Usage = MgBufferUsageFlagBits.VERTEX_BUFFER_BIT | MgBufferUsageFlagBits.TRANSFER_DST_BIT,
};
var err = mConfiguration.Device.CreateBuffer(vertexBufferInfo, null, out vertices.buffer);
Debug.Assert(err == Result.SUCCESS);
MgMemoryRequirements memReqs;
mConfiguration.Device.GetBufferMemoryRequirements(vertices.buffer, out memReqs);
uint typeIndex;
var isValid = mConfiguration.Partition.GetMemoryType(memReqs.MemoryTypeBits, MgMemoryPropertyFlagBits.DEVICE_LOCAL_BIT, out typeIndex);
Debug.Assert(isValid);
var memAlloc = new MgMemoryAllocateInfo
{
AllocationSize = memReqs.Size,
MemoryTypeIndex = typeIndex,
};
err = mConfiguration.Device.AllocateMemory(memAlloc, null, out vertices.memory);
Debug.Assert(err == Result.SUCCESS);
err = vertices.buffer.BindBufferMemory(mConfiguration.Device, vertices.memory, 0);
Debug.Assert(err == Result.SUCCESS);
}
// HOST_VISIBLE Index buffer
{
var indexbufferInfo = new MgBufferCreateInfo
{
Size = indexBufferSize,
Usage = MgBufferUsageFlagBits.TRANSFER_SRC_BIT,
};
// Copy index data to a buffer visible to the host (staging buffer)
var err = mConfiguration.Device.CreateBuffer(indexbufferInfo, null, out stagingBuffers.indices.buffer);
Debug.Assert(err == Result.SUCCESS);
MgMemoryRequirements memReqs;
mConfiguration.Device.GetBufferMemoryRequirements(stagingBuffers.indices.buffer, out memReqs);
uint typeIndex;
var isValid = mConfiguration.Partition.GetMemoryType(memReqs.MemoryTypeBits,
MgMemoryPropertyFlagBits.HOST_VISIBLE_BIT | MgMemoryPropertyFlagBits.HOST_COHERENT_BIT,
out typeIndex);
Debug.Assert(isValid);
var memAlloc = new MgMemoryAllocateInfo
{
AllocationSize = memReqs.Size,
MemoryTypeIndex = typeIndex,
};
err = mConfiguration.Device.AllocateMemory(memAlloc, null, out stagingBuffers.indices.memory);
Debug.Assert(err == Result.SUCCESS);
IntPtr data;
err = stagingBuffers.indices.memory.MapMemory(mConfiguration.Device, 0, indexBufferSize, 0, out data);
Debug.Assert(err == Result.SUCCESS);
var uintBuffer = new byte[indexBufferSize];
var bufferSize = (int)indexBufferSize;
Buffer.BlockCopy(indexBuffer, 0, uintBuffer, 0, bufferSize);
Marshal.Copy(uintBuffer, 0, data, bufferSize);
stagingBuffers.indices.memory.UnmapMemory(mConfiguration.Device);
err = stagingBuffers.indices.buffer.BindBufferMemory(mConfiguration.Device, stagingBuffers.indices.memory, 0);
Debug.Assert(err == Result.SUCCESS);
}
// DEVICE_LOCAL index buffer
{
// Create destination buffer with device only visibility
var indexbufferInfo = new MgBufferCreateInfo
{
Size = indexBufferSize,
Usage = MgBufferUsageFlagBits.INDEX_BUFFER_BIT | MgBufferUsageFlagBits.TRANSFER_DST_BIT,
};
var err = mConfiguration.Device.CreateBuffer(indexbufferInfo, null, out indices.buffer);
Debug.Assert(err == Result.SUCCESS);
MgMemoryRequirements memReqs;
mConfiguration.Device.GetBufferMemoryRequirements(indices.buffer, out memReqs);
uint typeIndex;
var isValid = mConfiguration.Partition.GetMemoryType(memReqs.MemoryTypeBits, MgMemoryPropertyFlagBits.DEVICE_LOCAL_BIT, out typeIndex);
Debug.Assert(isValid);
var memAlloc = new MgMemoryAllocateInfo
{
AllocationSize = memReqs.Size,
MemoryTypeIndex = typeIndex,
};
err = mConfiguration.Device.AllocateMemory(memAlloc, null, out indices.memory);
Debug.Assert(err == Result.SUCCESS);
err = indices.buffer.BindBufferMemory(mConfiguration.Device, indices.memory, 0);
Debug.Assert(err == Result.SUCCESS);
}
{
var cmdBufferBeginInfo = new MgCommandBufferBeginInfo
{
};
// Buffer copies have to be submitted to a queue, so we need a command buffer for them
// Note: Some devices offer a dedicated transfer queue (with only the transfer bit set) that may be faster when doing lots of copies
IMgCommandBuffer copyCmd = getCommandBuffer(true);
// Put buffer region copies into command buffer
// Vertex buffer
copyCmd.CmdCopyBuffer(
stagingBuffers.vertices.buffer,
vertices.buffer,
new[]
{
new MgBufferCopy
{
Size = vertexBufferSize,
}
}
);
// Index buffer
copyCmd.CmdCopyBuffer(stagingBuffers.indices.buffer, indices.buffer,
new[]
{
new MgBufferCopy
{
Size = indexBufferSize,
}
});
// Flushing the command buffer will also submit it to the queue and uses a fence to ensure that all commands have been executed before returning
flushCommandBuffer(copyCmd);
// Destroy staging buffers
// Note: Staging buffer must not be deleted before the copies have been submitted and executed
stagingBuffers.vertices.buffer.DestroyBuffer(mConfiguration.Device, null);
stagingBuffers.vertices.memory.FreeMemory(mConfiguration.Device, null);
stagingBuffers.indices.buffer.DestroyBuffer(mConfiguration.Device, null);
stagingBuffers.indices.memory.FreeMemory(mConfiguration.Device, null);
}
// Vertex input binding
const uint VERTEX_BUFFER_BIND_ID = 0;
vertices.inputBinding = new MgVertexInputBindingDescription
{
Binding = VERTEX_BUFFER_BIND_ID,
Stride = (uint) structSize,
InputRate = MgVertexInputRate.VERTEX,
};
// Inpute attribute binding describe shader attribute locations and memory layouts
// These match the following shader layout (see triangle.vert):
// layout (location = 0) in vec3 inPos;
// layout (location = 1) in vec3 inColor;
var vertexSize = (uint) Marshal.SizeOf(typeof(Vector3));
vertices.inputAttributes = new MgVertexInputAttributeDescription[]
{
new MgVertexInputAttributeDescription
{
// Attribute location 0: Position
Binding = VERTEX_BUFFER_BIND_ID,
Location = 0,
Format = MgFormat.R32G32B32_SFLOAT,
Offset = 0,
},
new MgVertexInputAttributeDescription
{
// Attribute location 1: Color
Binding = VERTEX_BUFFER_BIND_ID,
Location = 1,
Format = MgFormat.R32G32B32_SFLOAT,
Offset = vertexSize,
}
};
// Assign to the vertex input state used for pipeline creation
vertices.inputState = new MgPipelineVertexInputStateCreateInfo
{
VertexBindingDescriptions = new MgVertexInputBindingDescription[]
{
vertices.inputBinding,
},
VertexAttributeDescriptions = vertices.inputAttributes,
};
}
// Get a new command buffer from the command pool
// If begin is true, the command buffer is also started so we can start adding commands
IMgCommandBuffer getCommandBuffer(bool begin)
{
var buffers = new IMgCommandBuffer[1];
var cmdBufAllocateInfo = new MgCommandBufferAllocateInfo
{
CommandPool = mConfiguration.Partition.CommandPool,
Level = MgCommandBufferLevel.PRIMARY,
CommandBufferCount = 1,
};
var err = mConfiguration.Device.AllocateCommandBuffers(cmdBufAllocateInfo, buffers);
Debug.Assert(err == Result.SUCCESS);
var cmdBuf = buffers[0];
// If requested, also start the new command buffer
if (begin)
{
var cmdBufInfo = new MgCommandBufferBeginInfo
{
};
err = cmdBuf.BeginCommandBuffer(cmdBufInfo);
Debug.Assert(err == Result.SUCCESS);
}
return cmdBuf;
}
// End the command buffer and submit it to the queue
// Uses a fence to ensure command buffer has finished executing before deleting it
void flushCommandBuffer(IMgCommandBuffer commandBuffer)
{
Debug.Assert(commandBuffer != null);
var err = commandBuffer.EndCommandBuffer();
Debug.Assert(err == Result.SUCCESS);
var submitInfos = new MgSubmitInfo[]
{
new MgSubmitInfo
{
CommandBuffers = new []
{
commandBuffer
}
}
};
// Create fence to ensure that the command buffer has finished executing
var fenceCreateInfo = new MgFenceCreateInfo
{
};
IMgFence fence;
err = mConfiguration.Device.CreateFence(fenceCreateInfo, null, out fence);
Debug.Assert(err == Result.SUCCESS);
// Submit to the queue
err = mConfiguration.Queue.QueueSubmit(submitInfos, fence);
Debug.Assert(err == Result.SUCCESS);
// Mg.OpenGL
err = mConfiguration.Queue.QueueWaitIdle();
Debug.Assert(err == Result.SUCCESS);
// Wait for the fence to signal that command buffer has finished executing
err = mConfiguration.Device.WaitForFences(new[] { fence }, true, ulong.MaxValue);
Debug.Assert(err == Result.SUCCESS);
fence.DestroyFence(mConfiguration.Device, null);
mConfiguration.Device.FreeCommandBuffers(mConfiguration.Partition.CommandPool, new[] { commandBuffer } );
}
void prepareUniformBuffers()
{
var structSize = (uint)Marshal.SizeOf(typeof(UniformBufferObject));
// Vertex shader uniform buffer block
MgBufferCreateInfo bufferInfo = new MgBufferCreateInfo
{
Size = structSize,
// This buffer will be used as a uniform buffer
Usage = MgBufferUsageFlagBits.UNIFORM_BUFFER_BIT,
};
// Create a new buffer
var err = mConfiguration.Device.CreateBuffer(bufferInfo, null, out uniformDataVS.buffer);
Debug.Assert(err == Result.SUCCESS);
// Prepare and initialize a uniform buffer block containing shader uniforms
// Single uniforms like in OpenGL are no longer present in Vulkan. All Shader uniforms are passed via uniform buffer blocks
MgMemoryRequirements memReqs;
// Get memory requirements including size, alignment and memory type
mConfiguration.Device.GetBufferMemoryRequirements(uniformDataVS.buffer, out memReqs);
// Get the memory type index that supports host visibile memory access
// Most implementations offer multiple memory types and selecting the correct one to allocate memory from is crucial
// We also want the buffer to be host coherent so we don't have to flush (or sync after every update.
// Note: This may affect performance so you might not want to do this in a real world application that updates buffers on a regular base
uint typeIndex;
var isValid = mConfiguration.Partition.GetMemoryType(memReqs.MemoryTypeBits, MgMemoryPropertyFlagBits.HOST_VISIBLE_BIT | MgMemoryPropertyFlagBits.HOST_COHERENT_BIT, out typeIndex);
Debug.Assert(isValid);
MgMemoryAllocateInfo allocInfo = new MgMemoryAllocateInfo
{
AllocationSize = memReqs.Size,
MemoryTypeIndex = typeIndex,
};
// Allocate memory for the uniform buffer
err = mConfiguration.Device.AllocateMemory(allocInfo, null, out uniformDataVS.memory);
Debug.Assert(err == Result.SUCCESS);
// Bind memory to buffer
err = uniformDataVS.buffer.BindBufferMemory(mConfiguration.Device, uniformDataVS.memory, 0);
Debug.Assert(err == Result.SUCCESS);
// Store information in the uniform's descriptor that is used by the descriptor set
uniformDataVS.descriptor = new MgDescriptorBufferInfo
{
Buffer = uniformDataVS.buffer,
Offset = 0,
Range = structSize,
};
updateUniformBuffers();
}
void setupDescriptorSetLayout()
{
// Setup layout of descriptors used in this example
// Basically connects the different shader stages to descriptors for binding uniform buffers, image samplers, etc.
// So every shader binding should map to one descriptor set layout binding
var descriptorLayout = new MgDescriptorSetLayoutCreateInfo
{
Bindings = new[]
{
// Binding 0: Uniform buffer (Vertex shader)
new MgDescriptorSetLayoutBinding
{
DescriptorCount = 1,
StageFlags = MgShaderStageFlagBits.VERTEX_BIT,
ImmutableSamplers = null,
DescriptorType = MgDescriptorType.UNIFORM_BUFFER,
Binding = 0,
}
},
};
var err = mConfiguration.Device.CreateDescriptorSetLayout(descriptorLayout, null, out mDescriptorSetLayout);
Debug.Assert(err == Result.SUCCESS);
// Create the pipeline layout that is used to generate the rendering pipelines that are based on this descriptor set layout
// In a more complex scenario you would have different pipeline layouts for different descriptor set layouts that could be reused
var pPipelineLayoutCreateInfo = new MgPipelineLayoutCreateInfo
{
SetLayouts = new IMgDescriptorSetLayout[]
{
mDescriptorSetLayout,
}
};
err = mConfiguration.Device.CreatePipelineLayout(pPipelineLayoutCreateInfo, null, out mPipelineLayout);
Debug.Assert(err == Result.SUCCESS);
}
void preparePipelines()
{
// System.IO.File.OpenRead("shaders/triangle.vert.spv")
using (var vertFs = mTrianglePath.OpenVertexShader())
// System.IO.File.OpenRead("shaders/triangle.frag.spv")
using (var fragFs = mTrianglePath.OpenFragmentShader())
{
// Load shaders
// Vulkan loads it's shaders from an immediate binary representation called SPIR-V
// Shaders are compiled offline from e.g. GLSL using the reference glslang compiler
IMgShaderModule vsModule;
{
var vsCreateInfo = new MgShaderModuleCreateInfo
{
Code = vertFs,
CodeSize = new UIntPtr((ulong)vertFs.Length),
};
// shaderStages[0] = loadShader(getAssetPath() + "shaders/triangle.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
mConfiguration.Device.CreateShaderModule(vsCreateInfo, null, out vsModule);
}
IMgShaderModule fsModule;
{
var fsCreateInfo = new MgShaderModuleCreateInfo
{
Code = fragFs,
CodeSize = new UIntPtr((ulong)fragFs.Length),
};
// shaderStages[1] = loadShader(getAssetPath() + "shaders/triangle.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
mConfiguration.Device.CreateShaderModule(fsCreateInfo, null, out fsModule);
}
// Create the graphics pipeline used in this example
// Vulkan uses the concept of rendering pipelines to encapsulate fixed states, replacing OpenGL's complex state machine
// A pipeline is then stored and hashed on the GPU making pipeline changes very fast
// Note: There are still a few dynamic states that are not directly part of the pipeline (but the info that they are used is)
var pipelineCreateInfo = new MgGraphicsPipelineCreateInfo
{
Stages = new MgPipelineShaderStageCreateInfo[]
{
new MgPipelineShaderStageCreateInfo
{
Stage = MgShaderStageFlagBits.VERTEX_BIT,
Module = vsModule,
Name = "vertFunc",
},
new MgPipelineShaderStageCreateInfo
{
Stage = MgShaderStageFlagBits.FRAGMENT_BIT,
Module = fsModule,
Name = "fragFunc",
},
},
VertexInputState = vertices.inputState,
// Construct the differnent states making up the pipeline
InputAssemblyState = new MgPipelineInputAssemblyStateCreateInfo
{
// Input assembly state describes how primitives are assembled
// This pipeline will assemble vertex data as a triangle lists (though we only use one triangle)
Topology = MgPrimitiveTopology.TRIANGLE_LIST,
},
// Rasterization state
RasterizationState = new MgPipelineRasterizationStateCreateInfo
{
PolygonMode = MgPolygonMode.FILL,
CullMode = MgCullModeFlagBits.NONE,
FrontFace = MgFrontFace.COUNTER_CLOCKWISE,
DepthClampEnable = false,
RasterizerDiscardEnable = false,
DepthBiasEnable = false,
LineWidth = 1.0f,
},
// Color blend state describes how blend factors are calculated (if used)
// We need one blend attachment state per color attachment (even if blending is not used
ColorBlendState = new MgPipelineColorBlendStateCreateInfo
{
Attachments = new MgPipelineColorBlendAttachmentState[]
{
new MgPipelineColorBlendAttachmentState
{
ColorWriteMask = MgColorComponentFlagBits.R_BIT | MgColorComponentFlagBits.G_BIT | MgColorComponentFlagBits.B_BIT | MgColorComponentFlagBits.A_BIT,
BlendEnable = false,
}
},
},
// Multi sampling state
// This example does not make use fo multi sampling (for anti-aliasing), the state must still be set and passed to the pipeline
MultisampleState = new MgPipelineMultisampleStateCreateInfo
{
RasterizationSamples = MgSampleCountFlagBits.COUNT_1_BIT,
SampleMask = null,
},
// The layout used for this pipeline (can be shared among multiple pipelines using the same layout)
Layout = mPipelineLayout,
// Renderpass this pipeline is attached to
RenderPass = mGraphicsDevice.Renderpass,
// Viewport state sets the number of viewports and scissor used in this pipeline
// Note: This is actually overriden by the dynamic states (see below)
ViewportState = null,
// Depth and stencil state containing depth and stencil compare and test operations
// We only use depth tests and want depth tests and writes to be enabled and compare with less or equal
DepthStencilState = new MgPipelineDepthStencilStateCreateInfo
{
DepthTestEnable = true,
DepthWriteEnable = true,
DepthCompareOp = MgCompareOp.LESS_OR_EQUAL,
DepthBoundsTestEnable = false,
Back = new MgStencilOpState
{
FailOp = MgStencilOp.KEEP,
PassOp = MgStencilOp.KEEP,
CompareOp = MgCompareOp.ALWAYS,
},
StencilTestEnable = false,
Front = new MgStencilOpState
{
FailOp = MgStencilOp.KEEP,
PassOp = MgStencilOp.KEEP,
CompareOp = MgCompareOp.ALWAYS,
},
},
// Enable dynamic states
// Most states are baked into the pipeline, but there are still a few dynamic states that can be changed within a command buffer
// To be able to change these we need do specify which dynamic states will be changed using this pipeline. Their actual states are set later on in the command buffer.
// For this example we will set the viewport and scissor using dynamic states
DynamicState = new MgPipelineDynamicStateCreateInfo
{
DynamicStates = new[]
{
MgDynamicState.VIEWPORT,
MgDynamicState.SCISSOR,
}
},
};
IMgPipeline[] pipelines;
// Create rendering pipeline using the specified states
var err = mConfiguration.Device.CreateGraphicsPipelines(null, new[] { pipelineCreateInfo }, null, out pipelines);
Debug.Assert(err == Result.SUCCESS);
vsModule.DestroyShaderModule(mConfiguration.Device, null);
fsModule.DestroyShaderModule(mConfiguration.Device, null);
mPipeline = pipelines[0];
}
}
void setupDescriptorPool()
{
// Create the global descriptor pool
// All descriptors used in this example are allocated from this pool
var descriptorPoolInfo = new MgDescriptorPoolCreateInfo
{
// We need to tell the API the number of max. requested descriptors per type
PoolSizes = new MgDescriptorPoolSize[]
{
new MgDescriptorPoolSize
{
// This example only uses one descriptor type (uniform buffer) and only requests one descriptor of this type
Type = MgDescriptorType.UNIFORM_BUFFER,
DescriptorCount = 1,
},
// For additional types you need to add new entries in the type count list
// E.g. for two combined image samplers :
// typeCounts[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
// typeCounts[1].descriptorCount = 2;
},
// Set the max. number of descriptor sets that can be requested from this pool (requesting beyond this limit will result in an error)
MaxSets = 1,
};
var err = mConfiguration.Device.CreateDescriptorPool(descriptorPoolInfo, null, out mDescriptorPool);
Debug.Assert(err == Result.SUCCESS);
}
void setupDescriptorSet()
{
// Allocate a new descriptor set from the global descriptor pool
var allocInfo = new MgDescriptorSetAllocateInfo
{
DescriptorPool = mDescriptorPool,
DescriptorSetCount = 1,
SetLayouts = new[] { mDescriptorSetLayout },
};
IMgDescriptorSet[] dSets;
var err = mConfiguration.Device.AllocateDescriptorSets(allocInfo, out dSets);
mDescriptorSet = dSets[0];
Debug.Assert(err == Result.SUCCESS);
// Update the descriptor set determining the shader binding points
// For every binding point used in a shader there needs to be one
// descriptor set matching that binding point
mConfiguration.Device.UpdateDescriptorSets(
new []
{
// Binding 0 : Uniform buffer
new MgWriteDescriptorSet
{
DstSet = mDescriptorSet,
DescriptorCount = 1,
DescriptorType = MgDescriptorType.UNIFORM_BUFFER,
BufferInfo = new MgDescriptorBufferInfo[]
{
uniformDataVS.descriptor,
},
// Binds this uniform buffer to binding point 0
DstBinding = 0,
},
}, null);
}
IMgCommandBuffer[] drawCmdBuffers;
void createCommandBuffers()
{
// Create one command buffer per frame buffer
// in the swap chain
// Command buffers store a reference to the
// frame buffer inside their render pass info
// so for static usage withouth having to rebuild
// them each frame, we use one per frame buffer
drawCmdBuffers = new IMgCommandBuffer[mGraphicsDevice.Framebuffers.Length];
{
var cmdBufAllocateInfo = new MgCommandBufferAllocateInfo
{
CommandBufferCount = (uint)mGraphicsDevice.Framebuffers.Length,
CommandPool = mConfiguration.Partition.CommandPool,
Level = MgCommandBufferLevel.PRIMARY,
};
var err = mConfiguration.Device.AllocateCommandBuffers(cmdBufAllocateInfo, drawCmdBuffers);
Debug.Assert(err == Result.SUCCESS);
}
// Command buffers for submitting present barriers
{
var cmdBufAllocateInfo = new MgCommandBufferAllocateInfo
{
CommandBufferCount = 2,
CommandPool = mConfiguration.Partition.CommandPool,
Level = MgCommandBufferLevel.PRIMARY,
};
var presentBuffers = new IMgCommandBuffer[2];
var err = mConfiguration.Device.AllocateCommandBuffers(cmdBufAllocateInfo, presentBuffers);
Debug.Assert(err == Result.SUCCESS);
// Pre present
mPrePresentCmdBuffer = presentBuffers[0];
// Post present
mPostPresentCmdBuffer = presentBuffers[1];
}
}
// Build separate command buffers for every framebuffer image
// Unlike in OpenGL all rendering commands are recorded once into command buffers that are then resubmitted to the queue
// This allows to generate work upfront and from multiple threads, one of the biggest advantages of Vulkan
void buildCommandBuffers()
{
var renderPassBeginInfo = new MgRenderPassBeginInfo {
RenderPass = mGraphicsDevice.Renderpass,
RenderArea = new MgRect2D
{
Offset = new MgOffset2D { X = 0, Y = 0 },
Extent = new MgExtent2D { Width = mWidth, Height = mHeight },
},
// Set clear values for all framebuffer attachments with loadOp set to clear
// We use two attachments (color and depth) that are cleared at the start of the subpass and as such we need to set clear values for both
ClearValues = new MgClearValue[]
{
MgClearValue.FromColorAndFormat(mSwapchains.Format, new MgColor4f(0f, 0f, 0f, 0f)),
new MgClearValue { DepthStencil = new MgClearDepthStencilValue( 1.0f, 0) },
},
};
for (var i = 0; i < drawCmdBuffers.Length; ++i)
{
// Set target frame buffer
renderPassBeginInfo.Framebuffer = mGraphicsDevice.Framebuffers[i];
var cmdBuf = drawCmdBuffers[i];
var cmdBufInfo = new MgCommandBufferBeginInfo { };
var err = cmdBuf.BeginCommandBuffer(cmdBufInfo);
Debug.Assert(err == Result.SUCCESS);
// Start the first sub pass specified in our default render pass setup by the base class
// This will clear the color and depth attachment
cmdBuf.CmdBeginRenderPass(renderPassBeginInfo, MgSubpassContents.INLINE);
// Update dynamic viewport state
cmdBuf.CmdSetViewport(0,
new[] {
new MgViewport {
Height = (float) mHeight,
Width = (float) mWidth,
MinDepth = 0.0f,
MaxDepth = 1.0f,
}
}
);
// Update dynamic scissor state
cmdBuf.CmdSetScissor(0,
new[] {
new MgRect2D {
Extent = new MgExtent2D { Width = mWidth, Height = mHeight },
Offset = new MgOffset2D { X = 0, Y = 0 },
}
}
);
// Bind descriptor sets describing shader binding points
cmdBuf.CmdBindDescriptorSets( MgPipelineBindPoint.GRAPHICS, mPipelineLayout, 0, 1, new[] { mDescriptorSet }, null);
// Bind the rendering pipeline
// The pipeline (state object) contains all states of the rendering pipeline, binding it will set all the states specified at pipeline creation time
cmdBuf.CmdBindPipeline(MgPipelineBindPoint.GRAPHICS, mPipeline);
// Bind triangle vertex buffer (contains position and colors)
cmdBuf.CmdBindVertexBuffers(0, new[] { vertices.buffer }, new [] { 0UL });
// Bind triangle index buffer
cmdBuf.CmdBindIndexBuffer(indices.buffer, 0, MgIndexType.UINT32);
// Draw indexed triangle
cmdBuf.CmdDrawIndexed(indices.count, 1, 0, 0, 1);
cmdBuf.CmdEndRenderPass();
// Ending the render pass will add an implicit barrier transitioning the frame buffer color attachment to
// VK_IMAGE_LAYOUT_PRESENT_SRC_KHR for presenting it to the windowing system
err = cmdBuf.EndCommandBuffer();
Debug.Assert(err == Result.SUCCESS);
}
}
#endregion
/// <summary>
/// Convert degrees to radians
/// </summary>
/// <param name="degrees">An angle in degrees</param>
/// <returns>The angle expressed in radians</returns>
public static float DegreesToRadians(float degrees)
{
const double degToRad = System.Math.PI / 180.0;
return (float) (degrees * degToRad);
}
void updateUniformBuffers()
{
// Update matrices
uboVS.projectionMatrix = Matrix4.CreatePerspectiveFieldOfView(
DegreesToRadians(60.0f),
(mWidth / mHeight),
1.0f,
256.0f);
const float ZOOM = -2.5f;
uboVS.viewMatrix = Matrix4.CreateTranslation(0, 0, ZOOM);
// TODO : track down rotation
uboVS.modelMatrix = Matrix4.Identity;
//uboVS.modelMatrix = glm::rotate(uboVS.modelMatrix, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
//uboVS.modelMatrix = glm::rotate(uboVS.modelMatrix, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
//uboVS.modelMatrix = glm::rotate(uboVS.modelMatrix, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
var structSize = (ulong) Marshal.SizeOf(typeof(UniformBufferObject));
// Map uniform buffer and update it
IntPtr pData;
var err = uniformDataVS.memory.MapMemory(mConfiguration.Device, 0, structSize, 0, out pData);
Marshal.StructureToPtr(uboVS, pData, false);
// Unmap after data has been copied
// Note: Since we requested a host coherent memory type for the uniform buffer, the write is instantly visible to the GPU
uniformDataVS.memory.UnmapMemory(mConfiguration.Device);
}
public void RenderLoop()
{
render();
}
void render()
{
if (!mPrepared)
return;
draw();
}
void draw()
{
// Get next image in the swap chain (back/front buffer)
var currentBufferIndex = mPresentationLayer.BeginDraw(mPostPresentCmdBuffer, mPresentCompleteSemaphore);
// Use a fence to wait until the command buffer has finished execution before using it again
var fence = mWaitFences[(int) currentBufferIndex];
var err = mConfiguration.Device.WaitForFences(new[] { fence } , true, ulong.MaxValue);
Debug.Assert(err == Result.SUCCESS);
err = mConfiguration.Device.ResetFences(new[] { fence });
// Pipeline stage at which the queue submission will wait (via pWaitSemaphores)
var submitInfos = new MgSubmitInfo[]
{
// The submit info structure specifices a command buffer queue submission batch
new MgSubmitInfo
{
WaitSemaphores = new []
{
// One wait semaphore
new MgSubmitInfoWaitSemaphoreInfo
{
// Pointer to the list of pipeline stages that the semaphore waits will occur at
WaitDstStageMask = MgPipelineStageFlagBits.COLOR_ATTACHMENT_OUTPUT_BIT,
// Semaphore(s) to wait upon before the submitted command buffer starts executing
WaitSemaphore = mPresentCompleteSemaphore,
}
},
// One command buffer
CommandBuffers = new []
{
// Command buffers(s) to execute in this batch (submission)
drawCmdBuffers[currentBufferIndex]
},
// One signal semaphore
SignalSemaphores = new []
{
// Semaphore(s) to be signaled when command buffers have completed
mRenderCompleteSemaphore
},
}
};
// Submit to the graphics queue passing a wait fence
err = mConfiguration.Queue.QueueSubmit(submitInfos, fence);
Debug.Assert(err == Result.SUCCESS);
// Present the current buffer to the swap chain
// Pass the semaphore signaled by the command buffer submission from the submit info as the wait semaphore for swap chain presentation
// This ensures that the image is not presented to the windowing system until all commands have been submitted
mPresentationLayer.EndDraw(new[] { currentBufferIndex }, mPrePresentCmdBuffer, new[] { mRenderCompleteSemaphore });
}
void viewChanged()
{
// This function is called by the base example class each time the view is changed by user input
updateUniformBuffers();
}
#region IDisposable Support
private bool mIsDisposed = false; // To detect redundant calls
private ITriangleDemoShaderPath mTrianglePath;
protected virtual void Dispose(bool disposing)
{
if (mIsDisposed)
{
return;
}
ReleaseUnmanagedResources();
if (disposing)
{
ReleaseManagedResources();
}
mIsDisposed = true;
}
private void ReleaseManagedResources()
{
}
private void ReleaseUnmanagedResources()
{
var device = mConfiguration.Device;
if (device != null)
{
// Clean up used Vulkan resources
// Note: Inherited destructor cleans up resources stored in base class
if (mPipeline != null)
mPipeline.DestroyPipeline(device, null);
if (mPipelineLayout != null)
mPipelineLayout.DestroyPipelineLayout(device, null);
if (mDescriptorSetLayout != null)
mDescriptorSetLayout.DestroyDescriptorSetLayout(device, null);
if (vertices.buffer != null)
vertices.buffer.DestroyBuffer(device, null);
if (vertices.memory != null)
vertices.memory.FreeMemory(device, null);
if (indices.buffer != null)
indices.buffer.DestroyBuffer(device, null);
if (indices.memory != null)
indices.memory.FreeMemory(device, null);
if (uniformDataVS.buffer != null)
uniformDataVS.buffer.DestroyBuffer(device, null);
if (uniformDataVS.memory != null)
uniformDataVS.memory.FreeMemory(device, null);
if (mPresentCompleteSemaphore != null)
mPresentCompleteSemaphore.DestroySemaphore(device, null);
if (mRenderCompleteSemaphore != null)
mRenderCompleteSemaphore.DestroySemaphore(device, null);
foreach (var fence in mWaitFences)
{
fence.DestroyFence(device, null);
}
if (mDescriptorPool != null)
mDescriptorPool.DestroyDescriptorPool(device, null);
if (drawCmdBuffers != null)
mConfiguration.Device.FreeCommandBuffers(mConfiguration.Partition.CommandPool, drawCmdBuffers);
if (mPostPresentCmdBuffer != null)
mConfiguration.Device.FreeCommandBuffers(mConfiguration.Partition.CommandPool, new[] { mPostPresentCmdBuffer });
if (mPrePresentCmdBuffer != null)
mConfiguration.Device.FreeCommandBuffers(mConfiguration.Partition.CommandPool, new[] { mPrePresentCmdBuffer });
if (mGraphicsDevice != null)
mGraphicsDevice.Dispose();
}
}
~VulkanExample()
{
Dispose(false);
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="JoinCqlBlock.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Data.Common.CommandTrees;
using System.Data.Common.CommandTrees.ExpressionBuilder;
using System.Data.Common.Utils;
using System.Text;
using System.Collections.Generic;
using System.Data.Mapping.ViewGeneration.Structures;
using System.Diagnostics;
namespace System.Data.Mapping.ViewGeneration.CqlGeneration
{
/// <summary>
/// Represents to the various Join nodes in the view: IJ, LOJ, FOJ.
/// </summary>
internal sealed class JoinCqlBlock : CqlBlock
{
#region Constructor
/// <summary>
/// Creates a join block (type given by <paramref name="opType"/>) with SELECT (<paramref name="slotInfos"/>), FROM (<paramref name="children"/>),
/// ON (<paramref name="onClauses"/> - one for each child except 0th), WHERE (true), AS (<paramref name="blockAliasNum"/>).
/// </summary>
internal JoinCqlBlock(CellTreeOpType opType,
SlotInfo[] slotInfos,
List<CqlBlock> children,
List<OnClause> onClauses,
CqlIdentifiers identifiers,
int blockAliasNum)
: base(slotInfos, children, BoolExpression.True, identifiers, blockAliasNum)
{
m_opType = opType;
m_onClauses = onClauses;
}
#endregion
#region Fields
private readonly CellTreeOpType m_opType;
private readonly List<OnClause> m_onClauses;
#endregion
#region Methods
internal override StringBuilder AsEsql(StringBuilder builder, bool isTopLevel, int indentLevel)
{
// The SELECT part.
StringUtil.IndentNewLine(builder, indentLevel);
builder.Append("SELECT ");
GenerateProjectionEsql(
builder,
null, /* There is no single input, so the blockAlias is null. ProjectedSlot objects will have to carry their own input block info:
* see QualifiedSlot and QualifiedCellIdBoolean for more info. */
false,
indentLevel,
isTopLevel);
StringUtil.IndentNewLine(builder, indentLevel);
// The FROM part by joining all the children using ON Clauses.
builder.Append("FROM ");
int i = 0;
foreach (CqlBlock child in Children)
{
if (i > 0)
{
StringUtil.IndentNewLine(builder, indentLevel + 1);
builder.Append(OpCellTreeNode.OpToEsql(m_opType));
}
builder.Append(" (");
child.AsEsql(builder, false, indentLevel + 1);
builder.Append(") AS ")
.Append(child.CqlAlias);
// The ON part.
if (i > 0)
{
StringUtil.IndentNewLine(builder, indentLevel + 1);
builder.Append("ON ");
m_onClauses[i - 1].AsEsql(builder);
}
i++;
}
return builder;
}
internal override DbExpression AsCqt(bool isTopLevel)
{
// The FROM part:
// - build a tree of binary joins out of the inputs (this.Children).
// - update each child block with its relative position in the join tree,
// so that QualifiedSlot and QualifiedCellIdBoolean objects could find their
// designated block areas inside the cumulative join row passed into their AsCqt(row) method.
CqlBlock leftmostBlock = this.Children[0];
DbExpression left = leftmostBlock.AsCqt(false);
List<string> joinTreeCtxParentQualifiers = new List<string>();
for (int i = 1; i < this.Children.Count; ++i)
{
// Join the current left expression (a tree) to the current right block.
CqlBlock rightBlock = this.Children[i];
DbExpression right = rightBlock.AsCqt(false);
Func<DbExpression, DbExpression, DbExpression> joinConditionFunc = m_onClauses[i - 1].AsCqt;
DbJoinExpression join;
switch (m_opType)
{
case CellTreeOpType.FOJ:
join = left.FullOuterJoin(right, joinConditionFunc);
break;
case CellTreeOpType.IJ:
join = left.InnerJoin(right, joinConditionFunc);
break;
case CellTreeOpType.LOJ:
join = left.LeftOuterJoin(right, joinConditionFunc);
break;
default:
Debug.Fail("Unknown operator");
return null;
}
if (i == 1)
{
// Assign the joinTreeContext to the leftmost block.
leftmostBlock.SetJoinTreeContext(joinTreeCtxParentQualifiers, join.Left.VariableName);
}
else
{
// Update the joinTreeCtxParentQualifiers.
// Note that all blocks that already participate in the left expression tree share the same copy of the joinTreeContext.
joinTreeCtxParentQualifiers.Add(join.Left.VariableName);
}
// Assign the joinTreeContext to the right block.
rightBlock.SetJoinTreeContext(joinTreeCtxParentQualifiers, join.Right.VariableName);
left = join;
}
// The SELECT part.
return left.Select(row => GenerateProjectionCqt(row, false));
}
#endregion
/// <summary>
/// Represents a complete ON clause "slot1 == slot2 AND "slot3 == slot4" ... for two <see cref="JoinCqlBlock"/>s.
/// </summary>
internal sealed class OnClause : InternalBase
{
#region Constructor
internal OnClause()
{
m_singleClauses = new List<SingleClause>();
}
#endregion
#region Fields
private readonly List<SingleClause> m_singleClauses;
#endregion
#region Methods
/// <summary>
/// Adds an <see cref="SingleClause"/> element for a join of the form <paramref name="leftSlot"/> = <paramref name="rightSlot"/>.
/// </summary>
internal void Add(QualifiedSlot leftSlot, MemberPath leftSlotOutputMember, QualifiedSlot rightSlot, MemberPath rightSlotOutputMember)
{
SingleClause singleClause = new SingleClause(leftSlot, leftSlotOutputMember, rightSlot, rightSlotOutputMember);
m_singleClauses.Add(singleClause);
}
/// <summary>
/// Generates eSQL string of the form "LeftSlot1 = RightSlot1 AND LeftSlot2 = RightSlot2 AND ...
/// </summary>
internal StringBuilder AsEsql(StringBuilder builder)
{
bool isFirst = true;
foreach (SingleClause singleClause in m_singleClauses)
{
if (false == isFirst)
{
builder.Append(" AND ");
}
singleClause.AsEsql(builder);
isFirst = false;
}
return builder;
}
/// <summary>
/// Generates CQT of the form "LeftSlot1 = RightSlot1 AND LeftSlot2 = RightSlot2 AND ...
/// </summary>
internal DbExpression AsCqt(DbExpression leftRow, DbExpression rightRow)
{
DbExpression cqt = m_singleClauses[0].AsCqt(leftRow, rightRow);
for (int i = 1; i < m_singleClauses.Count; ++i)
{
cqt = cqt.And(m_singleClauses[i].AsCqt(leftRow, rightRow));
}
return cqt;
}
internal override void ToCompactString(StringBuilder builder)
{
builder.Append("ON ");
StringUtil.ToSeparatedString(builder, m_singleClauses, " AND ");
}
#endregion
#region SingleClause
/// <summary>
/// Represents an expression between slots of the form: LeftSlot = RightSlot
/// </summary>
private sealed class SingleClause : InternalBase
{
internal SingleClause(QualifiedSlot leftSlot, MemberPath leftSlotOutputMember, QualifiedSlot rightSlot, MemberPath rightSlotOutputMember)
{
m_leftSlot = leftSlot;
m_leftSlotOutputMember = leftSlotOutputMember;
m_rightSlot = rightSlot;
m_rightSlotOutputMember = rightSlotOutputMember;
}
#region Fields
private readonly QualifiedSlot m_leftSlot;
private readonly MemberPath m_leftSlotOutputMember;
private readonly QualifiedSlot m_rightSlot;
private readonly MemberPath m_rightSlotOutputMember;
#endregion
#region Methods
/// <summary>
/// Generates eSQL string of the form "leftSlot = rightSlot".
/// </summary>
internal StringBuilder AsEsql(StringBuilder builder)
{
builder.Append(m_leftSlot.GetQualifiedCqlName(m_leftSlotOutputMember))
.Append(" = ")
.Append(m_rightSlot.GetQualifiedCqlName(m_rightSlotOutputMember));
return builder;
}
/// <summary>
/// Generates CQT of the form "leftSlot = rightSlot".
/// </summary>
internal DbExpression AsCqt(DbExpression leftRow, DbExpression rightRow)
{
return m_leftSlot.AsCqt(leftRow, m_leftSlotOutputMember).Equal(m_rightSlot.AsCqt(rightRow, m_rightSlotOutputMember));
}
internal override void ToCompactString(StringBuilder builder)
{
m_leftSlot.ToCompactString(builder);
builder.Append(" = ");
m_rightSlot.ToCompactString(builder);
}
#endregion
}
#endregion
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors;
using OpenSim.Services.Connectors.SimianGrid;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGInventoryBroker")]
public class HGInventoryBroker : ISharedRegionModule, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static bool m_Enabled = false;
private static IInventoryService m_LocalGridInventoryService;
private Dictionary<string, IInventoryService> m_connectors = new Dictionary<string, IInventoryService>();
// A cache of userIDs --> ServiceURLs, for HGBroker only
protected Dictionary<UUID, string> m_InventoryURLs = new Dictionary<UUID,string>();
private List<Scene> m_Scenes = new List<Scene>();
private InventoryCache m_Cache = new InventoryCache();
protected IUserManagement m_UserManagement;
protected IUserManagement UserManagementModule
{
get
{
if (m_UserManagement == null)
{
m_UserManagement = m_Scenes[0].RequestModuleInterface<IUserManagement>();
if (m_UserManagement == null)
m_log.ErrorFormat(
"[HG INVENTORY CONNECTOR]: Could not retrieve IUserManagement module from {0}",
m_Scenes[0].RegionInfo.RegionName);
}
return m_UserManagement;
}
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "HGInventoryBroker"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
{
IConfig inventoryConfig = source.Configs["InventoryService"];
if (inventoryConfig == null)
{
m_log.Error("[HG INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini");
return;
}
string localDll = inventoryConfig.GetString("LocalGridInventoryService",
String.Empty);
//string HGDll = inventoryConfig.GetString("HypergridInventoryService",
// String.Empty);
if (localDll == String.Empty)
{
m_log.Error("[HG INVENTORY CONNECTOR]: No LocalGridInventoryService named in section InventoryService");
//return;
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
Object[] args = new Object[] { source };
m_LocalGridInventoryService =
ServerUtils.LoadPlugin<IInventoryService>(localDll,
args);
if (m_LocalGridInventoryService == null)
{
m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service");
return;
}
m_Enabled = true;
m_log.InfoFormat("[HG INVENTORY CONNECTOR]: HG inventory broker enabled with inner connector of type {0}", m_LocalGridInventoryService.GetType());
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IInventoryService>(this);
if (m_Scenes.Count == 1)
{
// FIXME: The local connector needs the scene to extract the UserManager. However, it's not enabled so
// we can't just add the region. But this approach is super-messy.
if (m_LocalGridInventoryService is RemoteXInventoryServicesConnector)
{
m_log.DebugFormat(
"[HG INVENTORY BROKER]: Manually setting scene in RemoteXInventoryServicesConnector to {0}",
scene.RegionInfo.RegionName);
((RemoteXInventoryServicesConnector)m_LocalGridInventoryService).Scene = scene;
}
else if (m_LocalGridInventoryService is LocalInventoryServicesConnector)
{
m_log.DebugFormat(
"[HG INVENTORY BROKER]: Manually setting scene in LocalInventoryServicesConnector to {0}",
scene.RegionInfo.RegionName);
((LocalInventoryServicesConnector)m_LocalGridInventoryService).Scene = scene;
}
scene.EventManager.OnClientClosed += OnClientClosed;
}
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Remove(scene);
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_log.InfoFormat("[HG INVENTORY CONNECTOR]: Enabled HG inventory for region {0}", scene.RegionInfo.RegionName);
}
#region URL Cache
void OnClientClosed(UUID clientID, Scene scene)
{
if (m_InventoryURLs.ContainsKey(clientID)) // if it's in cache
{
ScenePresence sp = null;
foreach (Scene s in m_Scenes)
{
s.TryGetScenePresence(clientID, out sp);
if ((sp != null) && !sp.IsChildAgent && (s != scene))
{
m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping inventoryURL in cache",
scene.RegionInfo.RegionName, clientID);
return;
}
}
DropInventoryServiceURL(clientID);
}
}
/// <summary>
/// Gets the user's inventory URL from its serviceURLs, if the user is foreign,
/// and sticks it in the cache
/// </summary>
/// <param name="userID"></param>
private void CacheInventoryServiceURL(UUID userID)
{
if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(userID))
{
// The user is not local; let's cache its service URL
string inventoryURL = string.Empty;
ScenePresence sp = null;
foreach (Scene scene in m_Scenes)
{
scene.TryGetScenePresence(userID, out sp);
if (sp != null)
{
AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
if (aCircuit == null)
return;
if (aCircuit.ServiceURLs == null)
return;
if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI"))
{
inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString();
if (inventoryURL != null && inventoryURL != string.Empty)
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
m_InventoryURLs.Add(userID, inventoryURL);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
return;
}
}
// else
// {
// m_log.DebugFormat("[HG INVENTORY CONNECTOR]: User {0} does not have InventoryServerURI. OH NOES!", userID);
// return;
// }
}
}
if (sp == null)
{
inventoryURL = UserManagementModule.GetUserServerURL(userID, "InventoryServerURI");
if (!string.IsNullOrEmpty(inventoryURL))
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
m_InventoryURLs.Add(userID, inventoryURL);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
}
}
}
}
private void DropInventoryServiceURL(UUID userID)
{
lock (m_InventoryURLs)
if (m_InventoryURLs.ContainsKey(userID))
{
string url = m_InventoryURLs[userID];
m_InventoryURLs.Remove(userID);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Removed {0} from the cache of inventory URLs", url);
}
}
public string GetInventoryServiceURL(UUID userID)
{
if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID];
CacheInventoryServiceURL(userID);
if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID];
return null; //it means that the methods should forward to local grid's inventory
}
#endregion
#region IInventoryService
public bool CreateUserInventory(UUID userID)
{
return m_LocalGridInventoryService.CreateUserInventory(userID);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userID)
{
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetInventorySkeleton(userID);
IInventoryService connector = GetConnector(invURL);
return connector.GetInventorySkeleton(userID);
}
public InventoryCollection GetUserInventory(UUID userID)
{
string invURL = GetInventoryServiceURL(userID);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetUserInventory for {0} {1}", userID, invURL);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetUserInventory(userID);
InventoryCollection c = m_Cache.GetUserInventory(userID);
if (c != null)
return c;
IInventoryService connector = GetConnector(invURL);
c = connector.GetUserInventory(userID);
m_Cache.Cache(userID, c);
return c;
}
public void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
{
}
public InventoryFolderBase GetRootFolder(UUID userID)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetRootFolder for {0}", userID);
InventoryFolderBase root = m_Cache.GetRootFolder(userID);
if (root != null)
return root;
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetRootFolder(userID);
IInventoryService connector = GetConnector(invURL);
root = connector.GetRootFolder(userID);
m_Cache.Cache(userID, root);
return root;
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetFolderForType {0} type {1}", userID, type);
InventoryFolderBase f = m_Cache.GetFolderForType(userID, type);
if (f != null)
return f;
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolderForType(userID, type);
IInventoryService connector = GetConnector(invURL);
f = connector.GetFolderForType(userID, type);
m_Cache.Cache(userID, type, f);
return f;
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent " + folderID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolderContent(userID, folderID);
InventoryCollection c = m_Cache.GetFolderContent(userID, folderID);
if (c != null)
{
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent found content in cache " + folderID);
return c;
}
IInventoryService connector = GetConnector(invURL);
return connector.GetFolderContent(userID, folderID);
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems " + folderID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolderItems(userID, folderID);
List<InventoryItemBase> items = m_Cache.GetFolderItems(userID, folderID);
if (items != null)
{
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems found items in cache " + folderID);
return items;
}
IInventoryService connector = GetConnector(invURL);
return connector.GetFolderItems(userID, folderID);
}
public bool AddFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: AddFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.AddFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.AddFolder(folder);
}
public bool UpdateFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.UpdateFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.UpdateFolder(folder);
}
public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
if (folderIDs == null)
return false;
if (folderIDs.Count == 0)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteFolders for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.DeleteFolders(ownerID, folderIDs);
IInventoryService connector = GetConnector(invURL);
return connector.DeleteFolders(ownerID, folderIDs);
}
public bool MoveFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: MoveFolder for " + folder.Owner);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.MoveFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.MoveFolder(folder);
}
public bool PurgeFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: PurgeFolder for " + folder.Owner);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.PurgeFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.PurgeFolder(folder);
}
public bool AddItem(InventoryItemBase item)
{
if (item == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: AddItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.AddItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.AddItem(item);
}
public bool UpdateItem(InventoryItemBase item)
{
if (item == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.UpdateItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.UpdateItem(item);
}
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
if (items == null)
return false;
if (items.Count == 0)
return true;
//m_log.Debug("[HG INVENTORY CONNECTOR]: MoveItems for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.MoveItems(ownerID, items);
IInventoryService connector = GetConnector(invURL);
return connector.MoveItems(ownerID, items);
}
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID);
if (itemIDs == null)
return false;
if (itemIDs.Count == 0)
return true;
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.DeleteItems(ownerID, itemIDs);
IInventoryService connector = GetConnector(invURL);
return connector.DeleteItems(ownerID, itemIDs);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
if (item == null)
return null;
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.GetItem(item);
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
if (folder == null)
return null;
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.GetFolder(folder);
}
public bool HasInventoryForUser(UUID userID)
{
return false;
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return new List<InventoryItemBase>();
}
public int GetAssetPermissions(UUID userID, UUID assetID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetAssetPermissions " + assetID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetAssetPermissions(userID, assetID);
IInventoryService connector = GetConnector(invURL);
return connector.GetAssetPermissions(userID, assetID);
}
#endregion
private IInventoryService GetConnector(string url)
{
IInventoryService connector = null;
lock (m_connectors)
{
if (m_connectors.ContainsKey(url))
{
connector = m_connectors[url];
}
else
{
// Still not as flexible as I would like this to be,
// but good enough for now
string connectorType = new HeloServicesConnector(url).Helo();
m_log.DebugFormat("[HG INVENTORY SERVICE]: HELO returned {0}", connectorType);
if (connectorType == "opensim-simian")
{
connector = new SimianInventoryServiceConnector(url);
}
else
{
RemoteXInventoryServicesConnector rxisc = new RemoteXInventoryServicesConnector(url);
rxisc.Scene = m_Scenes[0];
connector = rxisc;
}
m_connectors.Add(url, connector);
}
}
return connector;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Linq;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using JetBrains.Annotations;
namespace LinqToDB.Extensions
{
public static class ReflectionExtensions
{
#region Type extensions
public static bool IsGenericTypeEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsGenericType;
#else
return type.IsGenericType;
#endif
}
public static bool IsValueTypeEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsValueType;
#else
return type.IsValueType;
#endif
}
public static bool IsAbstractEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsAbstract;
#else
return type.IsAbstract;
#endif
}
public static bool IsPublicEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsPublic;
#else
return type.IsPublic;
#endif
}
public static bool IsClassEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsClass;
#else
return type.IsClass;
#endif
}
public static bool IsEnumEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsEnum;
#else
return type.IsEnum;
#endif
}
public static bool IsPrimitiveEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsPrimitive;
#else
return type.IsPrimitive;
#endif
}
public static bool IsInterfaceEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsInterface;
#else
return type.IsInterface;
#endif
}
public static Type BaseTypeEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().BaseType;
#else
return type.BaseType;
#endif
}
public static Type[] GetInterfacesEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().ImplementedInterfaces.ToArray();
#else
return type.GetInterfaces();
#endif
}
public static object[] GetCustomAttributesEx(this Type type, Type attributeType, bool inherit)
{
#if NETFX_CORE
return type.GetTypeInfo().GetCustomAttributes(attributeType, inherit).Cast<object>().ToArray();
#else
return type.GetCustomAttributes(attributeType, inherit);
#endif
}
public static MemberInfo[] GetPublicInstanceMembersEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().DeclaredMembers.Where(m =>
{
var fieldInfo = m as FieldInfo;
if (fieldInfo != null)
return fieldInfo.IsPublic && !fieldInfo.IsStatic;
var propertyInfo = m as PropertyInfo;
if (propertyInfo != null)
return propertyInfo.CanRead && propertyInfo.GetMethod.IsPublic && !propertyInfo.GetMethod.IsStatic;
return false;
}).ToArray();
#else
return type.GetMembers(BindingFlags.Instance | BindingFlags.Public);
#endif
}
public static MethodInfo GetMethodEx(this Type type, string name, params Type[] types)
{
#if NETFX_CORE
return type.GetRuntimeMethod(name, types);
#else
return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, types, null);
#endif
}
public static ConstructorInfo GetDefaultConstructorEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().DeclaredConstructors.FirstOrDefault(p => p.GetParameters().Length == 0);
#else
return type.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
null,
Type.EmptyTypes,
null);
#endif
}
public static TypeCode GetTypeCodeEx(this Type type)
{
#if NETFX_CORE
if (type == null)
return TypeCode.Empty;
if (type.IsPrimitiveEx())
{
if (type == typeof(bool)) return TypeCode.Boolean;
if (type == typeof(char)) return TypeCode.Char;
if (type == typeof(sbyte)) return TypeCode.SByte;
if (type == typeof(byte)) return TypeCode.Byte;
if (type == typeof(short)) return TypeCode.Int16;
if (type == typeof(ushort)) return TypeCode.UInt16;
if (type == typeof(int)) return TypeCode.Int32;
if (type == typeof(uint)) return TypeCode.UInt32;
if (type == typeof(long)) return TypeCode.Int64;
if (type == typeof(ulong)) return TypeCode.UInt64;
if (type == typeof(float)) return TypeCode.Single;
if (type == typeof(double)) return TypeCode.Double;
if (type == typeof(decimal)) return TypeCode.Decimal;
}
if (type == typeof(DBNull)) return TypeCode.DBNull;
if (type == typeof(DateTime)) return TypeCode.DateTime;
if (type == typeof(String)) return TypeCode.String;
var underlyingSystemType = type.ToUnderlying();
if (type != underlyingSystemType && underlyingSystemType != null)
return underlyingSystemType.GetTypeCodeEx();
return TypeCode.Object;
#else
return Type.GetTypeCode(type);
#endif
}
public static bool IsAssignableFromEx(this Type type, Type c)
{
#if NETFX_CORE
return type.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo());
#else
return type.IsAssignableFrom(c);
#endif
}
public static FieldInfo[] GetFieldsEx(this Type type)
{
#if NETFX_CORE
return type.GetRuntimeFields().ToArray();
#else
return type.GetFields();
#endif
}
public static Type[] GetGenericArgumentsEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().GenericTypeArguments;
#else
return type.GetGenericArguments();
#endif
}
public static MethodInfo GetGetMethodEx(this PropertyInfo propertyInfo, bool nonPublic)
{
#if NETFX_CORE
return propertyInfo.GetMethod;
#else
return propertyInfo.GetGetMethod(nonPublic);
#endif
}
public static MethodInfo GetGetMethodEx(this PropertyInfo propertyInfo)
{
#if NETFX_CORE
return propertyInfo.GetMethod;
#else
return propertyInfo.GetGetMethod();
#endif
}
public static MethodInfo GetSetMethodEx(this PropertyInfo propertyInfo, bool nonPublic)
{
#if NETFX_CORE
return propertyInfo.SetMethod;
#else
return propertyInfo.GetSetMethod(nonPublic);
#endif
}
public static MethodInfo GetSetMethodEx(this PropertyInfo propertyInfo)
{
#if NETFX_CORE
return propertyInfo.SetMethod;
#else
return propertyInfo.GetSetMethod();
#endif
}
public static object[] GetCustomAttributesEx(this Type type, bool inherit)
{
#if NETFX_CORE
return type.GetTypeInfo().GetCustomAttributes(inherit).Cast<object>().ToArray();
#else
return type.GetCustomAttributes(inherit);
#endif
}
public static InterfaceMapping GetInterfaceMapEx(this Type type, Type interfaceType)
{
#if NETFX_CORE
return type.GetTypeInfo().GetRuntimeInterfaceMap(interfaceType);
#else
return type.GetInterfaceMap(interfaceType);
#endif
}
public static bool IsPropertyEx(this MemberInfo memberInfo)
{
#if NETFX_CORE
return memberInfo is PropertyInfo;
#else
return memberInfo.MemberType == MemberTypes.Property;
#endif
}
public static bool IsFieldEx(this MemberInfo memberInfo)
{
#if NETFX_CORE
return memberInfo is FieldInfo;
#else
return memberInfo.MemberType == MemberTypes.Field;
#endif
}
public static bool IsMethodEx(this MemberInfo memberInfo)
{
#if NETFX_CORE
return memberInfo is MethodInfo;
#else
return memberInfo.MemberType == MemberTypes.Method;
#endif
}
public static object[] GetCustomAttributesEx(this MemberInfo memberInfo, Type attributeType, bool inherit)
{
#if NETFX_CORE
return memberInfo.GetCustomAttributes(attributeType, inherit).Cast<object>().ToArray();
#else
return memberInfo.GetCustomAttributes(attributeType, inherit);
#endif
}
public static bool IsSubclassOfEx(this Type type, Type c)
{
#if NETFX_CORE
return type.GetTypeInfo().IsSubclassOf(c);
#else
return type.IsSubclassOf(c);
#endif
}
public static bool IsGenericTypeDefinitionEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().IsGenericTypeDefinition;
#else
return type.IsGenericTypeDefinition;
#endif
}
public static PropertyInfo[] GetPropertiesEx(this Type type)
{
#if NETFX_CORE
return type.GetRuntimeProperties().Where(p => p.GetMethod != null).ToArray();
#else
return type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
#endif
}
public static PropertyInfo[] GetNonPublicPropertiesEx(this Type type)
{
#if NETFX_CORE
return type.GetRuntimeProperties().Where(p => p.GetMethod != null && !p.GetMethod.IsPublic && !p.GetMethod.IsStatic).ToArray();
#else
return type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
#endif
}
public static MethodInfo[] GetMethodsEx(this Type type)
{
#if NETFX_CORE
return type.GetRuntimeMethods().ToArray();
#else
return type.GetMethods();
#endif
}
public static Assembly AssemblyEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().Assembly;
#else
return type.Assembly;
#endif
}
public static ConstructorInfo[] GetConstructorsEx(this Type type)
{
#if NETFX_CORE
return type.GetTypeInfo().DeclaredConstructors.Where(c => c.IsPublic).ToArray();
#else
return type.GetConstructors();
#endif
}
public static ConstructorInfo GetConstructorEx(this Type type, Type[] parameterTypes)
{
#if NETFX_CORE
return
(
from ctor in type.GetTypeInfo().DeclaredConstructors
let ps = ctor.GetParameters()
where
ps.Length == parameterTypes.Length &&
parameterTypes.Zip(ps, (t,p) => p.ParameterType == t).All(v => v)
select ctor
)
.FirstOrDefault();
#else
return type.GetConstructor(parameterTypes);
#endif
}
public static PropertyInfo GetPropertyEx(this Type type, string propertyName)
{
#if NETFX_CORE
return type.GetTypeInfo().DeclaredProperties.FirstOrDefault(property => property.Name == propertyName);
#else
return type.GetProperty(propertyName);
#endif
}
public static FieldInfo GetFieldEx(this Type type, string propertyName)
{
#if NETFX_CORE
return type.GetTypeInfo().DeclaredFields.FirstOrDefault(field => field.Name == propertyName);
#else
return type.GetField(propertyName);
#endif
}
public static Type ReflectedTypeEx(this MemberInfo memberInfo)
{
#if NETFX_CORE
return memberInfo.DeclaringType;
#else
return memberInfo.ReflectedType;
#endif
}
public static MemberInfo[] GetInstanceMemberEx(this Type type, string name)
{
#if NETFX_CORE
return type.GetTypeInfo().DeclaredMembers.Where(m => m.Name == name).ToArray();
#else
return type.GetMember(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
#endif
}
public static MemberInfo[] GetPublicMemberEx(this Type type, string name)
{
#if NETFX_CORE
return type.GetTypeInfo().DeclaredMembers.Where(m => m.Name == name).ToArray();
#else
return type.GetMember(name);
#endif
}
public static object[] GetCustomAttributesEx(this MemberInfo memberInfo, bool inherit)
{
#if NETFX_CORE
return memberInfo.GetCustomAttributes(inherit).Cast<object>().ToArray();
#else
return memberInfo.GetCustomAttributes(inherit);
#endif
}
public static object[] GetCustomAttributesEx(this ParameterInfo parameterInfo, bool inherit)
{
#if NETFX_CORE
return parameterInfo.GetCustomAttributes(inherit).Cast<object>().ToArray();
#else
return parameterInfo.GetCustomAttributes(inherit);
#endif
}
static class CacheHelper<T>
{
public static readonly ConcurrentDictionary<Type,T[]> TypeAttributes = new ConcurrentDictionary<Type,T[]>();
}
#region Attributes cache
static readonly Dictionary<Type, object[]> _typeAttributesTopInternal = new Dictionary<Type, object[]>(10);
static void GetAttributesInternal(List<object> list, Type type)
{
object[] attrs;
if (_typeAttributesTopInternal.TryGetValue(type, out attrs))
{
list.AddRange(attrs);
}
else
{
GetAttributesTreeInternal(list, type);
_typeAttributesTopInternal.Add(type, list.ToArray());
}
}
static readonly ConcurrentDictionary<Type, object[]> _typeAttributesInternal = new ConcurrentDictionary<Type, object[]>();
static void GetAttributesTreeInternal(List<object> list, Type type)
{
var attrs = _typeAttributesInternal.GetOrAdd(type, x => type.GetCustomAttributesEx(false));
list.AddRange(attrs);
if (type.IsInterfaceEx())
return;
// Reflection returns interfaces for the whole inheritance chain.
// So, we are going to get some hemorrhoid here to restore the inheritance sequence.
//
var interfaces = type.GetInterfacesEx();
var nBaseInterfaces = type.BaseTypeEx() != null? type.BaseTypeEx().GetInterfacesEx().Length: 0;
for (var i = 0; i < interfaces.Length; i++)
{
var intf = interfaces[i];
if (i < nBaseInterfaces)
{
var getAttr = false;
foreach (var mi in type.GetInterfaceMapEx(intf).TargetMethods)
{
// Check if the interface is reimplemented.
//
if (mi.DeclaringType == type)
{
getAttr = true;
break;
}
}
if (getAttr == false)
continue;
}
GetAttributesTreeInternal(list, intf);
}
if (type.BaseTypeEx() != null && type.BaseTypeEx() != typeof(object))
GetAttributesTreeInternal(list, type.BaseTypeEx());
}
#endregion
/// <summary>
/// Returns an array of custom attributes applied to a type.
/// </summary>
/// <param name="type">A type instance.</param>
/// <typeparam name="T">The type of attribute to search for.
/// Only attributes that are assignable to this type are returned.</typeparam>
/// <returns>An array of custom attributes applied to this type,
/// or an array with zero (0) elements if no attributes have been applied.</returns>
public static T[] GetAttributes<T>([NotNull] this Type type)
where T : Attribute
{
if (type == null) throw new ArgumentNullException("type");
T[] attrs;
if (!CacheHelper<T>.TypeAttributes.TryGetValue(type, out attrs))
{
var list = new List<object>();
GetAttributesInternal(list, type);
CacheHelper<T>.TypeAttributes[type] = attrs = list.OfType<T>().ToArray();
}
return attrs;
}
/// <summary>
/// Retrieves a custom attribute applied to a type.
/// </summary>
/// <param name="type">A type instance.</param>
/// <typeparam name="T">The type of attribute to search for.
/// Only attributes that are assignable to this type are returned.</typeparam>
/// <returns>A reference to the first custom attribute of type attributeType
/// that is applied to element, or null if there is no such attribute.</returns>
public static T GetFirstAttribute<T>([NotNull] this Type type)
where T : Attribute
{
var attrs = GetAttributes<T>(type);
return attrs.Length > 0 ? attrs[0] : null;
}
/// <summary>
/// Gets a value indicating whether a type (or type's element type)
/// instance can be null in the underlying data store.
/// </summary>
/// <param name="type">A <see cref="System.Type"/> instance. </param>
/// <returns> True, if the type parameter is a closed generic nullable type; otherwise, False.</returns>
/// <remarks>Arrays of Nullable types are treated as Nullable types.</remarks>
public static bool IsNullable([NotNull] this Type type)
{
return type.IsGenericTypeEx() && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
/// <summary>
/// Returns the underlying type argument of the specified type.
/// </summary>
/// <param name="type">A <see cref="System.Type"/> instance. </param>
/// <returns><list>
/// <item>The type argument of the type parameter,
/// if the type parameter is a closed generic nullable type.</item>
/// <item>The underlying Type if the type parameter is an enum type.</item>
/// <item>Otherwise, the type itself.</item>
/// </list>
/// </returns>
public static Type ToUnderlying([NotNull] this Type type)
{
if (type == null) throw new ArgumentNullException("type");
if (type.IsNullable()) type = type.GetGenericArgumentsEx()[0];
if (type.IsEnumEx ()) type = Enum.GetUnderlyingType(type);
return type;
}
public static Type ToNullableUnderlying([NotNull] this Type type)
{
if (type == null) throw new ArgumentNullException("type");
return type.IsNullable() ? type.GetGenericArgumentsEx()[0] : type;
}
public static IEnumerable<Type> GetDefiningTypes(this Type child, MemberInfo member)
{
if (member.IsPropertyEx())
{
var prop = (PropertyInfo)member;
member = prop.GetGetMethodEx();
}
foreach (var inf in child.GetInterfacesEx())
{
var pm = child.GetInterfaceMapEx(inf);
for (var i = 0; i < pm.TargetMethods.Length; i++)
{
var method = pm.TargetMethods[i];
if (method == member || (method.DeclaringType == member.DeclaringType && method.Name == member.Name))
yield return inf;
}
}
yield return member.DeclaringType;
}
/// <summary>
/// Determines whether the specified types are considered equal.
/// </summary>
/// <param name="parent">A <see cref="System.Type"/> instance. </param>
/// <param name="child">A type possible derived from the <c>parent</c> type</param>
/// <returns>True, when an object instance of the type <c>child</c>
/// can be used as an object of the type <c>parent</c>; otherwise, false.</returns>
/// <remarks>Note that nullable types does not have a parent-child relation to it's underlying type.
/// For example, the 'int?' type (nullable int) and the 'int' type
/// aren't a parent and it's child.</remarks>
public static bool IsSameOrParentOf([NotNull] this Type parent, [NotNull] Type child)
{
if (parent == null) throw new ArgumentNullException("parent");
if (child == null) throw new ArgumentNullException("child");
if (parent == child ||
child.IsEnumEx() && Enum.GetUnderlyingType(child) == parent ||
child.IsSubclassOfEx(parent))
{
return true;
}
if (parent.IsGenericTypeDefinitionEx())
for (var t = child; t != typeof(object) && t != null; t = t.BaseTypeEx())
if (t.IsGenericTypeEx() && t.GetGenericTypeDefinition() == parent)
return true;
if (parent.IsInterfaceEx())
{
var interfaces = child.GetInterfacesEx();
foreach (var t in interfaces)
{
if (parent.IsGenericTypeDefinitionEx())
{
if (t.IsGenericTypeEx() && t.GetGenericTypeDefinition() == parent)
return true;
}
else if (t == parent)
return true;
}
}
return false;
}
public static Type GetGenericType([NotNull] this Type genericType, Type type)
{
if (genericType == null) throw new ArgumentNullException("genericType");
while (type != null && type != typeof(object))
{
if (type.IsGenericTypeEx() && type.GetGenericTypeDefinition() == genericType)
return type;
if (genericType.IsInterfaceEx())
{
foreach (var interfaceType in type.GetInterfacesEx())
{
var gType = GetGenericType(genericType, interfaceType);
if (gType != null)
return gType;
}
}
type = type.BaseTypeEx();
}
return null;
}
///<summary>
/// Gets the Type of a list item.
///</summary>
/// <param name="list">A <see cref="System.Object"/> instance. </param>
///<returns>The Type instance that represents the exact runtime type of a list item.</returns>
public static Type GetListItemType(this IEnumerable list)
{
var typeOfObject = typeof(object);
if (list == null)
return typeOfObject;
if (list is Array)
return list.GetType().GetElementType();
var type = list.GetType();
if (list is IList
#if !SILVERLIGHT && !NETFX_CORE
|| list is ITypedList || list is IListSource
#endif
)
{
PropertyInfo last = null;
foreach (var pi in type.GetPropertiesEx())
{
if (pi.GetIndexParameters().Length > 0 && pi.PropertyType != typeOfObject)
{
if (pi.Name == "Item")
return pi.PropertyType;
last = pi;
}
}
if (last != null)
return last.PropertyType;
}
if (list is IList)
{
foreach (var o in (IList)list)
if (o != null && o.GetType() != typeOfObject)
return o.GetType();
}
else
{
foreach (var o in list)
if (o != null && o.GetType() != typeOfObject)
return o.GetType();
}
return typeOfObject;
}
///<summary>
/// Gets the Type of a list item.
///</summary>
/// <param name="listType">A <see cref="System.Type"/> instance. </param>
///<returns>The Type instance that represents the exact runtime type of a list item.</returns>
public static Type GetListItemType(this Type listType)
{
if (listType.IsGenericTypeEx())
{
var elementTypes = listType.GetGenericArguments(typeof(IList<>));
if (elementTypes != null)
return elementTypes[0];
}
if (typeof(IList).IsSameOrParentOf(listType)
#if !SILVERLIGHT && !NETFX_CORE
|| typeof(ITypedList). IsSameOrParentOf(listType)
|| typeof(IListSource).IsSameOrParentOf(listType)
#endif
)
{
var elementType = listType.GetElementType();
if (elementType != null)
return elementType;
PropertyInfo last = null;
foreach (var pi in listType.GetPropertiesEx())
{
if (pi.GetIndexParameters().Length > 0 && pi.PropertyType != typeof(object))
{
if (pi.Name == "Item")
return pi.PropertyType;
last = pi;
}
}
if (last != null)
return last.PropertyType;
}
return typeof(object);
}
public static Type GetItemType(this Type type)
{
if (type == null)
return null;
if (type == typeof(object))
return type.HasElementType ? type.GetElementType(): null;
if (type.IsArray)
return type.GetElementType();
if (type.IsGenericTypeEx())
foreach (var aType in type.GetGenericArgumentsEx())
if (typeof(IEnumerable<>).MakeGenericType(new[] { aType }).IsAssignableFromEx(type))
return aType;
var interfaces = type.GetInterfacesEx();
if (interfaces != null && interfaces.Length > 0)
{
foreach (var iType in interfaces)
{
var eType = iType.GetItemType();
if (eType != null)
return eType;
}
}
return type.BaseTypeEx().GetItemType();
}
/// <summary>
/// Gets a value indicating whether a type can be used as a db primitive.
/// </summary>
/// <param name="type">A <see cref="System.Type"/> instance. </param>
/// <returns> True, if the type parameter is a primitive type; otherwise, False.</returns>
/// <remarks><see cref="System.String"/>. <see cref="Stream"/>.
/// <see cref="XmlReader"/>. <see cref="XmlDocument"/>. are specially handled by the library
/// and, therefore, can be treated as scalar types.</remarks>
public static bool IsScalar(this Type type)
{
while (type.IsArray)
type = type.GetElementType();
return type.IsValueTypeEx()
|| type == typeof(string)
|| type == typeof(Binary)
|| type == typeof(Stream)
|| type == typeof(XmlReader)
#if !SILVERLIGHT && !NETFX_CORE
|| type == typeof(XmlDocument)
#endif
;
}
///<summary>
/// Returns an array of Type objects that represent the type arguments
/// of a generic type or the type parameters of a generic type definition.
///</summary>
/// <param name="type">A <see cref="System.Type"/> instance.</param>
///<param name="baseType">Non generic base type.</param>
///<returns>An array of Type objects that represent the type arguments
/// of a generic type. Returns an empty array if the current type is not a generic type.</returns>
public static Type[] GetGenericArguments(this Type type, Type baseType)
{
var baseTypeName = baseType.Name;
for (var t = type; t != typeof(object) && t != null; t = t.BaseTypeEx())
{
if (t.IsGenericTypeEx())
{
if (baseType.IsGenericTypeDefinitionEx())
{
if (t.GetGenericTypeDefinition() == baseType)
return t.GetGenericArgumentsEx();
}
else if (baseTypeName == null || t.Name.Split('`')[0] == baseTypeName)
{
return t.GetGenericArgumentsEx();
}
}
}
foreach (var t in type.GetInterfacesEx())
{
if (t.IsGenericTypeEx())
{
if (baseType.IsGenericTypeDefinitionEx())
{
if (t.GetGenericTypeDefinition() == baseType)
return t.GetGenericArgumentsEx();
}
else if (baseTypeName == null || t.Name.Split('`')[0] == baseTypeName)
{
return t.GetGenericArgumentsEx();
}
}
}
return null;
}
public static bool IsFloatType(this Type type)
{
if (type.IsNullable())
type = type.GetGenericArgumentsEx()[0];
switch (type.GetTypeCodeEx())
{
case TypeCode.Single :
case TypeCode.Double :
case TypeCode.Decimal : return true;
}
return false;
}
public static bool IsIntegerType(this Type type)
{
if (type.IsNullable())
type = type.GetGenericArgumentsEx()[0];
switch (type.GetTypeCodeEx())
{
case TypeCode.SByte :
case TypeCode.Byte :
case TypeCode.Int16 :
case TypeCode.UInt16 :
case TypeCode.Int32 :
case TypeCode.UInt32 :
case TypeCode.Int64 :
case TypeCode.UInt64 : return true;
}
return false;
}
interface IGetDefaultValueHelper
{
object GetDefaultValue();
}
class GetDefaultValueHelper<T> : IGetDefaultValueHelper
{
public object GetDefaultValue()
{
return default(T);
}
}
public static object GetDefaultValue(this Type type)
{
var dtype = typeof(GetDefaultValueHelper<>).MakeGenericType(type);
var helper = (IGetDefaultValueHelper)Activator.CreateInstance(dtype);
return helper.GetDefaultValue();
}
#endregion
#region MethodInfo extensions
public static PropertyInfo GetPropertyInfo(this MethodInfo method)
{
if (method != null)
{
var type = method.DeclaringType;
foreach (var info in type.GetPropertiesEx())
{
if (info.CanRead && method == info.GetGetMethodEx(true))
return info;
if (info.CanWrite && method == info.GetSetMethodEx(true))
return info;
}
}
return null;
}
#endregion
#region MemberInfo extensions
public static Type GetMemberType(this MemberInfo memberInfo)
{
#if NETFX_CORE
if (memberInfo is PropertyInfo) return ((PropertyInfo)memberInfo).PropertyType;
if (memberInfo is FieldInfo) return ((FieldInfo) memberInfo).FieldType;
if (memberInfo is MethodInfo) return ((MethodInfo) memberInfo).ReturnType;
if (memberInfo is ConstructorInfo) return memberInfo. DeclaringType;
#else
switch (memberInfo.MemberType)
{
case MemberTypes.Property : return ((PropertyInfo)memberInfo).PropertyType;
case MemberTypes.Field : return ((FieldInfo) memberInfo).FieldType;
case MemberTypes.Method : return ((MethodInfo) memberInfo).ReturnType;
case MemberTypes.Constructor : return memberInfo. DeclaringType;
}
#endif
throw new InvalidOperationException();
}
public static bool IsNullableValueMember(this MemberInfo member)
{
return
member.Name == "Value" &&
member.DeclaringType.IsGenericTypeEx() &&
member.DeclaringType.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static bool IsNullableHasValueMember(this MemberInfo member)
{
return
member.Name == "HasValue" &&
member.DeclaringType.IsGenericTypeEx() &&
member.DeclaringType.GetGenericTypeDefinition() == typeof(Nullable<>);
}
static Dictionary<Type,HashSet<Type>> _castDic = new Dictionary<Type,HashSet<Type>>
{
{ typeof(decimal), new HashSet<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char) } },
{ typeof(double), new HashSet<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
{ typeof(float), new HashSet<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
{ typeof(ulong), new HashSet<Type> { typeof(byte), typeof(ushort), typeof(uint), typeof(char) } },
{ typeof(long), new HashSet<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(char) } },
{ typeof(uint), new HashSet<Type> { typeof(byte), typeof(ushort), typeof(char) } },
{ typeof(int), new HashSet<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(char) } },
{ typeof(ushort), new HashSet<Type> { typeof(byte), typeof(char) } },
{ typeof(short), new HashSet<Type> { typeof(byte) } }
};
public static bool CanConvertTo(this Type fromType, Type toType)
{
if (fromType == toType)
return true;
if (_castDic.ContainsKey(toType) && _castDic[toType].Contains(fromType))
return true;
#if !SILVERLIGHT && !NETFX_CORE
var tc = TypeDescriptor.GetConverter(fromType);
if (toType.IsAssignableFrom(fromType))
return true;
if (tc.CanConvertTo(toType))
return true;
tc = TypeDescriptor.GetConverter(toType);
if (tc.CanConvertFrom(fromType))
return true;
#endif
if (fromType.GetMethodsEx()
.Any(m => m.IsStatic && m.IsPublic && m.ReturnType == toType && (m.Name == "op_Implicit" || m.Name == "op_Explicit")))
return true;
return false;
}
public static bool EqualsTo(this MemberInfo member1, MemberInfo member2, Type declaringType = null )
{
if (ReferenceEquals(member1, member2))
return true;
if (member1 == null || member2 == null)
return false;
if (member1.Name == member2.Name)
{
if (member1.DeclaringType == member2.DeclaringType)
return true;
if (member1 is PropertyInfo)
{
var isSubclass =
member1.DeclaringType.IsSameOrParentOf(member2.DeclaringType) ||
member2.DeclaringType.IsSameOrParentOf(member1.DeclaringType);
if (isSubclass)
return true;
if (declaringType != null && member2.DeclaringType.IsInterfaceEx())
{
var getter1 = ((PropertyInfo)member1).GetGetMethodEx();
var getter2 = ((PropertyInfo)member2).GetGetMethodEx();
var map = declaringType.GetInterfaceMapEx(member2.DeclaringType);
for (var i = 0; i < map.InterfaceMethods.Length; i++)
if (getter2.Name == map.InterfaceMethods[i].Name && getter2.DeclaringType == map.InterfaceMethods[i].DeclaringType &&
getter1.Name == map.TargetMethods [i].Name && getter1.DeclaringType == map.TargetMethods [i].DeclaringType)
return true;
}
}
}
if (member2.DeclaringType.IsInterfaceEx() && !member1.DeclaringType.IsInterfaceEx() && member1.Name.EndsWith(member2.Name))
{
if (member1 is PropertyInfo)
{
var isSubclass = member2.DeclaringType.IsAssignableFromEx(member1.DeclaringType);
if (isSubclass)
{
var getter1 = ((PropertyInfo)member1).GetGetMethodEx();
var getter2 = ((PropertyInfo)member2).GetGetMethodEx();
var map = member1.DeclaringType.GetInterfaceMapEx(member2.DeclaringType);
foreach (var mi in map.InterfaceMethods)
if ((getter2 == null || (getter2.Name == mi.Name && getter2.DeclaringType == mi.DeclaringType)) &&
(getter1 == null || (getter1.Name == mi.Name && getter1.DeclaringType == mi.DeclaringType)))
{
return true;
}
}
}
}
return false;
}
#endregion
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// OrderTaxes
/// </summary>
[DataContract]
public partial class OrderTaxes : IEquatable<OrderTaxes>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="OrderTaxes" /> class.
/// </summary>
/// <param name="arbitraryTax">Arbitrary Tax, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system..</param>
/// <param name="arbitraryTaxRate">Arbitrary tax rate, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system..</param>
/// <param name="arbitraryTaxableSubtotal">Arbitrary taxable subtotal, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system..</param>
/// <param name="taxCityAccountingCode">QuickBooks tax city code.</param>
/// <param name="taxCountryAccountingCode">QuickBooks tax country code.</param>
/// <param name="taxCounty">County used for tax calculation purposes (only in the United States).</param>
/// <param name="taxCountyAccountingCode">QuickBooks tax county code.</param>
/// <param name="taxGiftCharge">True if gift charge is taxed.</param>
/// <param name="taxPostalCodeAccountingCode">QuickBooks tax postal code code.</param>
/// <param name="taxRate">Tax rate, this is meaningless for updating an order. For inserting a new order, if you need to override internal tax calculations, use the arbitrary fields..</param>
/// <param name="taxRateCity">Tax rate at the city level.</param>
/// <param name="taxRateCountry">Tax rate at the country level.</param>
/// <param name="taxRateCounty">Tax rate at the county level.</param>
/// <param name="taxRatePostalCode">Tax rate at the postal code level.</param>
/// <param name="taxRateState">Tax rate at the state level.</param>
/// <param name="taxShipping">True if shipping is taxed.</param>
/// <param name="taxStateAccountingCode">QuickBooks tax state code.</param>
public OrderTaxes(decimal? arbitraryTax = default(decimal?), decimal? arbitraryTaxRate = default(decimal?), decimal? arbitraryTaxableSubtotal = default(decimal?), string taxCityAccountingCode = default(string), string taxCountryAccountingCode = default(string), string taxCounty = default(string), string taxCountyAccountingCode = default(string), bool? taxGiftCharge = default(bool?), string taxPostalCodeAccountingCode = default(string), decimal? taxRate = default(decimal?), decimal? taxRateCity = default(decimal?), decimal? taxRateCountry = default(decimal?), decimal? taxRateCounty = default(decimal?), decimal? taxRatePostalCode = default(decimal?), decimal? taxRateState = default(decimal?), bool? taxShipping = default(bool?), string taxStateAccountingCode = default(string))
{
this.ArbitraryTax = arbitraryTax;
this.ArbitraryTaxRate = arbitraryTaxRate;
this.ArbitraryTaxableSubtotal = arbitraryTaxableSubtotal;
this.TaxCityAccountingCode = taxCityAccountingCode;
this.TaxCountryAccountingCode = taxCountryAccountingCode;
this.TaxCounty = taxCounty;
this.TaxCountyAccountingCode = taxCountyAccountingCode;
this.TaxGiftCharge = taxGiftCharge;
this.TaxPostalCodeAccountingCode = taxPostalCodeAccountingCode;
this.TaxRate = taxRate;
this.TaxRateCity = taxRateCity;
this.TaxRateCountry = taxRateCountry;
this.TaxRateCounty = taxRateCounty;
this.TaxRatePostalCode = taxRatePostalCode;
this.TaxRateState = taxRateState;
this.TaxShipping = taxShipping;
this.TaxStateAccountingCode = taxStateAccountingCode;
}
/// <summary>
/// Arbitrary Tax, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system.
/// </summary>
/// <value>Arbitrary Tax, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system.</value>
[DataMember(Name="arbitrary_tax", EmitDefaultValue=false)]
public decimal? ArbitraryTax { get; set; }
/// <summary>
/// Arbitrary tax rate, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system.
/// </summary>
/// <value>Arbitrary tax rate, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system.</value>
[DataMember(Name="arbitrary_tax_rate", EmitDefaultValue=false)]
public decimal? ArbitraryTaxRate { get; set; }
/// <summary>
/// Arbitrary taxable subtotal, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system.
/// </summary>
/// <value>Arbitrary taxable subtotal, this is meaningless for updating an order. For inserting a new order, this will override any internal tax calculations and should only be used for orders completed outside the system.</value>
[DataMember(Name="arbitrary_taxable_subtotal", EmitDefaultValue=false)]
public decimal? ArbitraryTaxableSubtotal { get; set; }
/// <summary>
/// QuickBooks tax city code
/// </summary>
/// <value>QuickBooks tax city code</value>
[DataMember(Name="tax_city_accounting_code", EmitDefaultValue=false)]
public string TaxCityAccountingCode { get; set; }
/// <summary>
/// QuickBooks tax country code
/// </summary>
/// <value>QuickBooks tax country code</value>
[DataMember(Name="tax_country_accounting_code", EmitDefaultValue=false)]
public string TaxCountryAccountingCode { get; set; }
/// <summary>
/// County used for tax calculation purposes (only in the United States)
/// </summary>
/// <value>County used for tax calculation purposes (only in the United States)</value>
[DataMember(Name="tax_county", EmitDefaultValue=false)]
public string TaxCounty { get; set; }
/// <summary>
/// QuickBooks tax county code
/// </summary>
/// <value>QuickBooks tax county code</value>
[DataMember(Name="tax_county_accounting_code", EmitDefaultValue=false)]
public string TaxCountyAccountingCode { get; set; }
/// <summary>
/// True if gift charge is taxed
/// </summary>
/// <value>True if gift charge is taxed</value>
[DataMember(Name="tax_gift_charge", EmitDefaultValue=false)]
public bool? TaxGiftCharge { get; set; }
/// <summary>
/// QuickBooks tax postal code code
/// </summary>
/// <value>QuickBooks tax postal code code</value>
[DataMember(Name="tax_postal_code_accounting_code", EmitDefaultValue=false)]
public string TaxPostalCodeAccountingCode { get; set; }
/// <summary>
/// Tax rate, this is meaningless for updating an order. For inserting a new order, if you need to override internal tax calculations, use the arbitrary fields.
/// </summary>
/// <value>Tax rate, this is meaningless for updating an order. For inserting a new order, if you need to override internal tax calculations, use the arbitrary fields.</value>
[DataMember(Name="tax_rate", EmitDefaultValue=false)]
public decimal? TaxRate { get; set; }
/// <summary>
/// Tax rate at the city level
/// </summary>
/// <value>Tax rate at the city level</value>
[DataMember(Name="tax_rate_city", EmitDefaultValue=false)]
public decimal? TaxRateCity { get; set; }
/// <summary>
/// Tax rate at the country level
/// </summary>
/// <value>Tax rate at the country level</value>
[DataMember(Name="tax_rate_country", EmitDefaultValue=false)]
public decimal? TaxRateCountry { get; set; }
/// <summary>
/// Tax rate at the county level
/// </summary>
/// <value>Tax rate at the county level</value>
[DataMember(Name="tax_rate_county", EmitDefaultValue=false)]
public decimal? TaxRateCounty { get; set; }
/// <summary>
/// Tax rate at the postal code level
/// </summary>
/// <value>Tax rate at the postal code level</value>
[DataMember(Name="tax_rate_postal_code", EmitDefaultValue=false)]
public decimal? TaxRatePostalCode { get; set; }
/// <summary>
/// Tax rate at the state level
/// </summary>
/// <value>Tax rate at the state level</value>
[DataMember(Name="tax_rate_state", EmitDefaultValue=false)]
public decimal? TaxRateState { get; set; }
/// <summary>
/// True if shipping is taxed
/// </summary>
/// <value>True if shipping is taxed</value>
[DataMember(Name="tax_shipping", EmitDefaultValue=false)]
public bool? TaxShipping { get; set; }
/// <summary>
/// QuickBooks tax state code
/// </summary>
/// <value>QuickBooks tax state code</value>
[DataMember(Name="tax_state_accounting_code", EmitDefaultValue=false)]
public string TaxStateAccountingCode { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OrderTaxes {\n");
sb.Append(" ArbitraryTax: ").Append(ArbitraryTax).Append("\n");
sb.Append(" ArbitraryTaxRate: ").Append(ArbitraryTaxRate).Append("\n");
sb.Append(" ArbitraryTaxableSubtotal: ").Append(ArbitraryTaxableSubtotal).Append("\n");
sb.Append(" TaxCityAccountingCode: ").Append(TaxCityAccountingCode).Append("\n");
sb.Append(" TaxCountryAccountingCode: ").Append(TaxCountryAccountingCode).Append("\n");
sb.Append(" TaxCounty: ").Append(TaxCounty).Append("\n");
sb.Append(" TaxCountyAccountingCode: ").Append(TaxCountyAccountingCode).Append("\n");
sb.Append(" TaxGiftCharge: ").Append(TaxGiftCharge).Append("\n");
sb.Append(" TaxPostalCodeAccountingCode: ").Append(TaxPostalCodeAccountingCode).Append("\n");
sb.Append(" TaxRate: ").Append(TaxRate).Append("\n");
sb.Append(" TaxRateCity: ").Append(TaxRateCity).Append("\n");
sb.Append(" TaxRateCountry: ").Append(TaxRateCountry).Append("\n");
sb.Append(" TaxRateCounty: ").Append(TaxRateCounty).Append("\n");
sb.Append(" TaxRatePostalCode: ").Append(TaxRatePostalCode).Append("\n");
sb.Append(" TaxRateState: ").Append(TaxRateState).Append("\n");
sb.Append(" TaxShipping: ").Append(TaxShipping).Append("\n");
sb.Append(" TaxStateAccountingCode: ").Append(TaxStateAccountingCode).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as OrderTaxes);
}
/// <summary>
/// Returns true if OrderTaxes instances are equal
/// </summary>
/// <param name="input">Instance of OrderTaxes to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OrderTaxes input)
{
if (input == null)
return false;
return
(
this.ArbitraryTax == input.ArbitraryTax ||
(this.ArbitraryTax != null &&
this.ArbitraryTax.Equals(input.ArbitraryTax))
) &&
(
this.ArbitraryTaxRate == input.ArbitraryTaxRate ||
(this.ArbitraryTaxRate != null &&
this.ArbitraryTaxRate.Equals(input.ArbitraryTaxRate))
) &&
(
this.ArbitraryTaxableSubtotal == input.ArbitraryTaxableSubtotal ||
(this.ArbitraryTaxableSubtotal != null &&
this.ArbitraryTaxableSubtotal.Equals(input.ArbitraryTaxableSubtotal))
) &&
(
this.TaxCityAccountingCode == input.TaxCityAccountingCode ||
(this.TaxCityAccountingCode != null &&
this.TaxCityAccountingCode.Equals(input.TaxCityAccountingCode))
) &&
(
this.TaxCountryAccountingCode == input.TaxCountryAccountingCode ||
(this.TaxCountryAccountingCode != null &&
this.TaxCountryAccountingCode.Equals(input.TaxCountryAccountingCode))
) &&
(
this.TaxCounty == input.TaxCounty ||
(this.TaxCounty != null &&
this.TaxCounty.Equals(input.TaxCounty))
) &&
(
this.TaxCountyAccountingCode == input.TaxCountyAccountingCode ||
(this.TaxCountyAccountingCode != null &&
this.TaxCountyAccountingCode.Equals(input.TaxCountyAccountingCode))
) &&
(
this.TaxGiftCharge == input.TaxGiftCharge ||
(this.TaxGiftCharge != null &&
this.TaxGiftCharge.Equals(input.TaxGiftCharge))
) &&
(
this.TaxPostalCodeAccountingCode == input.TaxPostalCodeAccountingCode ||
(this.TaxPostalCodeAccountingCode != null &&
this.TaxPostalCodeAccountingCode.Equals(input.TaxPostalCodeAccountingCode))
) &&
(
this.TaxRate == input.TaxRate ||
(this.TaxRate != null &&
this.TaxRate.Equals(input.TaxRate))
) &&
(
this.TaxRateCity == input.TaxRateCity ||
(this.TaxRateCity != null &&
this.TaxRateCity.Equals(input.TaxRateCity))
) &&
(
this.TaxRateCountry == input.TaxRateCountry ||
(this.TaxRateCountry != null &&
this.TaxRateCountry.Equals(input.TaxRateCountry))
) &&
(
this.TaxRateCounty == input.TaxRateCounty ||
(this.TaxRateCounty != null &&
this.TaxRateCounty.Equals(input.TaxRateCounty))
) &&
(
this.TaxRatePostalCode == input.TaxRatePostalCode ||
(this.TaxRatePostalCode != null &&
this.TaxRatePostalCode.Equals(input.TaxRatePostalCode))
) &&
(
this.TaxRateState == input.TaxRateState ||
(this.TaxRateState != null &&
this.TaxRateState.Equals(input.TaxRateState))
) &&
(
this.TaxShipping == input.TaxShipping ||
(this.TaxShipping != null &&
this.TaxShipping.Equals(input.TaxShipping))
) &&
(
this.TaxStateAccountingCode == input.TaxStateAccountingCode ||
(this.TaxStateAccountingCode != null &&
this.TaxStateAccountingCode.Equals(input.TaxStateAccountingCode))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.ArbitraryTax != null)
hashCode = hashCode * 59 + this.ArbitraryTax.GetHashCode();
if (this.ArbitraryTaxRate != null)
hashCode = hashCode * 59 + this.ArbitraryTaxRate.GetHashCode();
if (this.ArbitraryTaxableSubtotal != null)
hashCode = hashCode * 59 + this.ArbitraryTaxableSubtotal.GetHashCode();
if (this.TaxCityAccountingCode != null)
hashCode = hashCode * 59 + this.TaxCityAccountingCode.GetHashCode();
if (this.TaxCountryAccountingCode != null)
hashCode = hashCode * 59 + this.TaxCountryAccountingCode.GetHashCode();
if (this.TaxCounty != null)
hashCode = hashCode * 59 + this.TaxCounty.GetHashCode();
if (this.TaxCountyAccountingCode != null)
hashCode = hashCode * 59 + this.TaxCountyAccountingCode.GetHashCode();
if (this.TaxGiftCharge != null)
hashCode = hashCode * 59 + this.TaxGiftCharge.GetHashCode();
if (this.TaxPostalCodeAccountingCode != null)
hashCode = hashCode * 59 + this.TaxPostalCodeAccountingCode.GetHashCode();
if (this.TaxRate != null)
hashCode = hashCode * 59 + this.TaxRate.GetHashCode();
if (this.TaxRateCity != null)
hashCode = hashCode * 59 + this.TaxRateCity.GetHashCode();
if (this.TaxRateCountry != null)
hashCode = hashCode * 59 + this.TaxRateCountry.GetHashCode();
if (this.TaxRateCounty != null)
hashCode = hashCode * 59 + this.TaxRateCounty.GetHashCode();
if (this.TaxRatePostalCode != null)
hashCode = hashCode * 59 + this.TaxRatePostalCode.GetHashCode();
if (this.TaxRateState != null)
hashCode = hashCode * 59 + this.TaxRateState.GetHashCode();
if (this.TaxShipping != null)
hashCode = hashCode * 59 + this.TaxShipping.GetHashCode();
if (this.TaxStateAccountingCode != null)
hashCode = hashCode * 59 + this.TaxStateAccountingCode.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// TaxCounty (string) maxLength
if(this.TaxCounty != null && this.TaxCounty.Length > 32)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for TaxCounty, length must be less than 32.", new [] { "TaxCounty" });
}
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace Hadoop.Client.Jobs.WebHCatalog.Data
{
internal class JsonPayloadConverter : JsonPayloadConverterBase, IPayloadConverter
{
private readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
private const string ExitValuePropertyName = "exitValue";
private const string RunStatePropertyName = "runState";
private const string PercentCompletePropertyName = "percentComplete";
private const string StatusPropertyName = "status";
private const string UserArgsPropertyName = "userargs";
private const string StatusDirectoryPropertyName = "statusdir";
private const string DefinesPropertyName = "define";
private const string ArgumentsPropertyName = "arg";
private const string StartTimePropertyName = "startTime";
private const string JobNameKey = "hdInsightJobName=";
private const string DetailPropertyName = "detail";
private const string ExecutePropertyName = "execute";
private const string CommandPropertyName = "command";
private const string UnknownJobId = "unknown";
private const string ParentId = "parentId";
private const string JobId = "id";
private const string ErrorString = "error";
private const string Callback = "callback";
public string DeserializeJobSubmissionResponse(string payload)
{
return JObject.Parse(payload).Value<string>(JobId);
}
public JobList DeserializeListJobResult(string payload)
{
int t = 2 + 2;
//var ret = new JobList();
//var list = new List<JobDetails>();
//using (var parser = new JsonParser(payload))
//{
// var jobList = parser.ParseNext();
// if (jobList == null || !jobList.IsValidArray())
// {
// throw new InvalidOperationException();
// }
// if (jobList.IsEmpty)
// {
// return ret;
// }
// for (var i = 0; i < jobList.Count(); i++)
// {
// var job = jobList.GetIndex(i);
// if (job == null || !job.IsValidObject())
// {
// continue;
// }
// var detailProp = job.GetProperty(DetailPropertyName);
// if (detailProp != null && detailProp.IsValidObject())
// {
// try
// {
// var jobDetails = this.DeserializeJobDetails((JsonObject)detailProp);
// jobDetails.SubmissionTime = jobDetails.SubmissionTime.ToLocalTime();
// if (jobDetails != null)
// {
// list.Add(jobDetails);
// }
// }
// catch (InvalidOperationException)
// {
// //Eat it.
// }
// }
// }
//}
//ret.Jobs.AddRange((from j in list orderby j.SubmissionTime.ToUniversalTime() select j));
//return ret;
throw new NotImplementedException();
}
public JobDetails DeserializeJobDetails(string payload)
{
var job = JObject.Parse(payload);
var status = job[StatusPropertyName];
//TODO: thats not everything
return new JobDetails
{
Callback = job[UserArgsPropertyName].Value<string>(Callback),
JobId = status.Value<string>(JobId),
ExitCode = job.Value<int?>(ExitValuePropertyName),
SubmissionTime = _unixEpoch.AddMilliseconds(status.Value<int>(StartTimePropertyName)),
StatusCode = GetStatusCode(status),
};
}
private static JobStatusCode GetStatusCode(JToken status)
{
var code = status.Value<string>(RunStatePropertyName);
JobStatusCode result;
return Enum.TryParse(code, true, out result)
? result
: JobStatusCode.Unknown;
}
private JobDetails DeserializeJobDetails(JsonObject job)
{
//if (job == null || job.IsError || job.IsNullMissingOrEmpty)
//{
// throw new InvalidOperationException();
//}
//var jobId = string.Empty;
//if (!this.GetJobId(job, out jobId))
//{
// var errorString = this.GetJsonPropertyStringValue(job, ErrorString);
// if (!string.IsNullOrEmpty(errorString))
// {
// return null;
// }
// throw new InvalidOperationException();
//}
//var ret = new JobDetails()
//{
// JobId = jobId
//};
////NEIN: this is downcasting a long to an int.... which is ok for an exit code, but we should add a way to parse ints to the json lib
//ret.ExitCode = (int?)this.GetJsonPropertyNullableLongValue(job, ExitValuePropertyName);
//var status = this.GetJsonObject(job, StatusPropertyName);
//if (status != null)
//{
// var startTime = this.GetJsonPropertyLongValue(status, StartTimePropertyName);
// if (startTime != default(long))
// {
// ret.SubmissionTime = this.unixEpoch.AddMilliseconds(startTime);
// }
// ret.StatusCode = this.GetJobStatusCodeValue(status, RunStatePropertyName);
//}
//var userArgs = this.GetJsonObject(job, UserArgsPropertyName);
//if (userArgs != null)
//{
// ret.StatusDirectory = this.GetJsonPropertyStringValue(userArgs, StatusDirectoryPropertyName);
// ret.Query = this.GetJsonPropertyStringValue(userArgs, ExecutePropertyName);
// if (ret.Query.IsNullOrEmpty())
// {
// ret.Query = this.GetJsonPropertyStringValue(userArgs, CommandPropertyName);
// }
// var defines = this.GetJsonArray(userArgs, DefinesPropertyName);
// var arguments = this.GetJsonArray(userArgs, ArgumentsPropertyName);
// string jobName = string.Empty;
// if ((defines.IsNull() || !this.TryGetJobNameFromJsonArray(defines, out jobName)) && arguments.IsNotNull())
// {
// this.TryGetJobNameFromJsonArray(arguments, out jobName);
// }
// ret.Name = jobName;
//}
//ret.PercentComplete = this.GetJsonPropertyStringValue(job, PercentCompletePropertyName);
//ret.Callback = this.GetJsonPropertyStringValue(job, Callback);
//return ret;
throw new NotImplementedException();
}
private bool GetJobId(JsonItem details, out string jobId)
{
//var jobIdJson = details.GetProperty(JobId);
//if (jobIdJson == null || jobIdJson.IsNullOrMissing || jobIdJson.IsError)
//{
// var id = details.GetProperty(ParentId);
// return id.TryGetValue(out jobId);
//}
//return jobIdJson.TryGetValue(out jobId);
throw new NotImplementedException();
}
private bool TryGetJobNameFromJsonArray(IEnumerable<string> jsonArray, out string jobName)
{
//jobName = string.Empty;
//var jobNameItem = jsonArray.FirstOrDefault(s => s.Contains(JobNameKey));
//if (jobNameItem != null)
//{
// var jobNameString = jobNameItem;
// var indexOfNameAssigment = jobNameString.IndexOf('=');
// if (indexOfNameAssigment > -1 && jobNameString.Length > (indexOfNameAssigment + 1))
// {
// jobName = jobNameString.Substring(indexOfNameAssigment + 1);
// }
//}
//return jobName.IsNotNullOrEmpty();
throw new NotImplementedException();
}
private long GetJsonPropertyLongValue(JsonItem item, string property)
{
//long value;
//var prop = item.GetProperty(property);
//prop.TryGetValue(out value);
//return value;
throw new NotImplementedException();
}
private long? GetJsonPropertyNullableLongValue(JsonItem item, string property)
{
//long value;
//var prop = item.GetProperty(property);
//if (prop.TryGetValue(out value))
//{
// return value;
//}
//return null;
throw new NotImplementedException();
}
private JobStatusCode GetJobStatusCodeValue(JsonItem item, string property)
{
//var jobStatus = JobStatusCode.Unknown;
//var value = string.Empty;
//var prop = item.GetProperty(property);
//prop.TryGetValue(out value);
//if (value.IsNotNullOrEmpty())
//{
// if (!Enum.TryParse(value, true, out jobStatus))
// {
// jobStatus = JobStatusCode.Unknown;
// }
//}
//return jobStatus;
throw new NotImplementedException();
}
private string GetJsonPropertyStringValue(JsonItem item, string property)
{
//var value = string.Empty;
//var prop = item.GetProperty(property);
//prop.TryGetValue(out value);
//return value;
throw new NotImplementedException();
}
private string GetJsonStringValue(JsonItem item)
{
//var value = string.Empty;
//item.TryGetValue(out value);
//return value;
throw new NotImplementedException();
}
private JsonObject GetJsonObject(JsonItem item, string property)
{
//var prop = item.GetProperty(property);
//if (prop == null || !prop.IsValidObject())
//{
// return null;
//}
//return (JsonObject)prop;
throw new NotImplementedException();
}
private IEnumerable<string> GetJsonArray(JsonItem item, string property)
{
//var prop = item.GetProperty(property);
//if (prop == null || !prop.IsValidArray())
//{
// return null;
//}
//var ret = new List<string>();
//var array = (JsonArray)prop;
//for (var i = 0; i < array.Count(); i++)
//{
// var value = this.GetJsonStringValue(array.GetIndex(i));
// if (!string.IsNullOrEmpty(value))
// {
// ret.Add(value);
// }
//}
//return ret;
throw new NotImplementedException();
}
}
internal class JsonObject
{
}
internal class JsonItem
{
}
}
| |
//
// System.Diagnostics.DiagnosticsConfigurationHandler.cs
//
// Comments from John R. Hicks <angryjohn69@nc.rr.com> original implementation
// can be found at: /mcs/docs/apidocs/xml/en/System.Diagnostics
//
// Authors:
// John R. Hicks <angryjohn69@nc.rr.com>
// Jonathan Pryor <jonpryor@vt.edu>
//
// (C) 2002, 2005
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Reflection;
using System.Threading;
#if (XML_DEP)
using System.Xml;
#endif
namespace System.Diagnostics
{
// It handles following elements in <system.diagnostics> :
// - <sharedListeners> [2.0]
// - <sources>
// - <source>
// - <listeners> (collection)
// - <switches>
// - <add name=string value=string />
// - <trace autoflush=bool indentsize=int useGlobalLock=bool>
// - <listeners>
internal sealed class DiagnosticsConfiguration
{
#if NO_LOCK_FREE
private static object lock_ = new object();
#endif
private static object settings;
public static IDictionary Settings {
get {
#if !NO_LOCK_FREE
if (settings == null) {
object s = ConfigurationSettings.GetConfig ("system.diagnostics");
if (s == null)
throw new Exception ("INTERNAL configuration error: failed to get configuration 'system.diagnostics'");
Thread.MemoryBarrier ();
while (Interlocked.CompareExchange (ref settings, s, null) == null) {
// do nothing; we're just setting settings.
}
Thread.MemoryBarrier ();
}
#else
lock (lock_) {
if (settings == null)
settings = ConfigurationSettings.GetConfig ("system.diagnostics");
}
#endif
return (IDictionary) settings;
}
}
}
#if (XML_DEP)
[Obsolete ("This class is obsoleted")]
public class DiagnosticsConfigurationHandler : IConfigurationSectionHandler
{
TraceImplSettings configValues;
delegate void ElementHandler (IDictionary d, XmlNode node);
IDictionary elementHandlers = new Hashtable ();
public DiagnosticsConfigurationHandler ()
{
elementHandlers ["assert"] = new ElementHandler (AddAssertNode);
elementHandlers ["switches"] = new ElementHandler (AddSwitchesNode);
elementHandlers ["trace"] = new ElementHandler (AddTraceNode);
elementHandlers ["sources"] = new ElementHandler (AddSourcesNode);
}
public virtual object Create (object parent, object configContext, XmlNode section)
{
IDictionary d;
if (parent == null)
d = new Hashtable (CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default);
else
d = (IDictionary) ((ICloneable)parent).Clone();
if (d.Contains (TraceImplSettings.Key))
configValues = (TraceImplSettings) d [TraceImplSettings.Key];
else
d.Add (TraceImplSettings.Key, configValues = new TraceImplSettings ());
// process <sharedListeners> first
foreach (XmlNode child in section.ChildNodes) {
switch (child.NodeType) {
case XmlNodeType.Element:
if (child.LocalName != "sharedListeners")
continue;
AddTraceListeners (d, child, GetSharedListeners (d));
break;
}
}
foreach (XmlNode child in section.ChildNodes) {
XmlNodeType type = child.NodeType;
switch (type) {
/* ignore */
case XmlNodeType.Whitespace:
case XmlNodeType.Comment:
continue;
case XmlNodeType.Element:
if (child.LocalName == "sharedListeners")
continue;
ElementHandler eh = (ElementHandler) elementHandlers [child.Name];
if (eh != null)
eh (d, child);
else
ThrowUnrecognizedElement (child);
break;
default:
ThrowUnrecognizedElement (child);
break;
}
}
return d;
}
// Remarks: Both attribute are optional
private void AddAssertNode (IDictionary d, XmlNode node)
{
XmlAttributeCollection c = node.Attributes;
string assertuienabled = GetAttribute (c, "assertuienabled", false, node);
string logfilename = GetAttribute (c, "logfilename", false, node);
ValidateInvalidAttributes (c, node);
if (assertuienabled != null) {
try {
d ["assertuienabled"] = bool.Parse (assertuienabled);
}
catch (Exception e) {
throw new ConfigurationException ("The `assertuienabled' attribute must be `true' or `false'",
e, node);
}
}
if (logfilename != null)
d ["logfilename"] = logfilename;
DefaultTraceListener dtl = (DefaultTraceListener) configValues.Listeners["Default"];
if (dtl != null) {
if (assertuienabled != null)
dtl.AssertUiEnabled = (bool) d ["assertuienabled"];
if (logfilename != null)
dtl.LogFileName = logfilename;
}
if (node.ChildNodes.Count > 0)
ThrowUnrecognizedElement (node.ChildNodes[0]);
}
// name and value attributes are required
// Docs do not define "remove" or "clear" elements, but .NET recognizes
// them
private void AddSwitchesNode (IDictionary d, XmlNode node)
{
#if !TARGET_JVM
// There are no attributes on <switch/>
ValidateInvalidAttributes (node.Attributes, node);
IDictionary newNodes = new Hashtable ();
foreach (XmlNode child in node.ChildNodes) {
XmlNodeType t = child.NodeType;
if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
continue;
if (t == XmlNodeType.Element) {
XmlAttributeCollection attributes = child.Attributes;
string name = null;
string value = null;
switch (child.Name) {
case "add":
name = GetAttribute (attributes, "name", true, child);
value = GetAttribute (attributes, "value", true, child);
newNodes [name] = GetSwitchValue (name, value);
break;
case "remove":
name = GetAttribute (attributes, "name", true, child);
newNodes.Remove (name);
break;
case "clear":
newNodes.Clear ();
break;
default:
ThrowUnrecognizedElement (child);
break;
}
ValidateInvalidAttributes (attributes, child);
}
else
ThrowUnrecognizedNode (child);
}
d [node.Name] = newNodes;
#endif
}
private static object GetSwitchValue (string name, string value)
{
return value;
}
private void AddTraceNode (IDictionary d, XmlNode node)
{
AddTraceAttributes (d, node);
foreach (XmlNode child in node.ChildNodes) {
XmlNodeType t = child.NodeType;
if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
continue;
if (t == XmlNodeType.Element) {
if (child.Name == "listeners")
AddTraceListeners (d, child, configValues.Listeners);
else
ThrowUnrecognizedElement (child);
ValidateInvalidAttributes (child.Attributes, child);
}
else
ThrowUnrecognizedNode (child);
}
}
// all attributes are optional
private void AddTraceAttributes (IDictionary d, XmlNode node)
{
XmlAttributeCollection c = node.Attributes;
string autoflushConf = GetAttribute (c, "autoflush", false, node);
string indentsizeConf = GetAttribute (c, "indentsize", false, node);
ValidateInvalidAttributes (c, node);
if (autoflushConf != null) {
bool autoflush = false;
try {
autoflush = bool.Parse (autoflushConf);
d ["autoflush"] = autoflush;
} catch (Exception e) {
throw new ConfigurationException ("The `autoflush' attribute must be `true' or `false'",
e, node);
}
configValues.AutoFlush = autoflush;
}
if (indentsizeConf != null) {
int indentsize = 0;
try {
indentsize = int.Parse (indentsizeConf);
d ["indentsize"] = indentsize;
} catch (Exception e) {
throw new ConfigurationException ("The `indentsize' attribute must be an integral value.",
e, node);
}
configValues.IndentSize = indentsize;
}
}
private TraceListenerCollection GetSharedListeners (IDictionary d)
{
TraceListenerCollection shared_listeners = d ["sharedListeners"] as TraceListenerCollection;
if (shared_listeners == null) {
shared_listeners = new TraceListenerCollection (false);
d ["sharedListeners"] = shared_listeners;
}
return shared_listeners;
}
private void AddSourcesNode (IDictionary d, XmlNode node)
{
// FIXME: are there valid attributes?
ValidateInvalidAttributes (node.Attributes, node);
Hashtable sources = d ["sources"] as Hashtable;
if (sources == null) {
sources = new Hashtable ();
d ["sources"] = sources;
}
foreach (XmlNode child in node.ChildNodes) {
XmlNodeType t = child.NodeType;
if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
continue;
if (t == XmlNodeType.Element) {
if (child.Name == "source")
AddTraceSource (d, sources, child);
else
ThrowUnrecognizedElement (child);
// ValidateInvalidAttributes (child.Attributes, child);
}
else
ThrowUnrecognizedNode (child);
}
}
private void AddTraceSource (IDictionary d, Hashtable sources, XmlNode node)
{
string name = null;
SourceLevels levels = SourceLevels.Error;
StringDictionary atts = new StringDictionary ();
foreach (XmlAttribute a in node.Attributes) {
switch (a.Name) {
case "name":
name = a.Value;
break;
case "switchValue":
levels = (SourceLevels) Enum.Parse (typeof (SourceLevels), a.Value);
break;
default:
atts [a.Name] = a.Value;
break;
}
}
if (name == null)
throw new ConfigurationException ("Mandatory attribute 'name' is missing in 'source' element.");
// ignore duplicate ones (no error occurs)
if (sources.ContainsKey (name))
return;
TraceSourceInfo sinfo = new TraceSourceInfo (name, levels, configValues);
sources.Add (sinfo.Name, sinfo);
foreach (XmlNode child in node.ChildNodes) {
XmlNodeType t = child.NodeType;
if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
continue;
if (t == XmlNodeType.Element) {
if (child.Name == "listeners")
AddTraceListeners (d, child, sinfo.Listeners);
else
ThrowUnrecognizedElement (child);
ValidateInvalidAttributes (child.Attributes, child);
}
else
ThrowUnrecognizedNode (child);
}
}
// only defines "add" and "remove", but "clear" also works
// for add, "name" is required; initializeData is optional; "type" is required in 1.x, optional in 2.0.
private void AddTraceListeners (IDictionary d, XmlNode listenersNode, TraceListenerCollection listeners)
{
#if !TARGET_JVM
// There are no attributes on <listeners/>
ValidateInvalidAttributes (listenersNode.Attributes, listenersNode);
foreach (XmlNode child in listenersNode.ChildNodes) {
XmlNodeType t = child.NodeType;
if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
continue;
if (t == XmlNodeType.Element) {
XmlAttributeCollection attributes = child.Attributes;
string name = null;
switch (child.Name) {
case "add":
AddTraceListener (d, child, attributes, listeners);
break;
case "remove":
name = GetAttribute (attributes, "name", true, child);
RemoveTraceListener (name);
break;
case "clear":
configValues.Listeners.Clear ();
break;
default:
ThrowUnrecognizedElement (child);
break;
}
ValidateInvalidAttributes (attributes, child);
}
else
ThrowUnrecognizedNode (child);
}
#endif
}
private void AddTraceListener (IDictionary d, XmlNode child, XmlAttributeCollection attributes, TraceListenerCollection listeners)
{
string name = GetAttribute (attributes, "name", true, child);
string type = null;
#if CONFIGURATION_DEP
type = GetAttribute (attributes, "type", false, child);
if (type == null) {
// indicated by name.
TraceListener shared = GetSharedListeners (d) [name];
if (shared == null)
throw new ConfigurationException (String.Format ("Shared trace listener {0} does not exist.", name));
if (attributes.Count != 0)
throw new ConfigurationErrorsException (string.Format (
"Listener '{0}' references a shared " +
"listener and can only have a 'Name' " +
"attribute.", name));
listeners.Add (shared, configValues);
return;
}
#else
type = GetAttribute (attributes, "type", true, child);
#endif
Type t = Type.GetType (type);
if (t == null)
throw new ConfigurationException (string.Format ("Invalid Type Specified: {0}", type));
object[] args;
Type[] types;
string initializeData = GetAttribute (attributes, "initializeData", false, child);
if (initializeData != null) {
args = new object[] { initializeData };
types = new Type[] { typeof(string) };
} else {
args = null;
types = Type.EmptyTypes;
}
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
if (t.Assembly == GetType ().Assembly)
flags |= BindingFlags.NonPublic;
ConstructorInfo ctor = t.GetConstructor (flags, null, types, null);
if (ctor == null)
throw new ConfigurationException ("Couldn't find constructor for class " + type);
TraceListener l = (TraceListener) ctor.Invoke (args);
l.Name = name;
#if CONFIGURATION_DEP
string trace = GetAttribute (attributes, "traceOutputOptions", false, child);
if (trace != null) {
if (trace != trace.Trim ())
throw new ConfigurationErrorsException (string.Format (
"Invalid value '{0}' for 'traceOutputOptions'.",
trace), child);
TraceOptions trace_options;
try {
trace_options = (TraceOptions) Enum.Parse (
typeof (TraceOptions), trace);
} catch (ArgumentException) {
throw new ConfigurationErrorsException (string.Format (
"Invalid value '{0}' for 'traceOutputOptions'.",
trace), child);
}
l.TraceOutputOptions = trace_options;
}
string [] supported_attributes = l.GetSupportedAttributes ();
if (supported_attributes != null) {
for (int i = 0; i < supported_attributes.Length; i++) {
string key = supported_attributes [i];
string value = GetAttribute (attributes, key, false, child);
if (value != null)
l.Attributes.Add (key, value);
}
}
#endif
listeners.Add (l, configValues);
}
private void RemoveTraceListener (string name)
{
try {
configValues.Listeners.Remove (name);
}
catch (ArgumentException) {
// The specified listener wasn't in the collection
// Ignore this; .NET does.
}
catch (Exception e) {
throw new ConfigurationException (
string.Format ("Unknown error removing listener: {0}", name),
e);
}
}
private string GetAttribute (XmlAttributeCollection attrs, string attr, bool required, XmlNode node)
{
XmlAttribute a = attrs[attr];
string r = null;
if (a != null) {
r = a.Value;
if (required)
ValidateAttribute (attr, r, node);
attrs.Remove (a);
}
else if (required)
ThrowMissingAttribute (attr, node);
return r;
}
private void ValidateAttribute (string attribute, string value, XmlNode node)
{
if (value == null || value.Length == 0)
throw new ConfigurationException (string.Format ("Required attribute '{0}' cannot be empty.", attribute), node);
}
private void ValidateInvalidAttributes (XmlAttributeCollection c, XmlNode node)
{
if (c.Count != 0)
ThrowUnrecognizedAttribute (c[0].Name, node);
}
private void ThrowMissingAttribute (string attribute, XmlNode node)
{
throw new ConfigurationException (string.Format ("Required attribute '{0}' not found.", attribute), node);
}
private void ThrowUnrecognizedNode (XmlNode node)
{
throw new ConfigurationException (
string.Format ("Unrecognized node `{0}'; nodeType={1}", node.Name, node.NodeType),
node);
}
private void ThrowUnrecognizedElement (XmlNode node)
{
throw new ConfigurationException (
string.Format ("Unrecognized element '{0}'.", node.Name),
node);
}
private void ThrowUnrecognizedAttribute (string attribute, XmlNode node)
{
throw new ConfigurationException (
string.Format ("Unrecognized attribute '{0}' on element <{1}/>.", attribute, node.Name),
node);
}
}
#endif
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcov = Google.Cloud.OrgPolicy.V2;
using sys = System;
namespace Google.Cloud.OrgPolicy.V2
{
/// <summary>Resource name for the <c>Policy</c> resource.</summary>
public sealed partial class PolicyName : gax::IResourceName, sys::IEquatable<PolicyName>
{
/// <summary>The possible contents of <see cref="PolicyName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/policies/{policy}</c>.</summary>
ProjectPolicy = 1,
/// <summary>A resource name with pattern <c>folders/{folder}/policies/{policy}</c>.</summary>
FolderPolicy = 2,
/// <summary>A resource name with pattern <c>organizations/{organization}/policies/{policy}</c>.</summary>
OrganizationPolicy = 3,
}
private static gax::PathTemplate s_projectPolicy = new gax::PathTemplate("projects/{project}/policies/{policy}");
private static gax::PathTemplate s_folderPolicy = new gax::PathTemplate("folders/{folder}/policies/{policy}");
private static gax::PathTemplate s_organizationPolicy = new gax::PathTemplate("organizations/{organization}/policies/{policy}");
/// <summary>Creates a <see cref="PolicyName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="PolicyName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static PolicyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new PolicyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="PolicyName"/> with the pattern <c>projects/{project}/policies/{policy}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="policyId">The <c>Policy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PolicyName"/> constructed from the provided ids.</returns>
public static PolicyName FromProjectPolicy(string projectId, string policyId) =>
new PolicyName(ResourceNameType.ProjectPolicy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), policyId: gax::GaxPreconditions.CheckNotNullOrEmpty(policyId, nameof(policyId)));
/// <summary>
/// Creates a <see cref="PolicyName"/> with the pattern <c>folders/{folder}/policies/{policy}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="policyId">The <c>Policy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PolicyName"/> constructed from the provided ids.</returns>
public static PolicyName FromFolderPolicy(string folderId, string policyId) =>
new PolicyName(ResourceNameType.FolderPolicy, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), policyId: gax::GaxPreconditions.CheckNotNullOrEmpty(policyId, nameof(policyId)));
/// <summary>
/// Creates a <see cref="PolicyName"/> with the pattern <c>organizations/{organization}/policies/{policy}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="policyId">The <c>Policy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PolicyName"/> constructed from the provided ids.</returns>
public static PolicyName FromOrganizationPolicy(string organizationId, string policyId) =>
new PolicyName(ResourceNameType.OrganizationPolicy, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), policyId: gax::GaxPreconditions.CheckNotNullOrEmpty(policyId, nameof(policyId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PolicyName"/> with pattern
/// <c>projects/{project}/policies/{policy}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="policyId">The <c>Policy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PolicyName"/> with pattern
/// <c>projects/{project}/policies/{policy}</c>.
/// </returns>
public static string Format(string projectId, string policyId) => FormatProjectPolicy(projectId, policyId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PolicyName"/> with pattern
/// <c>projects/{project}/policies/{policy}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="policyId">The <c>Policy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PolicyName"/> with pattern
/// <c>projects/{project}/policies/{policy}</c>.
/// </returns>
public static string FormatProjectPolicy(string projectId, string policyId) =>
s_projectPolicy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(policyId, nameof(policyId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PolicyName"/> with pattern
/// <c>folders/{folder}/policies/{policy}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="policyId">The <c>Policy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PolicyName"/> with pattern
/// <c>folders/{folder}/policies/{policy}</c>.
/// </returns>
public static string FormatFolderPolicy(string folderId, string policyId) =>
s_folderPolicy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(policyId, nameof(policyId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PolicyName"/> with pattern
/// <c>organizations/{organization}/policies/{policy}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="policyId">The <c>Policy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PolicyName"/> with pattern
/// <c>organizations/{organization}/policies/{policy}</c>.
/// </returns>
public static string FormatOrganizationPolicy(string organizationId, string policyId) =>
s_organizationPolicy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(policyId, nameof(policyId)));
/// <summary>Parses the given resource name string into a new <see cref="PolicyName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/policies/{policy}</c></description></item>
/// <item><description><c>folders/{folder}/policies/{policy}</c></description></item>
/// <item><description><c>organizations/{organization}/policies/{policy}</c></description></item>
/// </list>
/// </remarks>
/// <param name="policyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="PolicyName"/> if successful.</returns>
public static PolicyName Parse(string policyName) => Parse(policyName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="PolicyName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/policies/{policy}</c></description></item>
/// <item><description><c>folders/{folder}/policies/{policy}</c></description></item>
/// <item><description><c>organizations/{organization}/policies/{policy}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="policyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="PolicyName"/> if successful.</returns>
public static PolicyName Parse(string policyName, bool allowUnparsed) =>
TryParse(policyName, allowUnparsed, out PolicyName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PolicyName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/policies/{policy}</c></description></item>
/// <item><description><c>folders/{folder}/policies/{policy}</c></description></item>
/// <item><description><c>organizations/{organization}/policies/{policy}</c></description></item>
/// </list>
/// </remarks>
/// <param name="policyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PolicyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string policyName, out PolicyName result) => TryParse(policyName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PolicyName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/policies/{policy}</c></description></item>
/// <item><description><c>folders/{folder}/policies/{policy}</c></description></item>
/// <item><description><c>organizations/{organization}/policies/{policy}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="policyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PolicyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string policyName, bool allowUnparsed, out PolicyName result)
{
gax::GaxPreconditions.CheckNotNull(policyName, nameof(policyName));
gax::TemplatedResourceName resourceName;
if (s_projectPolicy.TryParseName(policyName, out resourceName))
{
result = FromProjectPolicy(resourceName[0], resourceName[1]);
return true;
}
if (s_folderPolicy.TryParseName(policyName, out resourceName))
{
result = FromFolderPolicy(resourceName[0], resourceName[1]);
return true;
}
if (s_organizationPolicy.TryParseName(policyName, out resourceName))
{
result = FromOrganizationPolicy(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(policyName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private PolicyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string folderId = null, string organizationId = null, string policyId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
FolderId = folderId;
OrganizationId = organizationId;
PolicyId = policyId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="PolicyName"/> class from the component parts of pattern
/// <c>projects/{project}/policies/{policy}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="policyId">The <c>Policy</c> ID. Must not be <c>null</c> or empty.</param>
public PolicyName(string projectId, string policyId) : this(ResourceNameType.ProjectPolicy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), policyId: gax::GaxPreconditions.CheckNotNullOrEmpty(policyId, nameof(policyId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Policy</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string PolicyId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectPolicy: return s_projectPolicy.Expand(ProjectId, PolicyId);
case ResourceNameType.FolderPolicy: return s_folderPolicy.Expand(FolderId, PolicyId);
case ResourceNameType.OrganizationPolicy: return s_organizationPolicy.Expand(OrganizationId, PolicyId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as PolicyName);
/// <inheritdoc/>
public bool Equals(PolicyName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(PolicyName a, PolicyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(PolicyName a, PolicyName b) => !(a == b);
}
public partial class Policy
{
/// <summary>
/// <see cref="gcov::PolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::PolicyName PolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::PolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListConstraintsRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::FolderName ParentAsFolderName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::OrganizationName ParentAsOrganizationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder))
{
return folder;
}
if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization))
{
return organization;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListPoliciesRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::FolderName ParentAsFolderName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::OrganizationName ParentAsOrganizationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder))
{
return folder;
}
if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization))
{
return organization;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetPolicyRequest
{
/// <summary>
/// <see cref="gcov::PolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::PolicyName PolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::PolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetEffectivePolicyRequest
{
/// <summary>
/// <see cref="gcov::PolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::PolicyName PolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::PolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreatePolicyRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::FolderName ParentAsFolderName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::OrganizationName ParentAsOrganizationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder))
{
return folder;
}
if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization))
{
return organization;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeletePolicyRequest
{
/// <summary>
/// <see cref="gcov::PolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::PolicyName PolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::PolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Store
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Creates an Azure Data Lake Store filesystem client.
/// </summary>
public partial class DataLakeStoreFileSystemManagementClient : ServiceClient<DataLakeStoreFileSystemManagementClient>, IDataLakeStoreFileSystemManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
internal string BaseUri {get; set;}
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public string AdlsFileSystemDnsSuffix { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IFileSystemOperations.
/// </summary>
public virtual IFileSystemOperations FileSystem { get; private set; }
/// <summary>
/// Initializes a new instance of the DataLakeStoreFileSystemManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeStoreFileSystemManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreFileSystemManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeStoreFileSystemManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreFileSystemManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeStoreFileSystemManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreFileSystemManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeStoreFileSystemManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
FileSystem = new FileSystemOperations(this);
BaseUri = "https://{accountName}.{adlsFileSystemDnsSuffix}";
ApiVersion = "2016-11-01";
AdlsFileSystemDnsSuffix = "azuredatalakestore.net";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<AdlsRemoteException>("exception"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<AdlsRemoteException>("exception"));
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using Xunit;
namespace Tests.Collections
{
public enum CollectionOrder
{
Unspecified,
Sequential
}
public abstract class IEnumerableTest<T>
{
private const int EnumerableSize = 16;
protected T DefaultValue => default(T);
protected bool MoveNextAtEndThrowsOnModifiedCollection => true;
protected virtual CollectionOrder CollectionOrder => CollectionOrder.Sequential;
protected abstract bool IsResetNotSupported { get; }
protected abstract bool IsGenericCompatibility { get; }
protected abstract object GenerateItem();
protected object[] GenerateItems(int size)
{
var ret = new object[size];
for (var i = 0; i < size; i++)
{
ret[i] = GenerateItem();
}
return ret;
}
/// <summary>
/// When overridden in a derived class, Gets an instance of the enumerable under test containing the given items.
/// </summary>
/// <param name="items">The items to initialize the enumerable with.</param>
/// <returns>An instance of the enumerable under test containing the given items.</returns>
protected abstract IEnumerable GetEnumerable(object[] items);
/// <summary>
/// When overridden in a derived class, invalidates any enumerators for the given IEnumerable.
/// </summary>
/// <param name="enumerable">The <see cref="IEnumerable" /> to invalidate enumerators for.</param>
/// <returns>The new set of items in the <see cref="IEnumerable" /></returns>
protected abstract object[] InvalidateEnumerator(IEnumerable enumerable);
private void RepeatTest(
Action<IEnumerator, object[], int> testCode,
int iters = 3)
{
object[] items = GenerateItems(32);
IEnumerable enumerable = GetEnumerable(items);
IEnumerator enumerator = enumerable.GetEnumerator();
for (var i = 0; i < iters; i++)
{
testCode(enumerator, items, i);
if (IsResetNotSupported)
{
enumerator = enumerable.GetEnumerator();
}
else
{
enumerator.Reset();
}
}
}
private void RepeatTest(
Action<IEnumerator, object[]> testCode,
int iters = 3)
{
RepeatTest((e, i, it) => testCode(e, i), iters);
}
[Fact]
public void MoveNextHitsAllItems()
{
RepeatTest(
(enumerator, items) =>
{
var iterations = 0;
while (enumerator.MoveNext())
{
iterations++;
}
Assert.Equal(items.Length, iterations);
});
}
[Fact]
public void CurrentThrowsAfterEndOfCollection()
{
if (IsGenericCompatibility)
{
return;
// apparently it is okay if enumerator.Current doesn't throw when the collection is generic.
}
RepeatTest(
(enumerator, items) =>
{
while (enumerator.MoveNext())
{
}
Assert.Throws<InvalidOperationException>(
() => enumerator.Current);
});
}
[Fact]
public void MoveNextFalseAfterEndOfCollection()
{
RepeatTest(
(enumerator, items) =>
{
while (enumerator.MoveNext())
{
}
Assert.False(enumerator.MoveNext());
});
}
[Fact]
public void Current()
{
// Verify that current returns proper result.
RepeatTest(
(enumerator, items, iteration) =>
{
if (iteration == 1)
{
VerifyEnumerator(
enumerator,
items,
0,
items.Length/2,
true,
false);
}
else
{
VerifyEnumerator(enumerator, items);
}
});
}
[Fact]
public void Reset()
{
if (IsResetNotSupported)
{
RepeatTest(
(enumerator, items) =>
{
Assert.Throws<NotSupportedException>(
() => enumerator.Reset());
});
RepeatTest(
(enumerator, items, iter) =>
{
if (iter == 1)
{
VerifyEnumerator(
enumerator,
items,
0,
items.Length/2,
true,
false);
for (var i = 0; i < 3; i++)
{
Assert.Throws<NotSupportedException>(
() => enumerator.Reset());
}
VerifyEnumerator(
enumerator,
items,
items.Length/2,
items.Length - (items.Length/2),
false,
true);
}
else if (iter == 2)
{
VerifyEnumerator(enumerator, items);
for (var i = 0; i < 3; i++)
{
Assert.Throws<NotSupportedException>(
() => enumerator.Reset());
}
VerifyEnumerator(
enumerator,
items,
0,
0,
false,
true);
}
else
{
VerifyEnumerator(enumerator, items);
}
});
}
else
{
RepeatTest(
(enumerator, items, iter) =>
{
if (iter == 1)
{
VerifyEnumerator(
enumerator,
items,
0,
items.Length/2,
true,
false);
enumerator.Reset();
enumerator.Reset();
}
else if (iter == 3)
{
VerifyEnumerator(enumerator, items);
enumerator.Reset();
enumerator.Reset();
}
else
{
VerifyEnumerator(enumerator, items);
}
},
5);
}
}
[Fact]
public void ModifyCollectionWithNewEnumerator()
{
IEnumerable enumerable =
GetEnumerable(GenerateItems(EnumerableSize));
IEnumerator enumerator = enumerable.GetEnumerator();
InvalidateEnumerator(enumerable);
VerifyModifiedEnumerator(enumerator, null, true, false);
}
[Fact]
public void EnumerateFirstItemThenModify()
{
object[] items = GenerateItems(EnumerableSize);
IEnumerable enumerable = GetEnumerable(items);
IEnumerator enumerator = enumerable.GetEnumerator();
VerifyEnumerator(enumerator, items, 0, 1, true, false);
object currentItem = enumerator.Current;
InvalidateEnumerator(enumerable);
VerifyModifiedEnumerator(
enumerator,
currentItem,
false,
false);
}
[Fact]
public void EnumeratePartOfCollectionThenModify()
{
object[] items = GenerateItems(EnumerableSize);
IEnumerable enumerable = GetEnumerable(items);
IEnumerator enumerator = enumerable.GetEnumerator();
VerifyEnumerator(
enumerator,
items,
0,
items.Length/2,
true,
false);
object currentItem = enumerator.Current;
InvalidateEnumerator(enumerable);
VerifyModifiedEnumerator(
enumerator,
currentItem,
false,
false);
}
[Fact]
public void EnumerateEntireCollectionThenModify()
{
object[] items = GenerateItems(EnumerableSize);
IEnumerable enumerable = GetEnumerable(items);
IEnumerator enumerator = enumerable.GetEnumerator();
VerifyEnumerator(
enumerator,
items,
0,
items.Length,
true,
false);
object currentItem = enumerator.Current;
InvalidateEnumerator(enumerable);
VerifyModifiedEnumerator(
enumerator,
currentItem,
false,
true);
}
[Fact]
public void EnumerateThenModifyThrows()
{
object[] items = GenerateItems(EnumerableSize);
IEnumerable enumerable = GetEnumerable(items);
IEnumerator enumerator = enumerable.GetEnumerator();
VerifyEnumerator(
enumerator,
items,
0,
items.Length/2,
true,
false);
object currentItem = enumerator.Current;
InvalidateEnumerator(enumerable);
Assert.Equal(currentItem, enumerator.Current);
Assert.Throws<InvalidOperationException>(
() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(
() => enumerator.Reset());
}
[Fact]
public void EnumeratePastEndThenModify()
{
object[] items = GenerateItems(EnumerableSize);
IEnumerable enumerable = GetEnumerable(items);
IEnumerator enumerator = enumerable.GetEnumerator();
// enumerate to the end
VerifyEnumerator(enumerator, items);
// add elements to the collection
InvalidateEnumerator(enumerable);
// check that it throws proper exceptions
VerifyModifiedEnumerator(
enumerator,
DefaultValue,
false,
true);
}
private void VerifyModifiedEnumerator(
IEnumerator enumerator,
object expectedCurrent,
bool expectCurrentThrow,
bool atEnd)
{
if (expectCurrentThrow)
{
Assert.Throws<InvalidOperationException>(
() => enumerator.Current);
}
else
{
object current = enumerator.Current;
for (var i = 0; i < 3; i++)
{
Assert.Equal(expectedCurrent, current);
current = enumerator.Current;
}
}
if (!atEnd || MoveNextAtEndThrowsOnModifiedCollection)
{
Assert.Throws<InvalidOperationException>(
() => enumerator.MoveNext());
}
else
{
Assert.False(enumerator.MoveNext());
}
if (!IsResetNotSupported)
{
Assert.Throws<InvalidOperationException>(
() => enumerator.Reset());
}
}
private void VerifyEnumerator(
IEnumerator enumerator,
object[] expectedItems)
{
VerifyEnumerator(
enumerator,
expectedItems,
0,
expectedItems.Length,
true,
true);
}
private void VerifyEnumerator(
IEnumerator enumerator,
object[] expectedItems,
int startIndex,
int count,
bool validateStart,
bool validateEnd)
{
bool needToMatchAllExpectedItems = count - startIndex
== expectedItems.Length;
if (validateStart)
{
for (var i = 0; i < 3; i++)
{
Assert.Throws<InvalidOperationException>(
() => enumerator.Current);
}
}
int iterations;
if (CollectionOrder == CollectionOrder.Unspecified)
{
var itemsVisited =
new BitArray(
needToMatchAllExpectedItems
? count
: expectedItems.Length,
false);
for (iterations = 0;
iterations < count && enumerator.MoveNext();
iterations++)
{
object currentItem = enumerator.Current;
var itemFound = false;
for (var i = 0; i < itemsVisited.Length; ++i)
{
if (!itemsVisited[i]
&& Equals(
currentItem,
expectedItems[
i
+ (needToMatchAllExpectedItems
? startIndex
: 0)]))
{
itemsVisited[i] = true;
itemFound = true;
break;
}
}
Assert.True(itemFound, "itemFound");
for (var i = 0; i < 3; i++)
{
object tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem);
}
}
if (needToMatchAllExpectedItems)
{
for (var i = 0; i < itemsVisited.Length; i++)
{
Assert.True(itemsVisited[i]);
}
}
else
{
var visitedItemCount = 0;
for (var i = 0; i < itemsVisited.Length; i++)
{
if (itemsVisited[i])
{
++visitedItemCount;
}
}
Assert.Equal(count, visitedItemCount);
}
}
else if (CollectionOrder == CollectionOrder.Sequential)
{
for (iterations = 0;
iterations < count && enumerator.MoveNext();
iterations++)
{
object currentItem = enumerator.Current;
Assert.Equal(expectedItems[iterations], currentItem);
for (var i = 0; i < 3; i++)
{
object tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem);
}
}
}
else
{
throw new ArgumentException(
"CollectionOrder is invalid.");
}
Assert.Equal(count, iterations);
if (validateEnd)
{
for (var i = 0; i < 3; i++)
{
Assert.False(
enumerator.MoveNext(),
"enumerator.MoveNext() returned true past the expected end.");
}
if (IsGenericCompatibility)
{
return;
}
// apparently it is okay if enumerator.Current doesn't throw when the collection is generic.
for (var i = 0; i < 3; i++)
{
Assert.Throws<InvalidOperationException>(
() => enumerator.Current);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
//
// This class implements the Julian calendar. In 48 B.C. Julius Caesar ordered a calendar reform, and this calendar
// is called Julian calendar. It consisted of a solar year of twelve months and of 365 days with an extra day
// every fourth year.
//*
//* Calendar support range:
//* Calendar Minimum Maximum
//* ========== ========== ==========
//* Gregorian 0001/01/01 9999/12/31
//* Julia 0001/01/03 9999/10/19
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class JulianCalendar : Calendar
{
public static readonly int JulianEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
// Number of days in a non-leap year
private const int JulianDaysPerYear = 365;
// Number of days in 4 years
private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
//internal static Calendar m_defaultInstance;
private static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
private static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
// Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19
// keep it as variable field for serialization compat.
internal int MaxYear = 9999;
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
// Return the type of the Julian calendar.
//
//[System.Runtime.InteropServices.ComVisible(false)]
//public override CalendarAlgorithmType AlgorithmType
//{
// get
// {
// return CalendarAlgorithmType.SolarCalendar;
// }
//}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of JulianCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance() {
if (m_defaultInstance == null) {
m_defaultInstance = new JulianCalendar();
}
return (m_defaultInstance);
}
*/
// Construct an instance of gregorian calendar.
public JulianCalendar()
{
// There is no system setting of TwoDigitYear max, so set the value here.
twoDigitYearMax = 2029;
}
internal override CalendarId ID
{
get
{
return CalendarId.JULIAN;
}
}
static internal void CheckEraRange(int era)
{
if (era != CurrentEra && era != JulianEra)
{
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal void CheckYearEraRange(int year, int era)
{
CheckEraRange(era);
if (year <= 0 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
}
static internal void CheckMonthRange(int month)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
}
/*=================================GetDefaultInstance==========================
**Action: Check for if the day value is valid.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make
** sure year/month values are correct.
============================================================================*/
static internal void CheckDayRange(int year, int month, int day)
{
if (year == 1 && month == 1)
{
// The mimimum supported Julia date is Julian 0001/01/03.
if (day < 3)
{
throw new ArgumentOutOfRangeException(null,
SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
bool isLeapYear = (year % 4) == 0;
int[] days = isLeapYear ? DaysToMonth366 : DaysToMonth365;
int monthDays = days[month] - days[month - 1];
if (day < 1 || day > monthDays)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
monthDays));
}
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
static internal int GetDatePart(long ticks, int part)
{
// Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001.
// The following line convert Gregorian ticks to Julian ticks.
long julianTicks = ticks + TicksPerDay * 2;
// n = number of days since 1/1/0001
int n = (int)(julianTicks / TicksPerDay);
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / JulianDaysPer4Years;
// n = day number within 4-year period
n -= y4 * JulianDaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / JulianDaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * JulianDaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3);
int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = n >> 5 + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
// Returns the tick count corresponding to the given year, month, and day.
static internal long DateToTicks(int year, int month, int day)
{
int[] days = (year % 4 == 0) ? DaysToMonth366 : DaysToMonth365;
int y = year - 1;
int n = y * 365 + y / 4 + days[month - 1] + day - 1;
// Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar.
// Therefore, we subtract two days in the following to convert the ticks in JulianCalendar
// to ticks in Gregorian calendar.
return ((n - 2) * TicksPerDay);
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
int[] days = (year % 4 == 0) ? DaysToMonth366 : DaysToMonth365;
return (days[month] - days[month - 1]);
}
public override int GetDaysInYear(int year, int era)
{
// Year/Era range is done in IsLeapYear().
return (IsLeapYear(year, era) ? 366 : 365);
}
public override int GetEra(DateTime time)
{
return (JulianEra);
}
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
public override int[] Eras
{
get
{
return (new int[] { JulianEra });
}
}
public override int GetMonthsInYear(int year, int era)
{
CheckYearEraRange(year, era);
return (12);
}
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
CheckMonthRange(month);
// Year/Era range check is done in IsLeapYear().
if (IsLeapYear(year, era))
{
CheckDayRange(year, month, day);
return (month == 2 && day == 29);
}
CheckDayRange(year, month, day);
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
CheckYearEraRange(year, era);
return (0);
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearEraRange(year, era);
return (year % 4 == 0);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
CheckDayRange(year, month, day);
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
"millisecond",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
MillisPerSecond - 1));
}
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks);
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
}
public override int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
1,
MaxYear));
}
return (base.ToFourDigitYear(year));
}
}
}
| |
// 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;
namespace System.Linq.Parallel.Tests
{
internal class FailingEqualityComparer<T> : IEqualityComparer<T>
{
public bool Equals(T x, T y)
{
throw new DeliberateTestException();
}
public int GetHashCode(T obj)
{
throw new DeliberateTestException();
}
}
internal class ModularCongruenceComparer : IEqualityComparer<int>, IComparer<int>
{
private int _mod;
public ModularCongruenceComparer(int mod)
{
_mod = Math.Max(1, mod);
}
private int leastPositiveResidue(int x)
{
return ((x % _mod) + _mod) % _mod;
}
public bool Equals(int x, int y)
{
return leastPositiveResidue(x) == leastPositiveResidue(y);
}
public int GetHashCode(int x)
{
return leastPositiveResidue(x).GetHashCode();
}
public int GetHashCode(object obj)
{
return GetHashCode((int)obj);
}
public int Compare(int x, int y)
{
return leastPositiveResidue(x).CompareTo(leastPositiveResidue(y));
}
}
internal sealed class CancelingEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Action _canceler;
public CancelingEqualityComparer(Action canceler)
{
_canceler = canceler;
}
public bool Equals(T x, T y)
{
_canceler();
return EqualityComparer<T>.Default.Equals(x, y);
}
public int GetHashCode(T obj)
{
_canceler();
return obj.GetHashCode();
}
}
internal class ReverseComparer : IComparer<int>
{
public static readonly ReverseComparer Instance = new ReverseComparer();
public int Compare(int x, int y)
{
return y.CompareTo(x);
}
}
internal class FailingComparer : IComparer<int>
{
public int Compare(int x, int y)
{
throw new DeliberateTestException();
}
}
/// <summary>
/// Returns an extreme value from non-equal comparisons.
/// </summary>
/// <remarks>Helper for regression test against PLINQ's version of #2239 .</remarks>
/// <typeparam name="T">The type being compared.</typeparam>
internal class ExtremeComparer<T> : IComparer<T>
{
private IComparer<T> _def = Comparer<T>.Default;
public int Compare(T x, T y)
{
int direction = _def.Compare(x, y);
return direction == 0 ? 0 :
direction > 0 ? int.MaxValue :
int.MinValue;
}
}
internal sealed class CancelingComparer : IComparer<int>
{
private readonly Action _canceler;
public CancelingComparer(Action canceler)
{
_canceler = canceler;
}
public int Compare(int x, int y)
{
_canceler();
return Comparer<int>.Default.Compare(x, y);
}
}
internal static class DelgatedComparable
{
public static DelegatedComparable<T> Delegate<T>(T value, IComparer<T> comparer) where T : IComparable<T>
{
return new DelegatedComparable<T>(value, comparer);
}
}
internal class DelegatedComparable<T> : IComparable<DelegatedComparable<T>> where T : IComparable<T>
{
private T _value;
private IComparer<T> _comparer;
public T Value
{
get
{
return _value;
}
}
public DelegatedComparable(T value, IComparer<T> comparer)
{
_value = value;
_comparer = comparer;
}
public int CompareTo(DelegatedComparable<T> other)
{
return _comparer.Compare(Value, other.Value);
}
}
/// <summary>
/// All funcs to be used as comparers by wrapping and delegating.
/// </summary>
internal static class DelegatingComparer
{
public static IComparer<T> Create<T>(Func<T, T, int> comparer)
{
return new DelegatingOrderingComparer<T>(comparer);
}
public static IEqualityComparer<T> Create<T>(Func<T, T, bool> comparer, Func<T, int> hashcode)
{
return new DelegatingEqualityComparer<T>(comparer, hashcode);
}
private class DelegatingOrderingComparer<T> : IComparer<T>
{
private readonly Func<T, T, int> _comparer;
public DelegatingOrderingComparer(Func<T, T, int> comparer)
{
_comparer = comparer;
}
public int Compare(T left, T right)
{
return _comparer(left, right);
}
}
private class DelegatingEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _comparer;
private readonly Func<T, int> _hashcode;
public DelegatingEqualityComparer(Func<T, T, bool> comparer, Func<T, int> hashcode)
{
_comparer = comparer;
_hashcode = hashcode;
}
public bool Equals(T left, T right)
{
return _comparer(left, right);
}
public int GetHashCode(T item)
{
return _hashcode(item);
}
}
}
internal struct NotComparable
{
private readonly int _value;
public int Value
{
get
{
return _value;
}
}
public NotComparable(int x)
{
_value = x;
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComUtils.MasterSetup.DS
{
public class MST_EmployeeApprovalLevelDS
{
public MST_EmployeeApprovalLevelDS()
{
}
private const string THIS = "PCSComUtils.MasterSetup.DS.MST_EmployeeApprovalLevelDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to MST_EmployeeApprovalLevel
/// </Description>
/// <Inputs>
/// MST_EmployeeApprovalLevelVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
MST_EmployeeApprovalLevelVO objObject = (MST_EmployeeApprovalLevelVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO MST_EmployeeApprovalLevel("
+ MST_EmployeeApprovalLevelTable.EMPLOYEEAPPROVALLEVELID_FLD + ","
+ MST_EmployeeApprovalLevelTable.EMPLOYEEID_FLD + ","
+ MST_EmployeeApprovalLevelTable.APPROVALLEVELID_FLD + ")"
+ "VALUES(?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeApprovalLevelTable.EMPLOYEEAPPROVALLEVELID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeApprovalLevelTable.EMPLOYEEAPPROVALLEVELID_FLD].Value = objObject.EmployeeApprovalLevelID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeApprovalLevelTable.EMPLOYEEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeApprovalLevelTable.EMPLOYEEID_FLD].Value = objObject.EmployeeID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeApprovalLevelTable.APPROVALLEVELID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeApprovalLevelTable.APPROVALLEVELID_FLD].Value = objObject.ApprovalLevelID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from MST_EmployeeApprovalLevel
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + MST_EmployeeApprovalLevelTable.TABLE_NAME + " WHERE " + "Description" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from MST_EmployeeApprovalLevel
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// MST_EmployeeApprovalLevelVO
/// </Outputs>
/// <Returns>
/// MST_EmployeeApprovalLevelVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_EmployeeApprovalLevelTable.DESCRIPTION_FLD + ","
+ MST_EmployeeApprovalLevelTable.EMPLOYEEAPPROVALLEVELID_FLD + ","
+ MST_EmployeeApprovalLevelTable.EMPLOYEEID_FLD + ","
+ MST_EmployeeApprovalLevelTable.APPROVALLEVELID_FLD
+ " FROM " + MST_EmployeeApprovalLevelTable.TABLE_NAME
+" WHERE " + MST_EmployeeApprovalLevelTable.DESCRIPTION_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
MST_EmployeeApprovalLevelVO objObject = new MST_EmployeeApprovalLevelVO();
while (odrPCS.Read())
{
objObject.Description = odrPCS[MST_EmployeeApprovalLevelTable.DESCRIPTION_FLD].ToString().Trim();
objObject.EmployeeApprovalLevelID = int.Parse(odrPCS[MST_EmployeeApprovalLevelTable.EMPLOYEEAPPROVALLEVELID_FLD].ToString().Trim());
objObject.EmployeeID = int.Parse(odrPCS[MST_EmployeeApprovalLevelTable.EMPLOYEEID_FLD].ToString().Trim());
objObject.ApprovalLevelID = int.Parse(odrPCS[MST_EmployeeApprovalLevelTable.APPROVALLEVELID_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to MST_EmployeeApprovalLevel
/// </Description>
/// <Inputs>
/// MST_EmployeeApprovalLevelVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
MST_EmployeeApprovalLevelVO objObject = (MST_EmployeeApprovalLevelVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE MST_EmployeeApprovalLevel SET "
+ MST_EmployeeApprovalLevelTable.EMPLOYEEAPPROVALLEVELID_FLD + "= ?" + ","
+ MST_EmployeeApprovalLevelTable.EMPLOYEEID_FLD + "= ?" + ","
+ MST_EmployeeApprovalLevelTable.APPROVALLEVELID_FLD + "= ?"
+" WHERE " + MST_EmployeeApprovalLevelTable.DESCRIPTION_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeApprovalLevelTable.EMPLOYEEAPPROVALLEVELID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeApprovalLevelTable.EMPLOYEEAPPROVALLEVELID_FLD].Value = objObject.EmployeeApprovalLevelID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeApprovalLevelTable.EMPLOYEEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeApprovalLevelTable.EMPLOYEEID_FLD].Value = objObject.EmployeeID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeApprovalLevelTable.APPROVALLEVELID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeApprovalLevelTable.APPROVALLEVELID_FLD].Value = objObject.ApprovalLevelID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeApprovalLevelTable.DESCRIPTION_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_EmployeeApprovalLevelTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from MST_EmployeeApprovalLevel
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_EmployeeApprovalLevelTable.DESCRIPTION_FLD + ","
+ MST_EmployeeApprovalLevelTable.EMPLOYEEAPPROVALLEVELID_FLD + ","
+ MST_EmployeeApprovalLevelTable.EMPLOYEEID_FLD + ","
+ MST_EmployeeApprovalLevelTable.APPROVALLEVELID_FLD
+ " FROM " + MST_EmployeeApprovalLevelTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,MST_EmployeeApprovalLevelTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ MST_EmployeeApprovalLevelTable.DESCRIPTION_FLD + ","
+ MST_EmployeeApprovalLevelTable.EMPLOYEEAPPROVALLEVELID_FLD + ","
+ MST_EmployeeApprovalLevelTable.EMPLOYEEID_FLD + ","
+ MST_EmployeeApprovalLevelTable.APPROVALLEVELID_FLD
+ " FROM " + MST_EmployeeApprovalLevelTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,MST_EmployeeApprovalLevelTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
#region License
//
// CompositeArray.cs July 2006
//
// Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
#endregion
#region Using directives
using SimpleFramework.Xml.Strategy;
using SimpleFramework.Xml.Stream;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
/// <summary>
/// The <c>CompositeArray</c> object is used to convert a list of
/// elements to an array of object entries. This in effect performs a
/// root serialization and deserialization of entry elements for the
/// array object. On serialization each objects type must be checked
/// against the array component type so that it is serialized in a form
/// that can be deserialized dynamically.
/// </code>
/// <array length="2">
/// <entry>
/// <text>example text value</text>
/// </entry>
/// <entry>
/// <text>some other example</text>
/// </entry>
/// </array>
/// </code>
/// For the above XML element list the element <c>entry</c> is
/// contained within the array. Each entry element is deserialized as
/// a root element and then inserted into the array. For serialization
/// the reverse is done, each element taken from the array is written
/// as a root element to the parent element to create the list. Entry
/// objects do not need to be of the same type.
/// </summary>
/// <seealso>
/// SimpleFramework.Xml.Core.Traverser
/// </seealso>
/// <seealso>
/// SimpleFramework.Xml.ElementArray
/// </seealso>
class CompositeArray : Converter {
/// <summary>
/// This factory is used to create an array for the contact.
/// </summary>
private readonly ArrayFactory factory;
/// <summary>
/// This performs the traversal used for object serialization.
/// </summary>
private readonly Traverser root;
/// <summary>
/// This is the name to wrap each entry that is represented.
/// </summary>
private readonly String parent;
/// <summary>
/// This is the entry type for elements within the array.
/// </summary>
private readonly Type entry;
/// <summary>
/// Constructor for the <c>CompositeArray</c> object. This is
/// given the array type for the contact that is to be converted. An
/// array of the specified type is used to hold the deserialized
/// elements and will be the same length as the number of elements.
/// </summary>
/// <param name="context">
/// this is the context object used for serialization
/// </param>
/// <param name="type">
/// this is the field type for the array being used
/// </param>
/// <param name="entry">
/// this is the entry type for the array elements
/// </param>
/// <param name="parent">
/// this is the name to wrap the array element with
/// </param>
public CompositeArray(Context context, Type type, Type entry, String parent) {
this.factory = new ArrayFactory(context, type);
this.root = new Traverser(context);
this.parent = parent;
this.entry = entry;
}
/// <summary>
/// This <c>read</c> method will read the XML element list from
/// the provided node and deserialize its children as entry types.
/// This ensures each entry type is deserialized as a root type, that
/// is, its <c>Root</c> annotation must be present and the
/// name of the entry element must match that root element name.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be deserialized
/// </param>
/// <returns>
/// this returns the item to attach to the object contact
/// </returns>
public Object Read(InputNode node) {
Instance type = factory.GetInstance(node);
Object list = type.Instance;
if(!type.isReference()) {
return Read(node, list);
}
return list;
}
/// <summary>
/// This <c>read</c> method will read the XML element list from
/// the provided node and deserialize its children as entry types.
/// This ensures each entry type is deserialized as a root type, that
/// is, its <c>Root</c> annotation must be present and the
/// name of the entry element must match that root element name.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be deserialized
/// </param>
/// <param name="list">
/// this is the array that is to be deserialized
/// </param>
/// <returns>
/// this returns the item to attach to the object contact
/// </returns>
public Object Read(InputNode node, Object list) {
int length = Array.getLength(list);
for(int pos = 0; true; pos++) {
Position line = node.getPosition();
InputNode next = node.getNext();
if(next == null) {
return list;
}
if(pos >= length){
throw new ElementException("Array length missing or incorrect at %s", line);
}
Read(next, list, pos);
}
}
/// <summary>
/// This is used to read the specified node from in to the list. If
/// the node is null then this represents a null element value in
/// the array. The node can be null only if there is a parent and
/// that parent contains no child XML elements.
/// </summary>
/// <param name="node">
/// this is the node to read the array value from
/// </param>
/// <param name="list">
/// this is the list to add the array value in to
/// </param>
/// <param name="index">
/// this is the offset to set the value in the array
/// </param>
public void Read(InputNode node, Object list, int index) {
Class type = entry.Type;
Object value = null;
if(!node.isEmpty()) {
value = root.Read(node, type);
}
Array.set(list, index, value);
}
/// <summary>
/// This <c>validate</c> method will validate the XML element
/// list against the provided node and validate its children as entry
/// types. This ensures each entry type is validated as a root type,
/// that is, its <c>Root</c> annotation must be present and the
/// name of the entry element must match that root element name.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be validated
/// </param>
/// <returns>
/// true if the element matches the XML schema class given
/// </returns>
public bool Validate(InputNode node) {
Instance value = factory.GetInstance(node);
if(!value.isReference()) {
Object result = value.setInstance(null);
Class type = value.Type;
return Validate(node, type);
}
return true;
}
/// <summary>
/// This <c>validate</c> method wll validate the XML element
/// list against the provided node and validate its children as entry
/// types. This ensures each entry type is validated as a root type,
/// that is, its <c>Root</c> annotation must be present and the
/// name of the entry element must match that root element name.
/// </summary>
/// <param name="node">
/// this is the XML element that is to be validated
/// </param>
/// <param name="type">
/// this is the array type used to create the array
/// </param>
/// <returns>
/// true if the element matches the XML schema class given
/// </returns>
public bool Validate(InputNode node, Class type) {
for(int i = 0; true; i++) {
InputNode next = node.getNext();
if(next == null) {
return true;
}
if(!next.isEmpty()) {
root.Validate(next, type);
}
}
}
/// <summary>
/// This <c>write</c> method will write the specified object
/// to the given XML element as as array entries. Each entry within
/// the given array must be assignable to the array component type.
/// Each array entry is serialized as a root element, that is, its
/// <c>Root</c> annotation is used to extract the name.
/// </summary>
/// <param name="source">
/// this is the source object array to be serialized
/// </param>
/// <param name="node">
/// this is the XML element container to be populated
/// </param>
public void Write(OutputNode node, Object source) {
int size = Array.getLength(source);
for(int i = 0; i < size; i++) {
Object item = Array.get(source, i);
Class type = entry.Type;
root.Write(node, item, type, parent);
}
node.commit();
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// TaxProvidersResponse
/// </summary>
[DataContract]
public partial class TaxProvidersResponse : IEquatable<TaxProvidersResponse>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="TaxProvidersResponse" /> class.
/// </summary>
/// <param name="avalara">avalara.</param>
/// <param name="error">error.</param>
/// <param name="metadata">metadata.</param>
/// <param name="self">self.</param>
/// <param name="sovos">sovos.</param>
/// <param name="success">Indicates if API call was successful.</param>
/// <param name="taxjar">taxjar.</param>
/// <param name="ultracart">ultracart.</param>
/// <param name="warning">warning.</param>
public TaxProvidersResponse(TaxProviderAvalara avalara = default(TaxProviderAvalara), Error error = default(Error), ResponseMetadata metadata = default(ResponseMetadata), TaxProviderSelf self = default(TaxProviderSelf), TaxProviderSovos sovos = default(TaxProviderSovos), bool? success = default(bool?), TaxProviderTaxJar taxjar = default(TaxProviderTaxJar), TaxProviderUltraCart ultracart = default(TaxProviderUltraCart), Warning warning = default(Warning))
{
this.Avalara = avalara;
this.Error = error;
this.Metadata = metadata;
this.Self = self;
this.Sovos = sovos;
this.Success = success;
this.Taxjar = taxjar;
this.Ultracart = ultracart;
this.Warning = warning;
}
/// <summary>
/// Gets or Sets Avalara
/// </summary>
[DataMember(Name="avalara", EmitDefaultValue=false)]
public TaxProviderAvalara Avalara { get; set; }
/// <summary>
/// Gets or Sets Error
/// </summary>
[DataMember(Name="error", EmitDefaultValue=false)]
public Error Error { get; set; }
/// <summary>
/// Gets or Sets Metadata
/// </summary>
[DataMember(Name="metadata", EmitDefaultValue=false)]
public ResponseMetadata Metadata { get; set; }
/// <summary>
/// Gets or Sets Self
/// </summary>
[DataMember(Name="self", EmitDefaultValue=false)]
public TaxProviderSelf Self { get; set; }
/// <summary>
/// Gets or Sets Sovos
/// </summary>
[DataMember(Name="sovos", EmitDefaultValue=false)]
public TaxProviderSovos Sovos { get; set; }
/// <summary>
/// Indicates if API call was successful
/// </summary>
/// <value>Indicates if API call was successful</value>
[DataMember(Name="success", EmitDefaultValue=false)]
public bool? Success { get; set; }
/// <summary>
/// Gets or Sets Taxjar
/// </summary>
[DataMember(Name="taxjar", EmitDefaultValue=false)]
public TaxProviderTaxJar Taxjar { get; set; }
/// <summary>
/// Gets or Sets Ultracart
/// </summary>
[DataMember(Name="ultracart", EmitDefaultValue=false)]
public TaxProviderUltraCart Ultracart { get; set; }
/// <summary>
/// Gets or Sets Warning
/// </summary>
[DataMember(Name="warning", EmitDefaultValue=false)]
public Warning Warning { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class TaxProvidersResponse {\n");
sb.Append(" Avalara: ").Append(Avalara).Append("\n");
sb.Append(" Error: ").Append(Error).Append("\n");
sb.Append(" Metadata: ").Append(Metadata).Append("\n");
sb.Append(" Self: ").Append(Self).Append("\n");
sb.Append(" Sovos: ").Append(Sovos).Append("\n");
sb.Append(" Success: ").Append(Success).Append("\n");
sb.Append(" Taxjar: ").Append(Taxjar).Append("\n");
sb.Append(" Ultracart: ").Append(Ultracart).Append("\n");
sb.Append(" Warning: ").Append(Warning).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as TaxProvidersResponse);
}
/// <summary>
/// Returns true if TaxProvidersResponse instances are equal
/// </summary>
/// <param name="input">Instance of TaxProvidersResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TaxProvidersResponse input)
{
if (input == null)
return false;
return
(
this.Avalara == input.Avalara ||
(this.Avalara != null &&
this.Avalara.Equals(input.Avalara))
) &&
(
this.Error == input.Error ||
(this.Error != null &&
this.Error.Equals(input.Error))
) &&
(
this.Metadata == input.Metadata ||
(this.Metadata != null &&
this.Metadata.Equals(input.Metadata))
) &&
(
this.Self == input.Self ||
(this.Self != null &&
this.Self.Equals(input.Self))
) &&
(
this.Sovos == input.Sovos ||
(this.Sovos != null &&
this.Sovos.Equals(input.Sovos))
) &&
(
this.Success == input.Success ||
(this.Success != null &&
this.Success.Equals(input.Success))
) &&
(
this.Taxjar == input.Taxjar ||
(this.Taxjar != null &&
this.Taxjar.Equals(input.Taxjar))
) &&
(
this.Ultracart == input.Ultracart ||
(this.Ultracart != null &&
this.Ultracart.Equals(input.Ultracart))
) &&
(
this.Warning == input.Warning ||
(this.Warning != null &&
this.Warning.Equals(input.Warning))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Avalara != null)
hashCode = hashCode * 59 + this.Avalara.GetHashCode();
if (this.Error != null)
hashCode = hashCode * 59 + this.Error.GetHashCode();
if (this.Metadata != null)
hashCode = hashCode * 59 + this.Metadata.GetHashCode();
if (this.Self != null)
hashCode = hashCode * 59 + this.Self.GetHashCode();
if (this.Sovos != null)
hashCode = hashCode * 59 + this.Sovos.GetHashCode();
if (this.Success != null)
hashCode = hashCode * 59 + this.Success.GetHashCode();
if (this.Taxjar != null)
hashCode = hashCode * 59 + this.Taxjar.GetHashCode();
if (this.Ultracart != null)
hashCode = hashCode * 59 + this.Ultracart.GetHashCode();
if (this.Warning != null)
hashCode = hashCode * 59 + this.Warning.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Globalization;
using Avalonia.Animation.Animators;
namespace Avalonia.Media
{
/// <summary>
/// An ARGB color.
/// </summary>
public readonly struct Color : IEquatable<Color>
{
static Color()
{
Animation.Animation.RegisterAnimator<ColorAnimator>(prop => typeof(Color).IsAssignableFrom(prop.PropertyType));
}
/// <summary>
/// Gets the Alpha component of the color.
/// </summary>
public byte A { get; }
/// <summary>
/// Gets the Red component of the color.
/// </summary>
public byte R { get; }
/// <summary>
/// Gets the Green component of the color.
/// </summary>
public byte G { get; }
/// <summary>
/// Gets the Blue component of the color.
/// </summary>
public byte B { get; }
public Color(byte a, byte r, byte g, byte b)
{
A = a;
R = r;
G = g;
B = b;
}
/// <summary>
/// Creates a <see cref="Color"/> from alpha, red, green and blue components.
/// </summary>
/// <param name="a">The alpha component.</param>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <returns>The color.</returns>
public static Color FromArgb(byte a, byte r, byte g, byte b)
{
return new Color(a, r, g, b);
}
/// <summary>
/// Creates a <see cref="Color"/> from red, green and blue components.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <returns>The color.</returns>
public static Color FromRgb(byte r, byte g, byte b)
{
return new Color(0xff, r, g, b);
}
/// <summary>
/// Creates a <see cref="Color"/> from an integer.
/// </summary>
/// <param name="value">The integer value.</param>
/// <returns>The color.</returns>
public static Color FromUInt32(uint value)
{
return new Color(
(byte)((value >> 24) & 0xff),
(byte)((value >> 16) & 0xff),
(byte)((value >> 8) & 0xff),
(byte)(value & 0xff)
);
}
/// <summary>
/// Parses a color string.
/// </summary>
/// <param name="s">The color string.</param>
/// <returns>The <see cref="Color"/>.</returns>
public static Color Parse(string s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
if (TryParse(s, out Color color))
{
return color;
}
throw new FormatException($"Invalid color string: '{s}'.");
}
/// <summary>
/// Parses a color string.
/// </summary>
/// <param name="s">The color string.</param>
/// <returns>The <see cref="Color"/>.</returns>
public static Color Parse(ReadOnlySpan<char> s)
{
if (TryParse(s, out Color color))
{
return color;
}
throw new FormatException($"Invalid color string: '{s.ToString()}'.");
}
/// <summary>
/// Parses a color string.
/// </summary>
/// <param name="s">The color string.</param>
/// <param name="color">The parsed color</param>
/// <returns>The status of the operation.</returns>
public static bool TryParse(string s, out Color color)
{
color = default;
if (s is null)
{
return false;
}
if (s.Length == 0)
{
return false;
}
if (s[0] == '#' && TryParseInternal(s.AsSpan(), out color))
{
return true;
}
var knownColor = KnownColors.GetKnownColor(s);
if (knownColor != KnownColor.None)
{
color = knownColor.ToColor();
return true;
}
return false;
}
/// <summary>
/// Parses a color string.
/// </summary>
/// <param name="s">The color string.</param>
/// <param name="color">The parsed color</param>
/// <returns>The status of the operation.</returns>
public static bool TryParse(ReadOnlySpan<char> s, out Color color)
{
if (s.Length == 0)
{
color = default;
return false;
}
if (s[0] == '#')
{
return TryParseInternal(s, out color);
}
var knownColor = KnownColors.GetKnownColor(s.ToString());
if (knownColor != KnownColor.None)
{
color = knownColor.ToColor();
return true;
}
color = default;
return false;
}
private static bool TryParseInternal(ReadOnlySpan<char> s, out Color color)
{
static bool TryParseCore(ReadOnlySpan<char> input, ref Color color)
{
var alphaComponent = 0u;
if (input.Length == 6)
{
alphaComponent = 0xff000000;
}
else if (input.Length != 8)
{
return false;
}
// TODO: (netstandard 2.1) Can use allocation free parsing.
if (!uint.TryParse(input.ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out var parsed))
{
return false;
}
color = FromUInt32(parsed | alphaComponent);
return true;
}
color = default;
ReadOnlySpan<char> input = s.Slice(1);
// Handle shorthand cases like #FFF (RGB) or #FFFF (ARGB).
if (input.Length == 3 || input.Length == 4)
{
var extendedLength = 2 * input.Length;
Span<char> extended = stackalloc char[extendedLength];
for (int i = 0; i < input.Length; i++)
{
extended[2 * i + 0] = input[i];
extended[2 * i + 1] = input[i];
}
return TryParseCore(extended, ref color);
}
return TryParseCore(input, ref color);
}
/// <summary>
/// Returns the string representation of the color.
/// </summary>
/// <returns>
/// The string representation of the color.
/// </returns>
public override string ToString()
{
uint rgb = ToUint32();
return KnownColors.GetKnownColorName(rgb) ?? $"#{rgb:x8}";
}
/// <summary>
/// Returns the integer representation of the color.
/// </summary>
/// <returns>
/// The integer representation of the color.
/// </returns>
public uint ToUint32()
{
return ((uint)A << 24) | ((uint)R << 16) | ((uint)G << 8) | (uint)B;
}
/// <summary>
/// Check if two colors are equal.
/// </summary>
public bool Equals(Color other)
{
return A == other.A && R == other.R && G == other.G && B == other.B;
}
public override bool Equals(object obj)
{
return obj is Color other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = A.GetHashCode();
hashCode = (hashCode * 397) ^ R.GetHashCode();
hashCode = (hashCode * 397) ^ G.GetHashCode();
hashCode = (hashCode * 397) ^ B.GetHashCode();
return hashCode;
}
}
public static bool operator ==(Color left, Color right)
{
return left.Equals(right);
}
public static bool operator !=(Color left, Color right)
{
return !left.Equals(right);
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type OnenoteNotebooksCollectionRequest.
/// </summary>
public partial class OnenoteNotebooksCollectionRequest : BaseRequest, IOnenoteNotebooksCollectionRequest
{
/// <summary>
/// Constructs a new OnenoteNotebooksCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public OnenoteNotebooksCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Notebook to the collection via POST.
/// </summary>
/// <param name="notebook">The Notebook to add.</param>
/// <returns>The created Notebook.</returns>
public System.Threading.Tasks.Task<Notebook> AddAsync(Notebook notebook)
{
return this.AddAsync(notebook, CancellationToken.None);
}
/// <summary>
/// Adds the specified Notebook to the collection via POST.
/// </summary>
/// <param name="notebook">The Notebook to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Notebook.</returns>
public System.Threading.Tasks.Task<Notebook> AddAsync(Notebook notebook, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<Notebook>(notebook, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IOnenoteNotebooksCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IOnenoteNotebooksCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<OnenoteNotebooksCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <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 IOnenoteNotebooksCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteNotebooksCollectionRequest Expand(Expression<Func<Notebook, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteNotebooksCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteNotebooksCollectionRequest Select(Expression<Func<Notebook, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteNotebooksCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteNotebooksCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteNotebooksCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteNotebooksCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface ISalesOrderDetailOriginalData : ISchemaBaseOriginalData
{
string CarrierTrackingNumber { get; }
int OrderQty { get; }
double UnitPrice { get; }
string UnitPriceDiscount { get; }
string LineTotal { get; }
string rowguid { get; }
SalesOrderHeader SalesOrderHeader { get; }
Product Product { get; }
SpecialOffer SpecialOffer { get; }
}
public partial class SalesOrderDetail : OGM<SalesOrderDetail, SalesOrderDetail.SalesOrderDetailData, System.String>, ISchemaBase, INeo4jBase, ISalesOrderDetailOriginalData
{
#region Initialize
static SalesOrderDetail()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, SalesOrderDetail> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.SalesOrderDetailAlias, IWhereQuery> query)
{
q.SalesOrderDetailAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.SalesOrderDetail.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"SalesOrderDetail => CarrierTrackingNumber : {this.CarrierTrackingNumber?.ToString() ?? "null"}, OrderQty : {this.OrderQty}, UnitPrice : {this.UnitPrice}, UnitPriceDiscount : {this.UnitPriceDiscount}, LineTotal : {this.LineTotal}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new SalesOrderDetailData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.OrderQty == null)
throw new PersistenceException(string.Format("Cannot save SalesOrderDetail with key '{0}' because the OrderQty cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.UnitPrice == null)
throw new PersistenceException(string.Format("Cannot save SalesOrderDetail with key '{0}' because the UnitPrice cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.UnitPriceDiscount == null)
throw new PersistenceException(string.Format("Cannot save SalesOrderDetail with key '{0}' because the UnitPriceDiscount cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.LineTotal == null)
throw new PersistenceException(string.Format("Cannot save SalesOrderDetail with key '{0}' because the LineTotal cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.rowguid == null)
throw new PersistenceException(string.Format("Cannot save SalesOrderDetail with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save SalesOrderDetail with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class SalesOrderDetailData : Data<System.String>
{
public SalesOrderDetailData()
{
}
public SalesOrderDetailData(SalesOrderDetailData data)
{
CarrierTrackingNumber = data.CarrierTrackingNumber;
OrderQty = data.OrderQty;
UnitPrice = data.UnitPrice;
UnitPriceDiscount = data.UnitPriceDiscount;
LineTotal = data.LineTotal;
rowguid = data.rowguid;
SalesOrderHeader = data.SalesOrderHeader;
Product = data.Product;
SpecialOffer = data.SpecialOffer;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "SalesOrderDetail";
SalesOrderHeader = new EntityCollection<SalesOrderHeader>(Wrapper, Members.SalesOrderHeader);
Product = new EntityCollection<Product>(Wrapper, Members.Product);
SpecialOffer = new EntityCollection<SpecialOffer>(Wrapper, Members.SpecialOffer);
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("CarrierTrackingNumber", CarrierTrackingNumber);
dictionary.Add("OrderQty", Conversion<int, long>.Convert(OrderQty));
dictionary.Add("UnitPrice", UnitPrice);
dictionary.Add("UnitPriceDiscount", UnitPriceDiscount);
dictionary.Add("LineTotal", LineTotal);
dictionary.Add("rowguid", rowguid);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("CarrierTrackingNumber", out value))
CarrierTrackingNumber = (string)value;
if (properties.TryGetValue("OrderQty", out value))
OrderQty = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("UnitPrice", out value))
UnitPrice = (double)value;
if (properties.TryGetValue("UnitPriceDiscount", out value))
UnitPriceDiscount = (string)value;
if (properties.TryGetValue("LineTotal", out value))
LineTotal = (string)value;
if (properties.TryGetValue("rowguid", out value))
rowguid = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface ISalesOrderDetail
public string CarrierTrackingNumber { get; set; }
public int OrderQty { get; set; }
public double UnitPrice { get; set; }
public string UnitPriceDiscount { get; set; }
public string LineTotal { get; set; }
public string rowguid { get; set; }
public EntityCollection<SalesOrderHeader> SalesOrderHeader { get; private set; }
public EntityCollection<Product> Product { get; private set; }
public EntityCollection<SpecialOffer> SpecialOffer { get; private set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface ISalesOrderDetail
public string CarrierTrackingNumber { get { LazyGet(); return InnerData.CarrierTrackingNumber; } set { if (LazySet(Members.CarrierTrackingNumber, InnerData.CarrierTrackingNumber, value)) InnerData.CarrierTrackingNumber = value; } }
public int OrderQty { get { LazyGet(); return InnerData.OrderQty; } set { if (LazySet(Members.OrderQty, InnerData.OrderQty, value)) InnerData.OrderQty = value; } }
public double UnitPrice { get { LazyGet(); return InnerData.UnitPrice; } set { if (LazySet(Members.UnitPrice, InnerData.UnitPrice, value)) InnerData.UnitPrice = value; } }
public string UnitPriceDiscount { get { LazyGet(); return InnerData.UnitPriceDiscount; } set { if (LazySet(Members.UnitPriceDiscount, InnerData.UnitPriceDiscount, value)) InnerData.UnitPriceDiscount = value; } }
public string LineTotal { get { LazyGet(); return InnerData.LineTotal; } set { if (LazySet(Members.LineTotal, InnerData.LineTotal, value)) InnerData.LineTotal = value; } }
public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } }
public SalesOrderHeader SalesOrderHeader
{
get { return ((ILookupHelper<SalesOrderHeader>)InnerData.SalesOrderHeader).GetItem(null); }
set
{
if (LazySet(Members.SalesOrderHeader, ((ILookupHelper<SalesOrderHeader>)InnerData.SalesOrderHeader).GetItem(null), value))
((ILookupHelper<SalesOrderHeader>)InnerData.SalesOrderHeader).SetItem(value, null);
}
}
public Product Product
{
get { return ((ILookupHelper<Product>)InnerData.Product).GetItem(null); }
set
{
if (LazySet(Members.Product, ((ILookupHelper<Product>)InnerData.Product).GetItem(null), value))
((ILookupHelper<Product>)InnerData.Product).SetItem(value, null);
}
}
public SpecialOffer SpecialOffer
{
get { return ((ILookupHelper<SpecialOffer>)InnerData.SpecialOffer).GetItem(null); }
set
{
if (LazySet(Members.SpecialOffer, ((ILookupHelper<SpecialOffer>)InnerData.SpecialOffer).GetItem(null), value))
((ILookupHelper<SpecialOffer>)InnerData.SpecialOffer).SetItem(value, null);
}
}
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static SalesOrderDetailMembers members = null;
public static SalesOrderDetailMembers Members
{
get
{
if (members == null)
{
lock (typeof(SalesOrderDetail))
{
if (members == null)
members = new SalesOrderDetailMembers();
}
}
return members;
}
}
public class SalesOrderDetailMembers
{
internal SalesOrderDetailMembers() { }
#region Members for interface ISalesOrderDetail
public Property CarrierTrackingNumber { get; } = Datastore.AdventureWorks.Model.Entities["SalesOrderDetail"].Properties["CarrierTrackingNumber"];
public Property OrderQty { get; } = Datastore.AdventureWorks.Model.Entities["SalesOrderDetail"].Properties["OrderQty"];
public Property UnitPrice { get; } = Datastore.AdventureWorks.Model.Entities["SalesOrderDetail"].Properties["UnitPrice"];
public Property UnitPriceDiscount { get; } = Datastore.AdventureWorks.Model.Entities["SalesOrderDetail"].Properties["UnitPriceDiscount"];
public Property LineTotal { get; } = Datastore.AdventureWorks.Model.Entities["SalesOrderDetail"].Properties["LineTotal"];
public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["SalesOrderDetail"].Properties["rowguid"];
public Property SalesOrderHeader { get; } = Datastore.AdventureWorks.Model.Entities["SalesOrderDetail"].Properties["SalesOrderHeader"];
public Property Product { get; } = Datastore.AdventureWorks.Model.Entities["SalesOrderDetail"].Properties["Product"];
public Property SpecialOffer { get; } = Datastore.AdventureWorks.Model.Entities["SalesOrderDetail"].Properties["SpecialOffer"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static SalesOrderDetailFullTextMembers fullTextMembers = null;
public static SalesOrderDetailFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(SalesOrderDetail))
{
if (fullTextMembers == null)
fullTextMembers = new SalesOrderDetailFullTextMembers();
}
}
return fullTextMembers;
}
}
public class SalesOrderDetailFullTextMembers
{
internal SalesOrderDetailFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(SalesOrderDetail))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["SalesOrderDetail"];
}
}
return entity;
}
private static SalesOrderDetailEvents events = null;
public static SalesOrderDetailEvents Events
{
get
{
if (events == null)
{
lock (typeof(SalesOrderDetail))
{
if (events == null)
events = new SalesOrderDetailEvents();
}
}
return events;
}
}
public class SalesOrderDetailEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<SalesOrderDetail, EntityEventArgs> onNew;
public event EventHandler<SalesOrderDetail, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<SalesOrderDetail, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<SalesOrderDetail, EntityEventArgs> onDelete;
public event EventHandler<SalesOrderDetail, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<SalesOrderDetail, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<SalesOrderDetail, EntityEventArgs> onSave;
public event EventHandler<SalesOrderDetail, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<SalesOrderDetail, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnCarrierTrackingNumber
private static bool onCarrierTrackingNumberIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onCarrierTrackingNumber;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> OnCarrierTrackingNumber
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onCarrierTrackingNumberIsRegistered)
{
Members.CarrierTrackingNumber.Events.OnChange -= onCarrierTrackingNumberProxy;
Members.CarrierTrackingNumber.Events.OnChange += onCarrierTrackingNumberProxy;
onCarrierTrackingNumberIsRegistered = true;
}
onCarrierTrackingNumber += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onCarrierTrackingNumber -= value;
if (onCarrierTrackingNumber == null && onCarrierTrackingNumberIsRegistered)
{
Members.CarrierTrackingNumber.Events.OnChange -= onCarrierTrackingNumberProxy;
onCarrierTrackingNumberIsRegistered = false;
}
}
}
}
private static void onCarrierTrackingNumberProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onCarrierTrackingNumber;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnOrderQty
private static bool onOrderQtyIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onOrderQty;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> OnOrderQty
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onOrderQtyIsRegistered)
{
Members.OrderQty.Events.OnChange -= onOrderQtyProxy;
Members.OrderQty.Events.OnChange += onOrderQtyProxy;
onOrderQtyIsRegistered = true;
}
onOrderQty += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onOrderQty -= value;
if (onOrderQty == null && onOrderQtyIsRegistered)
{
Members.OrderQty.Events.OnChange -= onOrderQtyProxy;
onOrderQtyIsRegistered = false;
}
}
}
}
private static void onOrderQtyProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onOrderQty;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnUnitPrice
private static bool onUnitPriceIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onUnitPrice;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> OnUnitPrice
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUnitPriceIsRegistered)
{
Members.UnitPrice.Events.OnChange -= onUnitPriceProxy;
Members.UnitPrice.Events.OnChange += onUnitPriceProxy;
onUnitPriceIsRegistered = true;
}
onUnitPrice += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUnitPrice -= value;
if (onUnitPrice == null && onUnitPriceIsRegistered)
{
Members.UnitPrice.Events.OnChange -= onUnitPriceProxy;
onUnitPriceIsRegistered = false;
}
}
}
}
private static void onUnitPriceProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onUnitPrice;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnUnitPriceDiscount
private static bool onUnitPriceDiscountIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onUnitPriceDiscount;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> OnUnitPriceDiscount
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUnitPriceDiscountIsRegistered)
{
Members.UnitPriceDiscount.Events.OnChange -= onUnitPriceDiscountProxy;
Members.UnitPriceDiscount.Events.OnChange += onUnitPriceDiscountProxy;
onUnitPriceDiscountIsRegistered = true;
}
onUnitPriceDiscount += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUnitPriceDiscount -= value;
if (onUnitPriceDiscount == null && onUnitPriceDiscountIsRegistered)
{
Members.UnitPriceDiscount.Events.OnChange -= onUnitPriceDiscountProxy;
onUnitPriceDiscountIsRegistered = false;
}
}
}
}
private static void onUnitPriceDiscountProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onUnitPriceDiscount;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnLineTotal
private static bool onLineTotalIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onLineTotal;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> OnLineTotal
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onLineTotalIsRegistered)
{
Members.LineTotal.Events.OnChange -= onLineTotalProxy;
Members.LineTotal.Events.OnChange += onLineTotalProxy;
onLineTotalIsRegistered = true;
}
onLineTotal += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onLineTotal -= value;
if (onLineTotal == null && onLineTotalIsRegistered)
{
Members.LineTotal.Events.OnChange -= onLineTotalProxy;
onLineTotalIsRegistered = false;
}
}
}
}
private static void onLineTotalProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onLineTotal;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region Onrowguid
private static bool onrowguidIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onrowguid;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> Onrowguid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
Members.rowguid.Events.OnChange += onrowguidProxy;
onrowguidIsRegistered = true;
}
onrowguid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onrowguid -= value;
if (onrowguid == null && onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
onrowguidIsRegistered = false;
}
}
}
}
private static void onrowguidProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onrowguid;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnSalesOrderHeader
private static bool onSalesOrderHeaderIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onSalesOrderHeader;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> OnSalesOrderHeader
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onSalesOrderHeaderIsRegistered)
{
Members.SalesOrderHeader.Events.OnChange -= onSalesOrderHeaderProxy;
Members.SalesOrderHeader.Events.OnChange += onSalesOrderHeaderProxy;
onSalesOrderHeaderIsRegistered = true;
}
onSalesOrderHeader += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onSalesOrderHeader -= value;
if (onSalesOrderHeader == null && onSalesOrderHeaderIsRegistered)
{
Members.SalesOrderHeader.Events.OnChange -= onSalesOrderHeaderProxy;
onSalesOrderHeaderIsRegistered = false;
}
}
}
}
private static void onSalesOrderHeaderProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onSalesOrderHeader;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnProduct
private static bool onProductIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onProduct;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> OnProduct
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onProductIsRegistered)
{
Members.Product.Events.OnChange -= onProductProxy;
Members.Product.Events.OnChange += onProductProxy;
onProductIsRegistered = true;
}
onProduct += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onProduct -= value;
if (onProduct == null && onProductIsRegistered)
{
Members.Product.Events.OnChange -= onProductProxy;
onProductIsRegistered = false;
}
}
}
}
private static void onProductProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onProduct;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnSpecialOffer
private static bool onSpecialOfferIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onSpecialOffer;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> OnSpecialOffer
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onSpecialOfferIsRegistered)
{
Members.SpecialOffer.Events.OnChange -= onSpecialOfferProxy;
Members.SpecialOffer.Events.OnChange += onSpecialOfferProxy;
onSpecialOfferIsRegistered = true;
}
onSpecialOffer += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onSpecialOffer -= value;
if (onSpecialOffer == null && onSpecialOfferIsRegistered)
{
Members.SpecialOffer.Events.OnChange -= onSpecialOfferProxy;
onSpecialOfferIsRegistered = false;
}
}
}
}
private static void onSpecialOfferProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onSpecialOffer;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onModifiedDate;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<SalesOrderDetail, PropertyEventArgs> onUid;
public static event EventHandler<SalesOrderDetail, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesOrderDetail, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((SalesOrderDetail)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region ISalesOrderDetailOriginalData
public ISalesOrderDetailOriginalData OriginalVersion { get { return this; } }
#region Members for interface ISalesOrderDetail
string ISalesOrderDetailOriginalData.CarrierTrackingNumber { get { return OriginalData.CarrierTrackingNumber; } }
int ISalesOrderDetailOriginalData.OrderQty { get { return OriginalData.OrderQty; } }
double ISalesOrderDetailOriginalData.UnitPrice { get { return OriginalData.UnitPrice; } }
string ISalesOrderDetailOriginalData.UnitPriceDiscount { get { return OriginalData.UnitPriceDiscount; } }
string ISalesOrderDetailOriginalData.LineTotal { get { return OriginalData.LineTotal; } }
string ISalesOrderDetailOriginalData.rowguid { get { return OriginalData.rowguid; } }
SalesOrderHeader ISalesOrderDetailOriginalData.SalesOrderHeader { get { return ((ILookupHelper<SalesOrderHeader>)OriginalData.SalesOrderHeader).GetOriginalItem(null); } }
Product ISalesOrderDetailOriginalData.Product { get { return ((ILookupHelper<Product>)OriginalData.Product).GetOriginalItem(null); } }
SpecialOffer ISalesOrderDetailOriginalData.SpecialOffer { get { return ((ILookupHelper<SpecialOffer>)OriginalData.SpecialOffer).GetOriginalItem(null); } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Static;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Tests.Process;
using NUnit.Framework;
/// <summary>
/// Test utility methods.
/// </summary>
public static class TestUtils
{
/** Indicates long running and/or memory/cpu intensive test. */
public const string CategoryIntensive = "LONG_TEST";
/** Indicates examples tests. */
public const string CategoryExamples = "EXAMPLES_TEST";
/** */
private const int DfltBusywaitSleepInterval = 200;
/** */
private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess
? new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms1g",
"-Xmx4g",
"-ea",
"-DIGNITE_QUIET=true",
"-Duser.timezone=UTC"
}
: new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms64m",
"-Xmx99m",
"-ea",
"-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000",
"-DIGNITE_QUIET=true"
};
/** */
private static readonly IList<string> JvmDebugOpts =
new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005" };
/** */
public static bool JvmDebug = true;
/** */
[ThreadStatic]
private static Random _random;
/** */
private static int _seed = Environment.TickCount;
/// <summary>
/// Kill Ignite processes.
/// </summary>
public static void KillProcesses()
{
IgniteProcess.KillAll();
}
/// <summary>
///
/// </summary>
public static Random Random
{
get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IList<string> TestJavaOptions(bool? jvmDebug = null)
{
IList<string> ops = new List<string>(TestJvmOpts);
if (jvmDebug ?? JvmDebug)
{
foreach (string opt in JvmDebugOpts)
ops.Add(opt);
}
return ops;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string CreateTestClasspath()
{
return Classpath.CreateClasspath(forceTestClasspath: true);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
public static void RunMultiThreaded(Action action, int threadNum)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
action();
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
/// <param name="duration">Duration of test execution in seconds</param>
public static void RunMultiThreaded(Action action, int threadNum, int duration)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
bool stop = false;
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
while (true)
{
Thread.MemoryBarrier();
// ReSharper disable once AccessToModifiedClosure
if (stop)
break;
action();
}
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
Thread.Sleep(duration * 1000);
stop = true;
Thread.MemoryBarrier();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
/// Wait for particular topology size.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="size">Size.</param>
/// <param name="timeout">Timeout.</param>
/// <returns>
/// <c>True</c> if topology took required size.
/// </returns>
public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000)
{
int left = timeout;
while (true)
{
if (grid.GetCluster().GetNodes().Count != size)
{
if (left > 0)
{
Thread.Sleep(100);
left -= 100;
}
else
break;
}
else
return true;
}
return false;
}
/// <summary>
/// Asserts that the handle registry is empty.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, 0, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, expectedCount, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="grid">The grid to check.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout)
{
var handleRegistry = ((Ignite)grid).HandleRegistry;
expectedCount++; // Skip default lifecycle bean
if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout))
return;
var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleHandlerHolder)).ToList();
if (items.Any())
Assert.Fail("HandleRegistry is not empty in grid '{0}' (expected {1}, actual {2}):\n '{3}'",
grid.Name, expectedCount, handleRegistry.Count,
items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y));
}
/// <summary>
/// Waits for condition, polling in busy wait loop.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <returns>True if condition predicate returned true within interval; false otherwise.</returns>
public static bool WaitForCondition(Func<bool> cond, int timeout)
{
if (timeout <= 0)
return cond();
var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval);
while (DateTime.Now < maxTime)
{
if (cond())
return true;
Thread.Sleep(DfltBusywaitSleepInterval);
}
return false;
}
/// <summary>
/// Gets the static discovery.
/// </summary>
public static TcpDiscoverySpi GetStaticDiscovery()
{
return new TcpDiscoverySpi
{
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] { "127.0.0.1:47500" }
},
SocketTimeout = TimeSpan.FromSeconds(0.3)
};
}
/// <summary>
/// Gets the default code-based test configuration.
/// </summary>
public static IgniteConfiguration GetTestConfiguration(bool? jvmDebug = null, string name = null)
{
return new IgniteConfiguration
{
DiscoverySpi = GetStaticDiscovery(),
Localhost = "127.0.0.1",
JvmOptions = TestJavaOptions(jvmDebug),
JvmClasspath = CreateTestClasspath(),
IgniteInstanceName = name,
DataStorageConfiguration = new DataStorageConfiguration
{
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
Name = DataStorageConfiguration.DefaultDataRegionName,
InitialSize = 128 * 1024 * 1024,
MaxSize = Environment.Is64BitProcess
? DataRegionConfiguration.DefaultMaxSize
: 256 * 1024 * 1024
}
}
};
}
/// <summary>
/// Runs the test in new process.
/// </summary>
[SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")]
public static void RunTestInNewProcess(string fixtureName, string testName)
{
var procStart = new ProcessStartInfo
{
FileName = typeof(TestUtils).Assembly.Location,
Arguments = fixtureName + " " + testName,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var proc = System.Diagnostics.Process.Start(procStart);
Assert.IsNotNull(proc);
try
{
IgniteProcess.AttachProcessConsoleReader(proc);
Assert.IsTrue(proc.WaitForExit(19000));
Assert.AreEqual(0, proc.ExitCode);
}
finally
{
if (!proc.HasExited)
{
proc.Kill();
}
}
}
/// <summary>
/// Serializes and deserializes back an object.
/// </summary>
public static T SerializeDeserialize<T>(T obj)
{
var marsh = new Marshaller(null) {CompactFooter = false};
return marsh.Unmarshal<T>(marsh.Marshal(obj));
}
/// <summary>
/// Gets the primary keys.
/// </summary>
public static IEnumerable<int> GetPrimaryKeys(IIgnite ignite, string cacheName,
IClusterNode node = null)
{
var aff = ignite.GetAffinity(cacheName);
node = node ?? ignite.GetCluster().GetLocalNode();
return Enumerable.Range(1, int.MaxValue).Where(x => aff.IsPrimary(node, x));
}
/// <summary>
/// Gets the primary key.
/// </summary>
public static int GetPrimaryKey(IIgnite ignite, string cacheName, IClusterNode node = null)
{
return GetPrimaryKeys(ignite, cacheName, node).First();
}
/// <summary>
/// Asserts equality with reflection.
/// </summary>
public static void AssertReflectionEqual(object x, object y, string propertyPath = null,
HashSet<string> ignoredProperties = null)
{
if (x == null && y == null)
{
return;
}
Assert.IsNotNull(x, propertyPath);
Assert.IsNotNull(y, propertyPath);
var type = x.GetType();
if (type != typeof(string) && typeof(IEnumerable).IsAssignableFrom(type))
{
var xCol = ((IEnumerable)x).OfType<object>().ToList();
var yCol = ((IEnumerable)y).OfType<object>().ToList();
Assert.AreEqual(xCol.Count, yCol.Count, propertyPath);
for (var i = 0; i < xCol.Count; i++)
{
AssertReflectionEqual(xCol[i], yCol[i], propertyPath, ignoredProperties);
}
return;
}
Assert.AreEqual(type, y.GetType());
propertyPath = propertyPath ?? type.Name;
if (type.IsValueType || type == typeof(string) || type.IsSubclassOf(typeof(Type)))
{
Assert.AreEqual(x, y, propertyPath);
return;
}
var props = type.GetProperties().Where(p => p.GetIndexParameters().Length == 0);
foreach (var propInfo in props)
{
if (ignoredProperties != null && ignoredProperties.Contains(propInfo.Name))
{
continue;
}
var propName = propertyPath + "." + propInfo.Name;
var xVal = propInfo.GetValue(x, null);
var yVal = propInfo.GetValue(y, null);
AssertReflectionEqual(xVal, yVal, propName, ignoredProperties);
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Threading;
using NUnit.Common;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Execution;
namespace NUnit.Framework.Api
{
/// <summary>
/// Implementation of ITestAssemblyRunner
/// </summary>
public class NUnitTestAssemblyRunner : ITestAssemblyRunner
{
private static Logger log = InternalTrace.GetLogger("DefaultTestAssemblyRunner");
private ITestAssemblyBuilder _builder;
private AutoResetEvent _runComplete = new AutoResetEvent(false);
#if !SILVERLIGHT && !NETCF && !PORTABLE
// Saved Console.Out and Console.Error
private TextWriter _savedOut;
private TextWriter _savedErr;
#endif
#if PARALLEL
// Event Pump
private EventPump _pump;
#endif
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="NUnitTestAssemblyRunner"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public NUnitTestAssemblyRunner(ITestAssemblyBuilder builder)
{
_builder = builder;
}
#endregion
#region Properties
/// <summary>
/// The tree of tests that was loaded by the builder
/// </summary>
public ITest LoadedTest { get; private set; }
/// <summary>
/// The test result, if a run has completed
/// </summary>
public ITestResult Result
{
get { return TopLevelWorkItem == null ? null : TopLevelWorkItem.Result; }
}
/// <summary>
/// Indicates whether a test is loaded
/// </summary>
public bool IsTestLoaded
{
get { return LoadedTest != null; }
}
/// <summary>
/// Indicates whether a test is running
/// </summary>
public bool IsTestRunning
{
get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Running; }
}
/// <summary>
/// Indicates whether a test run is complete
/// </summary>
public bool IsTestComplete
{
get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Complete; }
}
/// <summary>
/// Our settings, specified when loading the assembly
/// </summary>
private IDictionary Settings { get; set; }
/// <summary>
/// The top level WorkItem created for the assembly as a whole
/// </summary>
private WorkItem TopLevelWorkItem { get; set; }
/// <summary>
/// The TestExecutionContext for the top level WorkItem
/// </summary>
private TestExecutionContext Context { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Loads the tests found in an Assembly
/// </summary>
/// <param name="assemblyName">File name of the assembly to load</param>
/// <param name="settings">Dictionary of option settings for loading the assembly</param>
/// <returns>True if the load was successful</returns>
public ITest Load(string assemblyName, IDictionary settings)
{
Settings = settings;
Randomizer.InitialSeed = GetInitialSeed(settings);
return LoadedTest = _builder.Build(assemblyName, settings);
}
/// <summary>
/// Loads the tests found in an Assembly
/// </summary>
/// <param name="assembly">The assembly to load</param>
/// <param name="settings">Dictionary of option settings for loading the assembly</param>
/// <returns>True if the load was successful</returns>
public ITest Load(Assembly assembly, IDictionary settings)
{
Settings = settings;
Randomizer.InitialSeed = GetInitialSeed(settings);
return LoadedTest = _builder.Build(assembly, settings);
}
/// <summary>
/// Count Test Cases using a filter
/// </summary>
/// <param name="filter">The filter to apply</param>
/// <returns>The number of test cases found</returns>
public int CountTestCases(ITestFilter filter)
{
if (LoadedTest == null)
throw new InvalidOperationException("The CountTestCases method was called but no test has been loaded");
return CountTestCases(LoadedTest, filter);
}
/// <summary>
/// Run selected tests and return a test result. The test is run synchronously,
/// and the listener interface is notified as it progresses.
/// </summary>
/// <param name="listener">Interface to receive EventListener notifications.</param>
/// <param name="filter">A test filter used to select tests to be run</param>
/// <returns></returns>
public ITestResult Run(ITestListener listener, ITestFilter filter)
{
RunAsync(listener, filter);
WaitForCompletion(Timeout.Infinite);
return Result;
}
/// <summary>
/// Run selected tests asynchronously, notifying the listener interface as it progresses.
/// </summary>
/// <param name="listener">Interface to receive EventListener notifications.</param>
/// <param name="filter">A test filter used to select tests to be run</param>
/// <remarks>
/// RunAsync is a template method, calling various abstract and
/// virtual methods to be overridden by derived classes.
/// </remarks>
public void RunAsync(ITestListener listener, ITestFilter filter)
{
log.Info("Running tests");
if (LoadedTest == null)
throw new InvalidOperationException("The Run method was called but no test has been loaded");
CreateTestExecutionContext(listener);
TopLevelWorkItem = WorkItem.CreateWorkItem(LoadedTest, filter);
TopLevelWorkItem.InitializeContext(Context);
TopLevelWorkItem.Completed += OnRunCompleted;
StartRun(listener);
}
/// <summary>
/// Wait for the ongoing run to complete.
/// </summary>
/// <param name="timeout">Time to wait in milliseconds</param>
/// <returns>True if the run completed, otherwise false</returns>
public bool WaitForCompletion(int timeout)
{
#if !SILVERLIGHT && !PORTABLE
return _runComplete.WaitOne(timeout, false);
#else
return _runComplete.WaitOne(timeout);
#endif
}
/// <summary>
/// Initiate the test run.
/// </summary>
public void StartRun(ITestListener listener)
{
#if !SILVERLIGHT && !NETCF && !PORTABLE
// Save Console.Out and Error for later restoration
_savedOut = Console.Out;
_savedErr = Console.Error;
Console.SetOut(new TextCapture(Console.Out));
Console.SetError(new TextCapture(Console.Error));
#endif
#if PARALLEL
// Queue and pump events, unless settings have SynchronousEvents == false
if (!Settings.Contains(PackageSettings.SynchronousEvents) || !(bool)Settings[PackageSettings.SynchronousEvents])
{
QueuingEventListener queue = new QueuingEventListener();
Context.Listener = queue;
_pump = new EventPump(listener, queue.Events);
_pump.Start();
}
#endif
#if !NETCF
if (!System.Diagnostics.Debugger.IsAttached &&
Settings.Contains(PackageSettings.DebugTests) &&
(bool)Settings[PackageSettings.DebugTests])
{
System.Diagnostics.Debugger.Launch();
}
#endif
Context.Dispatcher.Dispatch(TopLevelWorkItem);
}
/// <summary>
/// Signal any test run that is in process to stop. Return without error if no test is running.
/// </summary>
/// <param name="force">If true, kill any test-running threads</param>
public void StopRun(bool force)
{
if (IsTestRunning)
{
Context.ExecutionStatus = force
? TestExecutionStatus.AbortRequested
: TestExecutionStatus.StopRequested;
if (force)
Context.Dispatcher.CancelRun();
}
}
#endregion
#region Helper Methods
/// <summary>
/// Create the initial TestExecutionContext used to run tests
/// </summary>
/// <param name="listener">The ITestListener specified in the RunAsync call</param>
private void CreateTestExecutionContext(ITestListener listener)
{
Context = new TestExecutionContext();
if (Settings.Contains(PackageSettings.DefaultTimeout))
Context.TestCaseTimeout = (int)Settings[PackageSettings.DefaultTimeout];
if (Settings.Contains(PackageSettings.StopOnError))
Context.StopOnError = (bool)Settings[PackageSettings.StopOnError];
if (Settings.Contains(PackageSettings.WorkDirectory))
Context.WorkDirectory = (string)Settings[PackageSettings.WorkDirectory];
else
Context.WorkDirectory = Env.DefaultWorkDirectory;
// Overriding runners may replace this
Context.Listener = listener;
#if PARALLEL
int levelOfParallelism = GetLevelOfParallelism();
if (levelOfParallelism > 0)
{
Context.Dispatcher = new ParallelWorkItemDispatcher(levelOfParallelism);
// Assembly does not have IApplyToContext attributes applied
// when the test is built, so we do it here.
// TODO: Generalize this
if (LoadedTest.Properties.ContainsKey(PropertyNames.ParallelScope))
Context.ParallelScope =
(ParallelScope)LoadedTest.Properties.Get(PropertyNames.ParallelScope) & ~ParallelScope.Self;
}
else
Context.Dispatcher = new SimpleWorkItemDispatcher();
#else
Context.Dispatcher = new SimpleWorkItemDispatcher();
#endif
}
/// <summary>
/// Handle the the Completed event for the top level work item
/// </summary>
private void OnRunCompleted(object sender, EventArgs e)
{
#if PARALLEL
if (_pump != null)
_pump.Dispose();
#endif
#if !SILVERLIGHT && !NETCF && !PORTABLE
Console.SetOut(_savedOut);
Console.SetError(_savedErr);
#endif
_runComplete.Set();
}
private int CountTestCases(ITest test, ITestFilter filter)
{
if (!test.IsSuite)
return 1;
int count = 0;
foreach (ITest child in test.Tests)
if (filter.Pass(child))
count += CountTestCases(child, filter);
return count;
}
private static int GetInitialSeed(IDictionary settings)
{
return settings.Contains(PackageSettings.RandomSeed)
? (int)settings[PackageSettings.RandomSeed]
: new Random().Next();
}
#if PARALLEL
private int GetLevelOfParallelism()
{
return Settings.Contains(PackageSettings.NumberOfTestWorkers)
? (int)Settings[PackageSettings.NumberOfTestWorkers]
: (LoadedTest.Properties.ContainsKey(PropertyNames.LevelOfParallelism)
? (int)LoadedTest.Properties.Get(PropertyNames.LevelOfParallelism)
#if NETCF
: 2);
#else
: Math.Max(Environment.ProcessorCount, 2));
#endif
}
#endif
#endregion
}
}
| |
using UnityEngine;
namespace Xft
{
public class Sprite
{
public Color Color;
protected bool ColorChanged = false;
protected float ElapsedTime;
protected float Fps;
protected Matrix4x4 LastMat;
private Matrix4x4 LocalMat;
protected Vector2 LowerLeftUV;
public Camera MainCamera;
public STransform MyTransform;
private ORIPOINT OriPoint;
protected Vector3 RotateAxis;
private Quaternion Rotation;
private Vector3 ScaleVector;
private Style Type;
protected bool UVChanged = false;
protected Vector2 UVDimensions;
private int UVStretch;
public Vector3 v1 = Vector3.zero;
public Vector3 v2 = Vector3.zero;
public Vector3 v3 = Vector3.zero;
public Vector3 v4 = Vector3.zero;
protected VertexPool.VertexSegment Vertexsegment;
private Matrix4x4 WorldMat;
public Sprite(VertexPool.VertexSegment segment, float width, float height, Style type, ORIPOINT oripoint, Camera cam, int uvStretch, float maxFps)
{
this.MyTransform.position = Vector3.zero;
this.MyTransform.rotation = Quaternion.identity;
this.LocalMat = this.WorldMat = Matrix4x4.identity;
this.Vertexsegment = segment;
this.UVStretch = uvStretch;
this.LastMat = Matrix4x4.identity;
this.ElapsedTime = 0f;
this.Fps = 1f / maxFps;
this.OriPoint = oripoint;
this.RotateAxis = Vector3.zero;
this.SetSizeXZ(width, height);
this.RotateAxis.y = 1f;
this.Type = type;
this.MainCamera = cam;
this.ResetSegment();
}
public void Init(Color color, Vector2 lowerLeftUV, Vector2 uvDimensions)
{
this.SetUVCoord(lowerLeftUV, uvDimensions);
this.SetColor(color);
this.SetRotation(Quaternion.identity);
this.SetScale(1f, 1f);
this.SetRotation(0f);
}
public void Reset()
{
this.MyTransform.Reset();
this.SetColor(Color.white);
this.SetUVCoord(Vector2.zero, Vector2.zero);
this.ScaleVector = Vector3.one;
this.Rotation = Quaternion.identity;
VertexPool pool = this.Vertexsegment.Pool;
int vertStart = this.Vertexsegment.VertStart;
pool.Vertices[vertStart] = Vector3.zero;
pool.Vertices[vertStart + 1] = Vector3.zero;
pool.Vertices[vertStart + 2] = Vector3.zero;
pool.Vertices[vertStart + 3] = Vector3.zero;
}
public void ResetSegment()
{
VertexPool pool = this.Vertexsegment.Pool;
int indexStart = this.Vertexsegment.IndexStart;
int vertStart = this.Vertexsegment.VertStart;
pool.Indices[indexStart] = vertStart;
pool.Indices[indexStart + 1] = vertStart + 3;
pool.Indices[indexStart + 2] = vertStart + 1;
pool.Indices[indexStart + 3] = vertStart + 3;
pool.Indices[indexStart + 4] = vertStart + 2;
pool.Indices[indexStart + 5] = vertStart + 1;
pool.Vertices[vertStart] = Vector3.zero;
pool.Vertices[vertStart + 1] = Vector3.zero;
pool.Vertices[vertStart + 2] = Vector3.zero;
pool.Vertices[vertStart + 3] = Vector3.zero;
pool.Colors[vertStart] = Color.white;
pool.Colors[vertStart + 1] = Color.white;
pool.Colors[vertStart + 2] = Color.white;
pool.Colors[vertStart + 3] = Color.white;
pool.UVs[vertStart] = Vector2.zero;
pool.UVs[vertStart + 1] = Vector2.zero;
pool.UVs[vertStart + 2] = Vector2.zero;
pool.UVs[vertStart + 3] = Vector2.zero;
pool.VertChanged = true;
pool.ColorChanged = true;
pool.IndiceChanged = true;
pool.UVChanged = true;
}
public void SetColor(Color c)
{
this.Color = c;
this.ColorChanged = true;
}
public void SetPosition(Vector3 pos)
{
this.MyTransform.position = pos;
}
public void SetRotation(float angle)
{
this.Rotation = Quaternion.AngleAxis(angle, this.RotateAxis);
}
public void SetRotation(Quaternion q)
{
this.MyTransform.rotation = q;
}
public void SetRotationFaceTo(Vector3 dir)
{
this.MyTransform.rotation = Quaternion.FromToRotation(Vector3.up, dir);
}
public void SetRotationTo(Vector3 dir)
{
if (dir != Vector3.zero)
{
Quaternion identity = Quaternion.identity;
Vector3 toDirection = dir;
toDirection.y = 0f;
if (toDirection == Vector3.zero)
{
toDirection = Vector3.up;
}
if (this.OriPoint == ORIPOINT.CENTER)
{
Quaternion quaternion2 = Quaternion.FromToRotation(new Vector3(0f, 0f, 1f), toDirection);
identity = Quaternion.FromToRotation(toDirection, dir) * quaternion2;
}
else if (this.OriPoint == ORIPOINT.LEFT_UP)
{
Quaternion quaternion4 = Quaternion.FromToRotation(this.LocalMat.MultiplyPoint3x4(this.v3), toDirection);
identity = Quaternion.FromToRotation(toDirection, dir) * quaternion4;
}
else if (this.OriPoint == ORIPOINT.LEFT_BOTTOM)
{
Quaternion quaternion6 = Quaternion.FromToRotation(this.LocalMat.MultiplyPoint3x4(this.v4), toDirection);
identity = Quaternion.FromToRotation(toDirection, dir) * quaternion6;
}
else if (this.OriPoint == ORIPOINT.RIGHT_BOTTOM)
{
Quaternion quaternion8 = Quaternion.FromToRotation(this.LocalMat.MultiplyPoint3x4(this.v1), toDirection);
identity = Quaternion.FromToRotation(toDirection, dir) * quaternion8;
}
else if (this.OriPoint == ORIPOINT.RIGHT_UP)
{
Quaternion quaternion10 = Quaternion.FromToRotation(this.LocalMat.MultiplyPoint3x4(this.v2), toDirection);
identity = Quaternion.FromToRotation(toDirection, dir) * quaternion10;
}
else if (this.OriPoint == ORIPOINT.BOTTOM_CENTER)
{
Quaternion quaternion12 = Quaternion.FromToRotation(new Vector3(0f, 0f, 1f), toDirection);
identity = Quaternion.FromToRotation(toDirection, dir) * quaternion12;
}
else if (this.OriPoint == ORIPOINT.TOP_CENTER)
{
Quaternion quaternion14 = Quaternion.FromToRotation(new Vector3(0f, 0f, -1f), toDirection);
identity = Quaternion.FromToRotation(toDirection, dir) * quaternion14;
}
else if (this.OriPoint == ORIPOINT.RIGHT_CENTER)
{
Quaternion quaternion16 = Quaternion.FromToRotation(new Vector3(-1f, 0f, 0f), toDirection);
identity = Quaternion.FromToRotation(toDirection, dir) * quaternion16;
}
else if (this.OriPoint == ORIPOINT.LEFT_CENTER)
{
Quaternion quaternion18 = Quaternion.FromToRotation(new Vector3(1f, 0f, 0f), toDirection);
identity = Quaternion.FromToRotation(toDirection, dir) * quaternion18;
}
this.MyTransform.rotation = identity;
}
}
public void SetScale(float width, float height)
{
this.ScaleVector.x = width;
this.ScaleVector.z = height;
}
public void SetSizeXZ(float width, float height)
{
this.v1 = new Vector3(-width / 2f, 0f, height / 2f);
this.v2 = new Vector3(-width / 2f, 0f, -height / 2f);
this.v3 = new Vector3(width / 2f, 0f, -height / 2f);
this.v4 = new Vector3(width / 2f, 0f, height / 2f);
Vector3 zero = Vector3.zero;
if (this.OriPoint == ORIPOINT.LEFT_UP)
{
zero = this.v3;
}
else if (this.OriPoint == ORIPOINT.LEFT_BOTTOM)
{
zero = this.v4;
}
else if (this.OriPoint == ORIPOINT.RIGHT_BOTTOM)
{
zero = this.v1;
}
else if (this.OriPoint == ORIPOINT.RIGHT_UP)
{
zero = this.v2;
}
else if (this.OriPoint == ORIPOINT.BOTTOM_CENTER)
{
zero = new Vector3(0f, 0f, height / 2f);
}
else if (this.OriPoint == ORIPOINT.TOP_CENTER)
{
zero = new Vector3(0f, 0f, -height / 2f);
}
else if (this.OriPoint == ORIPOINT.LEFT_CENTER)
{
zero = new Vector3(width / 2f, 0f, 0f);
}
else if (this.OriPoint == ORIPOINT.RIGHT_CENTER)
{
zero = new Vector3(-width / 2f, 0f, 0f);
}
this.v1 += zero;
this.v2 += zero;
this.v3 += zero;
this.v4 += zero;
}
public void SetUVCoord(Vector2 lowerleft, Vector2 dimensions)
{
this.LowerLeftUV = lowerleft;
this.UVDimensions = dimensions;
this.UVChanged = true;
}
public void Transform()
{
this.LocalMat.SetTRS(Vector3.zero, this.Rotation, this.ScaleVector);
if (this.Type == Style.Billboard)
{
Transform transform = this.MainCamera.transform;
this.MyTransform.LookAt(this.MyTransform.position + transform.rotation * Vector3.up, transform.rotation * Vector3.back);
}
this.WorldMat.SetTRS(this.MyTransform.position, this.MyTransform.rotation, Vector3.one);
Matrix4x4 matrixx = this.WorldMat * this.LocalMat;
VertexPool pool = this.Vertexsegment.Pool;
int vertStart = this.Vertexsegment.VertStart;
Vector3 vector = matrixx.MultiplyPoint3x4(this.v1);
Vector3 vector2 = matrixx.MultiplyPoint3x4(this.v2);
Vector3 vector3 = matrixx.MultiplyPoint3x4(this.v3);
Vector3 vector4 = matrixx.MultiplyPoint3x4(this.v4);
if (this.Type == Style.BillboardSelf)
{
Vector3 zero = Vector3.zero;
Vector3 vector6 = Vector3.zero;
float magnitude = 0f;
if (this.UVStretch == 0)
{
zero = (vector + vector4) / 2f;
vector6 = (vector2 + vector3) / 2f;
Vector3 vector7 = vector4 - vector;
magnitude = vector7.magnitude;
}
else
{
zero = (vector + vector2) / 2f;
vector6 = (vector4 + vector3) / 2f;
Vector3 vector8 = vector2 - vector;
magnitude = vector8.magnitude;
}
Vector3 lhs = zero - vector6;
Vector3 rhs = this.MainCamera.transform.position - zero;
Vector3 vector11 = Vector3.Cross(lhs, rhs);
vector11.Normalize();
vector11 = vector11 * (magnitude * 0.5f);
Vector3 vector12 = this.MainCamera.transform.position - vector6;
Vector3 vector13 = Vector3.Cross(lhs, vector12);
vector13.Normalize();
vector13 = vector13 * (magnitude * 0.5f);
if (this.UVStretch == 0)
{
vector = zero - vector11;
vector4 = zero + vector11;
vector2 = vector6 - vector13;
vector3 = vector6 + vector13;
}
else
{
vector = zero - vector11;
vector2 = zero + vector11;
vector4 = vector6 - vector13;
vector3 = vector6 + vector13;
}
}
pool.Vertices[vertStart] = vector;
pool.Vertices[vertStart + 1] = vector2;
pool.Vertices[vertStart + 2] = vector3;
pool.Vertices[vertStart + 3] = vector4;
}
public void Update(bool force)
{
this.ElapsedTime += Time.deltaTime;
if (this.ElapsedTime > this.Fps || force)
{
this.Transform();
if (this.UVChanged)
{
this.UpdateUV();
}
if (this.ColorChanged)
{
this.UpdateColor();
}
this.ColorChanged = false;
this.UVChanged = false;
if (!force)
{
this.ElapsedTime -= this.Fps;
}
}
}
public void UpdateColor()
{
VertexPool pool = this.Vertexsegment.Pool;
int vertStart = this.Vertexsegment.VertStart;
pool.Colors[vertStart] = this.Color;
pool.Colors[vertStart + 1] = this.Color;
pool.Colors[vertStart + 2] = this.Color;
pool.Colors[vertStart + 3] = this.Color;
this.Vertexsegment.Pool.ColorChanged = true;
}
public void UpdateUV()
{
VertexPool pool = this.Vertexsegment.Pool;
int vertStart = this.Vertexsegment.VertStart;
if (this.UVDimensions.y > 0f)
{
pool.UVs[vertStart] = this.LowerLeftUV + Vector2.up * this.UVDimensions.y;
pool.UVs[vertStart + 1] = this.LowerLeftUV;
pool.UVs[vertStart + 2] = this.LowerLeftUV + Vector2.right * this.UVDimensions.x;
pool.UVs[vertStart + 3] = this.LowerLeftUV + this.UVDimensions;
}
else
{
pool.UVs[vertStart] = this.LowerLeftUV;
pool.UVs[vertStart + 1] = this.LowerLeftUV + Vector2.up * this.UVDimensions.y;
pool.UVs[vertStart + 2] = this.LowerLeftUV + this.UVDimensions;
pool.UVs[vertStart + 3] = this.LowerLeftUV + Vector2.right * this.UVDimensions.x;
}
this.Vertexsegment.Pool.UVChanged = true;
}
}
}
| |
#region License
//
// Author: Nate Kohari <nkohari@gmail.com>
// Copyright (c) 2007-2008, Enkari, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
#region Using Directives
using System;
using System.IO;
using System.Reflection;
using System.Text;
using Ninject.Core.Activation;
using Ninject.Core.Binding;
#endregion
namespace Ninject.Core.Infrastructure
{
internal static class Format
{
/*----------------------------------------------------------------------------------------*/
public static string ActivationPath(IContext context)
{
Ensure.ArgumentNotNull(context, "context");
IContext current = context;
using (var sw = new StringWriter())
{
do
{
sw.WriteLine("{0,3}) {1}", (current.Level + 1), Context(current));
current = current.ParentContext;
}
while (current != null);
return sw.ToString();
}
}
/*----------------------------------------------------------------------------------------*/
public static string Context(IContext context)
{
using (var sw = new StringWriter())
{
if (context.IsRoot)
{
sw.Write("active request for {0}", Type(context.Service));
}
else
{
sw.Write("passive injection of service {0} into {1}", Type(context.Service),
InjectionRequest(context));
}
if (context.HasDebugInfo)
{
sw.WriteLine();
sw.Write(" from {0}", context.DebugInfo);
}
if (context.Binding != null)
{
sw.WriteLine();
sw.Write(" using {0}", Binding(context.Binding));
if (context.Binding.HasDebugInfo)
{
sw.WriteLine();
sw.Write(" declared by {0}", context.Binding.DebugInfo);
}
}
return sw.ToString();
}
}
/*----------------------------------------------------------------------------------------*/
public static string InjectionRequest(IContext context)
{
Ensure.ArgumentNotNull(context, "context");
using (var sw = new StringWriter())
{
switch (context.Member.MemberType)
{
case MemberTypes.Constructor:
sw.Write("parameter {0} on constructor", context.Target.Name);
break;
case MemberTypes.Field:
sw.Write("field {0}", context.Member.Name);
break;
case MemberTypes.Method:
sw.Write("parameter {0} on method {1}", context.Target.Name, context.Member.Name);
break;
case MemberTypes.Property:
sw.Write("property {0}", context.Member.Name);
break;
default:
sw.Write("injection point {0} on member {1}", context.Target.Name, context.Member.Name);
break;
}
if (context.ParentContext.Binding != null)
sw.Write(" of type {0}", Type(context.ParentContext.Plan.Type));
return sw.ToString();
}
}
/*----------------------------------------------------------------------------------------*/
public static string Type(Type type)
{
Ensure.ArgumentNotNull(type, "type");
if (type.IsGenericType)
{
var sb = new StringBuilder();
sb.Append(type.Name.Substring(0, type.Name.LastIndexOf('`')));
sb.Append("<");
foreach (Type genericArgument in type.GetGenericArguments())
{
sb.Append(Type(genericArgument));
sb.Append(", ");
}
sb.Remove(sb.Length - 2, 2);
sb.Append(">");
return sb.ToString();
}
else
{
switch (System.Type.GetTypeCode(type))
{
case TypeCode.Boolean: return "bool";
case TypeCode.Char: return "char";
case TypeCode.SByte: return "sbyte";
case TypeCode.Byte: return "byte";
case TypeCode.Int16: return "short";
case TypeCode.UInt16: return "ushort";
case TypeCode.Int32: return "int";
case TypeCode.UInt32: return "uint";
case TypeCode.Int64: return "long";
case TypeCode.UInt64: return "ulong";
case TypeCode.Single: return "float";
case TypeCode.Double: return "double";
case TypeCode.Decimal: return "decimal";
case TypeCode.DateTime: return "DateTime";
case TypeCode.String: return "string";
default:
return type.Name;
}
}
}
/*----------------------------------------------------------------------------------------*/
public static string Binding(IBinding binding)
{
Ensure.ArgumentNotNull(binding, "binding");
using (var sw = new StringWriter())
{
if (binding.IsDefault)
sw.Write("default ");
else
sw.Write("conditional ");
if (binding.IsImplicit)
sw.Write("implicit ");
if (binding.Provider == null)
{
sw.Write("binding from {0} (incomplete)", binding.Service);
}
else
{
if (binding.Service == binding.Provider.Prototype)
sw.Write("self-binding of {0} ", Type(binding.Service));
else
sw.Write("binding from {0} to {1} ", Type(binding.Service), Type(binding.Provider.Prototype));
sw.Write("(via {0})", Type(binding.Provider.GetType()));
}
return sw.ToString();
}
}
/*----------------------------------------------------------------------------------------*/
}
}
| |
using System;
using System.Timers;
using System.Collections;
using System.Runtime.InteropServices;
using AW_API_NET;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using AWIComponentLib.Communication;
using AWIComponentLib.NetRdrConn;
namespace AWIComponentLib.NetRdrReconn
{
/// <summary>
/// Summary description for NetRdrReconnClass.
/// </summary>
public class NetRdrReconnClass
{
#region constructor
public NetRdrReconnClass(CommunicationClass comm)
{
communication = comm;
startProcessEvents = false;
scanRdrIpListIndex = -1;
openSockRdrIpListIndex = -1;
resetRdrIpListIndex = -1;
//Scanner
OnRdrScanTimer = new Timer();
OnRdrScanTimer.Interval = 1200;
OnRdrScanTimer.AutoReset = true;
OnRdrScanTimer.Enabled = true;
OnRdrScanTimer.Elapsed += new ElapsedEventHandler(OnRdrScanTimerEvent);
//open socket
OnRdrOpenSocketTimer = new Timer();
OnRdrOpenSocketTimer.Interval = 1400;
OnRdrOpenSocketTimer.AutoReset = true;
OnRdrOpenSocketTimer.Enabled = true;
OnRdrOpenSocketTimer.Elapsed += new ElapsedEventHandler(OnRdrOpenSocketTimerEvent);
// reset/powerup reader
OnRdrRestTimer = new Timer();
OnRdrRestTimer.Interval = 3000;
OnRdrRestTimer.AutoReset = true;
OnRdrRestTimer.Enabled = true;
OnRdrRestTimer.Elapsed += new ElapsedEventHandler(OnRdrRestTimerEvent);
//api = new APINetClass();
pktID = 1;
#region events
//these events will be used by the communication class to let the module know of the events
CommunicationClass.PowerupEventHandler += new PowerupEvent(this.PowerupReaderNotifty);
CommunicationClass.ScanNetworkEventHandler += new ScanNetworkEvent(this.ScanNetworkEventNotify);
CommunicationClass.OpenSocketEventHandler += new OpenSocketEvent(this.OpenSocketEventNotify);
CommunicationClass.CloseSocketEventHandler += new CloseSocketEvent(this.CloseSocketEventNotify);
NetRdrConnClass.StartReconnProcessHandler += new StartReconnProcess(this.StartReconnProcessNotify);
#endregion
}
#endregion
#region vars
private APINetClass api;
private ushort pktID;
private ArrayList scanRdrIpList = new ArrayList();
private ArrayList openSockRdrIpList = new ArrayList();
private ArrayList resetRdrIpList = new ArrayList();
public static Object myLock = new Object();
private int scanRdrIpListIndex;
private int openSockRdrIpListIndex;
private int resetRdrIpListIndex;
private Timer OnRdrScanTimer;
private Timer OnRdrOpenSocketTimer;
private Timer OnRdrRestTimer;
private bool startProcessEvents;
private CommunicationClass communication;
#endregion
#region OnRdrScanTimerEvent
private void OnRdrScanTimerEvent(object source, ElapsedEventArgs e)
{
lock(myLock)
{
if ((scanRdrIpList.Count > 0) && startProcessEvents)
{
if (scanRdrIpListIndex >= scanRdrIpList.Count)
scanRdrIpListIndex = 0;
Byte[] ip = new Byte[20];
char[] cIP = new char[20];
string ipStr = (string)scanRdrIpList[scanRdrIpListIndex];
cIP = ipStr.ToCharArray(0, ipStr.Length);
for (int i=0; i<ipStr.Length; i++)
ip[i] = Convert.ToByte(cIP[i]);
if (pktID >= 224)
pktID = 1;
//int ret = api.rfScanIP(ip, pktID++);
int ret = communication.ScanNetwork(ip);
scanRdrIpListIndex += 1;
Console.WriteLine("NetRdrReconn rfScanIP() was called");
}
}//lock
}
#endregion
#region OnRdrOpenSocketTimerEvent
private void OnRdrOpenSocketTimerEvent(object source, ElapsedEventArgs e)
{
lock(myLock)
{
if ((openSockRdrIpList.Count > 0) && startProcessEvents)
{
if (openSockRdrIpListIndex >= openSockRdrIpList.Count)
openSockRdrIpListIndex = 0;
Byte[] ip = new Byte[20];
char[] cIP = new char[20];
string ipStr = (string)openSockRdrIpList[openSockRdrIpListIndex];
cIP = ipStr.ToCharArray(0, ipStr.Length);
for (int i=0; i<ipStr.Length; i++)
ip[i] = Convert.ToByte(cIP[i]);
if (pktID >= 224)
pktID = 1;
//int ret = api.rfOpenSocket(ip, 1, false, AW_API_NET.APIConsts.SPECIFIC_IP, pktID++);
int ret = communication.SocketConnection(ip);
openSockRdrIpListIndex += 1;
Console.WriteLine("NetRdrReconn rfOpenSocket() was called");
}
}//lock
}
#endregion
#region OnRdrRestTimerEvent
private void OnRdrRestTimerEvent(object source, ElapsedEventArgs e)
{
lock(myLock)
{
if ((resetRdrIpList.Count > 0) && startProcessEvents) //flag to prevent from processing normal communication routines
{
if (resetRdrIpListIndex >= resetRdrIpList.Count)
resetRdrIpListIndex = 0;
Byte[] ip = new Byte[20];
char[] cIP = new char[20];
string ipStr = (string)resetRdrIpList[resetRdrIpListIndex];
cIP = ipStr.ToCharArray(0, ipStr.Length);
for (int i=0; i<ipStr.Length; i++)
ip[i] = Convert.ToByte(cIP[i]);
if (pktID >= 224)
pktID = 1;
//need to check these api function - may need to use ResetReader
//int ret = api.rfResetReaderSocket(1, ip, pktID++);
//int ret = api.rfResetReader(1, 0, 0, AW_API_NET.APIConsts.ALL_READERS, pktID++);
//int ret = communication.ResetReaderSocket(1, ip);
int ret = communication.ResetAllReaders();
resetRdrIpListIndex += 1;
Console.WriteLine("NetRdrReconn rfResetReaderSocket() was called time=" + DateTime.Now.ToString());
}
}//lock
}
#endregion
#region StartReconnProcessNotify
private void StartReconnProcessNotify(AW_API_NET.rfReaderEvent_t rdrEvent)
{
string ip;
int ret;
lock(myLock)
{
Console.WriteLine("NetRdrReconn StartReconnProcessNotify is called");
startProcessEvents = true;
if ((ip=GetStringIP(rdrEvent.ip)) != "")
{
if (pktID >= 224)
pktID = 1;
//add ip to the list to get scaned
if (!scanRdrIpList.Contains(ip))
{
ret = api.rfCloseSocket(rdrEvent.ip, AW_API_NET.APIConsts.SPECIFIC_IP);
scanRdrIpList.Add(ip); //string
//add to the scaniplist index
if (scanRdrIpListIndex < 0)
scanRdrIpListIndex = 0;
}
//ret = api.rfScanIP(rdrEvent.ip, pktID++);
}
}//lock
}
#endregion
#region ScanNetworkEventNotify
private void ScanNetworkEventNotify(AW_API_NET.rfReaderEvent_t rdrEvent)
{
string ip;
lock(myLock)
{
if (startProcessEvents) //flag to prevent from processing normal communication routines
{
Console.WriteLine("NetRdrReconn ScanNetworkEventNotify is received");
if ((ip=GetStringIP(rdrEvent.ip)) != "")
{
//remove it from scan list and add to opensock list
scanRdrIpList.Remove(ip);
if (scanRdrIpList.Count == 0)
scanRdrIpListIndex = -1;
openSockRdrIpList.Add(ip);
if (openSockRdrIpListIndex < 0)
openSockRdrIpListIndex = 0;
//if (pktID >= 224)
//pktID = 1;
//ret = api.rfOpenSocket(rdrEvent.ip, 1, false, AW_API_NET.APIConsts.SPECIFIC_IP, pktID++);
}
}
}
}
#endregion
#region OpenSocketEventNotify
private void OpenSocketEventNotify(AW_API_NET.rfReaderEvent_t rdrEvent)
{
string ip;
lock(myLock)
{
if (startProcessEvents) //flag to prevent from processing normal communication routines
{
Console.WriteLine("NetRdrReconn OpenSocketEventNotify is received");
if ((ip=GetStringIP(rdrEvent.ip)) != "")
{
openSockRdrIpList.Remove(ip);
if (openSockRdrIpList.Count == 0)
openSockRdrIpListIndex = -1;
resetRdrIpList.Add(ip);
if (resetRdrIpListIndex < 0)
resetRdrIpListIndex = 0;
}
}
}
}
#endregion
#region PowerupReaderNotifty
private void PowerupReaderNotifty(AW_API_NET.rfReaderEvent_t rdrEvent)
{
string ip;
lock(myLock)
{
if (startProcessEvents) //flag to prevent from processing normal communication routines
{
Console.WriteLine("NetRdrReconn PowerupReaderNotifty is received");
if ((ip=GetStringIP(rdrEvent.ip)) != "")
{
//remove it from reset reader list
resetRdrIpList.Remove(ip);
if (resetRdrIpList.Count == 0)
resetRdrIpListIndex = -1;
}
}
}
}
#endregion
#region CloseSocketEventNotify
private void CloseSocketEventNotify(AW_API_NET.rfReaderEvent_t rdrEvent)
{
}
#endregion
#region GetStringIP
private string GetStringIP (byte[] ip)
{
int p = 0;
string s = "";
int ct = 0;
while ((ct <= 3) && (p < 20) &&(ip[p] != 0))
{
if (ip[p] != 46)
s += Convert.ToInt16(ip[p++]) - 48;
else
{
ct++;
p++;
s += ".";
}
}
return s;
}
#endregion
}
}
| |
namespace SupermarketsChain.SQLite.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using SupermarketsChain.Data.Contexts;
using SupermarketsChain.Models;
internal sealed class Configuration : DbMigrationsConfiguration<SqliteDbContext>
{
private readonly Random random = new Random(0);
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(SqliteDbContext context)
{
var towns = this.SeedTowns(context);
var supermarkets = this.SeedSupermarkets(context, towns);
var vendors = this.SeedVendors(context);
var measures = this.SeedMeasures(context);
var products = this.SeedProducts(context, vendors, measures);
this.SeedSales(context, products, supermarkets);
}
private void SeedSales(SqliteDbContext context, IList<Product> products, IList<Supermarket> supermarkets)
{
var sales = new List<Sale>();
for (int i = 0; i < 100; i++)
{
var unitPrice = this.random.Next(1000);
var quantity = this.random.Next(1000);
sales.Add(new Sale
{
Product = products[this.random.Next(products.Count)],
Supermarket = supermarkets[this.random.Next(supermarkets.Count)],
SoldDate = this.RandomDay(),
PricePerUnit = unitPrice,
Quantity = quantity,
SaleCost = unitPrice * quantity
});
}
foreach (var sale in sales)
{
context.Sales.Add(sale);
}
context.SaveChanges();
}
private IList<Measure> SeedMeasures(SqliteDbContext context)
{
var measures = new List<Measure>
{
new Measure { Name = "Liter" },
new Measure { Name = "Unit" },
new Measure { Name = "Kilograms" },
new Measure { Name = "Grams" }
};
foreach (var measure in measures)
{
context.Measures.AddOrUpdate(measure);
}
context.SaveChanges();
return measures;
}
private IList<Product> SeedProducts(SqliteDbContext context, IList<Vendor> vendors, IList<Measure> measures)
{
var products = new List<Product>
{
new Product
{
Name = "Laptop",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Tablet",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Smartphone",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Glass",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Monitor",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Visual Studio",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Energy Drink",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Banana",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Potato",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Lan Cable",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Shirt",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Beer",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Vodka",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Wisky",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
},
new Product
{
Name = "Coffee",
Vendor = vendors[this.random.Next(vendors.Count)],
Measure = measures[this.random.Next(measures.Count)]
}
};
foreach (var product in products)
{
context.Products.AddOrUpdate(product);
}
context.SaveChanges();
return products;
}
private IList<Vendor> SeedVendors(SqliteDbContext context)
{
var vendors = new List<Vendor>
{
new Vendor { Name = "Bosh" },
new Vendor { Name = "Simens" },
new Vendor { Name = "Toshiba" },
new Vendor { Name = "FF" },
new Vendor { Name = "K-Classics" },
new Vendor { Name = "Clever" }
};
foreach (var vendor in vendors)
{
context.Vendors.AddOrUpdate(vendor);
}
context.SaveChanges();
return vendors;
}
private IList<Supermarket> SeedSupermarkets(SqliteDbContext context, IList<Town> towns)
{
var supermarkets = new List<Supermarket>
{
new Supermarket
{
Name = "Billa",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "Billa",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "Fantastico",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "T-Market",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "MyShop",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "Dar",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "Kal",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "Kaufland",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "MyShop",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "Kaufland",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "Lidl",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "Plus",
Town = towns[this.random.Next(towns.Count)]
},
new Supermarket
{
Name = "Tempo",
Town = towns[this.random.Next(towns.Count)]
}
};
foreach (var supermarket in supermarkets)
{
context.Supermarkets.AddOrUpdate(supermarket);
}
context.SaveChanges();
return supermarkets;
}
private IList<Town> SeedTowns(SqliteDbContext context)
{
var towns = new List<Town>
{
new Town { Name = "Sofia" },
new Town { Name = "Varna" },
new Town { Name = "Burgas" },
new Town { Name = "Plovdiv" },
new Town { Name = "Ruse" },
new Town { Name = "Pernik" }
};
foreach (var town in towns)
{
context.Towns.AddOrUpdate(town);
}
context.SaveChanges();
return towns;
}
private DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(this.random.Next(range));
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.SS.Formula
{
using System;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NUnit.Framework;
using TestCases.HSSF;
/**
* Tests {@link WorkbookEvaluator}.
*
* @author Josh Micich
*/
[TestFixture]
public class TestWorkbookEvaluator
{
private static ValueEval EvaluateFormula(Ptg[] ptgs)
{
OperationEvaluationContext ec = new OperationEvaluationContext(null, null, 0, 0, 0, null);
return new WorkbookEvaluator(null, null, null).EvaluateFormula(ec, ptgs);
}
/**
* Make sure that the Evaluator can directly handle tAttrSum (instead of relying on re-parsing
* the whole formula which Converts tAttrSum to tFuncVar("SUM") )
*/
[Test]
public void TestAttrSum()
{
Ptg[] ptgs = { new IntPtg(42), AttrPtg.SUM, };
ValueEval result = EvaluateFormula(ptgs);
Assert.AreEqual(42, ((NumberEval)result).NumberValue, 0.0);
}
/**
* Make sure that the Evaluator can directly handle (deleted) ref error tokens
* (instead of relying on re-parsing the whole formula which Converts these
* to the error constant #REF! )
*/
[Test]
public void TestRefErr()
{
ConfirmRefErr(new RefErrorPtg());
ConfirmRefErr(new AreaErrPtg());
ConfirmRefErr(new DeletedRef3DPtg(0));
ConfirmRefErr(new DeletedArea3DPtg(0));
}
private static void ConfirmRefErr(Ptg ptg)
{
Ptg[] ptgs = { ptg };
ValueEval result = EvaluateFormula(ptgs);
Assert.AreEqual(ErrorEval.REF_INVALID, result);
}
/**
* Make sure that the Evaluator can directly handle tAttrSum (instead of relying on re-parsing
* the whole formula which Converts tAttrSum to tFuncVar("SUM") )
*/
[Test]
public void TestMemFunc()
{
Ptg[] ptgs = { new IntPtg(42), AttrPtg.SUM, };
ValueEval result = EvaluateFormula(ptgs);
Assert.AreEqual(42, ((NumberEval)result).NumberValue, 0.0);
}
[Test]
public void TestEvaluateMultipleWorkbooks()
{
HSSFWorkbook wbA = HSSFTestDataSamples.OpenSampleWorkbook("multibookFormulaA.xls");
HSSFWorkbook wbB = HSSFTestDataSamples.OpenSampleWorkbook("multibookFormulaB.xls");
HSSFFormulaEvaluator EvaluatorA = new HSSFFormulaEvaluator(wbA);
HSSFFormulaEvaluator EvaluatorB = new HSSFFormulaEvaluator(wbB);
// Hook up the workbook Evaluators to enable Evaluation of formulas across books
String[] bookNames = { "multibookFormulaA.xls", "multibookFormulaB.xls", };
HSSFFormulaEvaluator[] Evaluators = { EvaluatorA, EvaluatorB, };
HSSFFormulaEvaluator.SetupEnvironment(bookNames, Evaluators);
ISheet aSheet1 = wbA.GetSheetAt(0);
ISheet bSheet1 = wbB.GetSheetAt(0);
// Simple case - single link from wbA to wbB
ConfirmFormula(wbA, 0, 0, 0, "[multibookFormulaB.xls]BSheet1!B1");
ICell cell = aSheet1.GetRow(0).GetCell(0);
ConfirmEvaluation(35, EvaluatorA, cell);
// more complex case - back link into wbA
// [wbA]ASheet1!A2 references (among other things) [wbB]BSheet1!B2
ConfirmFormula(wbA, 0, 1, 0, "[multibookFormulaB.xls]BSheet1!$B$2+2*A3");
// [wbB]BSheet1!B2 references (among other things) [wbA]AnotherSheet!A1:B2
ConfirmFormula(wbB, 0, 1, 1, "SUM([multibookFormulaA.xls]AnotherSheet!$A$1:$B$2)+B3");
cell = aSheet1.GetRow(1).GetCell(0);
ConfirmEvaluation(264, EvaluatorA, cell);
// change [wbB]BSheet1!B3 (from 50 to 60)
ICell cellB3 = bSheet1.GetRow(2).GetCell(1);
cellB3.SetCellValue(60);
EvaluatorB.NotifyUpdateCell(cellB3);
ConfirmEvaluation(274, EvaluatorA, cell);
// change [wbA]ASheet1!A3 (from 100 to 80)
ICell cellA3 = aSheet1.GetRow(2).GetCell(0);
cellA3.SetCellValue(80);
EvaluatorA.NotifyUpdateCell(cellA3);
ConfirmEvaluation(234, EvaluatorA, cell);
// change [wbA]AnotherSheet!A1 (from 2 to 3)
ICell cellA1 = wbA.GetSheetAt(1).GetRow(0).GetCell(0);
cellA1.SetCellValue(3);
EvaluatorA.NotifyUpdateCell(cellA1);
ConfirmEvaluation(235, EvaluatorA, cell);
}
private static void ConfirmEvaluation(double expectedValue, HSSFFormulaEvaluator fe, ICell cell)
{
Assert.AreEqual(expectedValue, fe.Evaluate(cell).NumberValue, 0.0);
}
private static void ConfirmFormula(HSSFWorkbook wb, int sheetIndex, int rowIndex, int columnIndex,
String expectedFormula)
{
ICell cell = wb.GetSheetAt(sheetIndex).GetRow(rowIndex).GetCell(columnIndex);
Assert.AreEqual(expectedFormula, cell.CellFormula);
}
/**
* This Test Makes sure that any {@link MissingArgEval} that propagates to
* the result of a function Gets translated to {@link BlankEval}.
*/
[Test]
public void TestMissingArg()
{
HSSFWorkbook wb = new HSSFWorkbook();
ISheet sheet = wb.CreateSheet("Sheet1");
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.CellFormula = "1+IF(1,,)";
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
CellValue cv;
try
{
cv = fe.Evaluate(cell);
}
catch (Exception)
{
throw new AssertionException("Missing arg result not being handled correctly.");
}
Assert.AreEqual(CellType.Numeric, cv.CellType);
// Adding blank to 1.0 gives 1.0
Assert.AreEqual(1.0, cv.NumberValue, 0.0);
// check with string operand
cell.CellFormula = "\"abc\"&IF(1,,)";
fe.NotifySetFormula(cell);
cv = fe.Evaluate(cell);
Assert.AreEqual(CellType.String, cv.CellType);
// Adding blank to "abc" gives "abc"
Assert.AreEqual("abc", cv.StringValue);
// check CHOOSE()
cell.CellFormula = "\"abc\"&CHOOSE(2,5,,9)";
fe.NotifySetFormula(cell);
cv = fe.Evaluate(cell);
Assert.AreEqual(CellType.String, cv.CellType);
// Adding blank to "abc" gives "abc"
Assert.AreEqual("abc", cv.StringValue);
}
/**
* Functions like IF, INDIRECT, INDEX, OFFSET etc can return AreaEvals which
* should be dereferenced by the Evaluator
*/
[Test]
public void TestResultOutsideRange()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
HSSFWorkbook wb = new HSSFWorkbook();
ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0);
cell.CellFormula = "D2:D5"; // IF(TRUE,D2:D5,D2) or OFFSET(D2:D5,0,0) would work too
IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();
CellValue cv;
try
{
cv = fe.Evaluate(cell);
}
catch (ArgumentException e)
{
if ("Specified row index (0) is outside the allowed range (1..4)".Equals(e.Message))
{
throw new AssertionException("Identified bug in result dereferencing");
}
throw;
}
Assert.AreEqual(CellType.Error, cv.CellType);
Assert.AreEqual(ErrorConstants.ERROR_VALUE, cv.ErrorValue);
// verify circular refs are still detected properly
fe.ClearAllCachedResultValues();
cell.CellFormula = "OFFSET(A1,0,0)";
cv = fe.Evaluate(cell);
Assert.AreEqual(CellType.Error, cv.CellType);
Assert.AreEqual(ErrorEval.CIRCULAR_REF_ERROR.ErrorCode, cv.ErrorValue);
}
/**
* formulas with defined names.
*/
[Test]
public void TestNamesInFormulas()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
IWorkbook wb = new HSSFWorkbook();
ISheet sheet = wb.CreateSheet("Sheet1");
IName name1 = wb.CreateName();
name1.NameName = "aConstant";
name1.RefersToFormula = "3.14";
IName name2 = wb.CreateName();
name2.NameName = "aFormula";
name2.RefersToFormula = "SUM(Sheet1!$A$1:$A$3)";
IName name3 = wb.CreateName();
name3.NameName = "aSet";
name3.RefersToFormula = "Sheet1!$A$2:$A$4";
IRow row0 = sheet.CreateRow(0);
IRow row1 = sheet.CreateRow(1);
IRow row2 = sheet.CreateRow(2);
IRow row3 = sheet.CreateRow(3);
row0.CreateCell(0).SetCellValue(2);
row1.CreateCell(0).SetCellValue(5);
row2.CreateCell(0).SetCellValue(3);
row3.CreateCell(0).SetCellValue(7);
row0.CreateCell(2).SetCellFormula("aConstant");
row1.CreateCell(2).SetCellFormula("aFormula");
row2.CreateCell(2).SetCellFormula("SUM(aSet)");
row3.CreateCell(2).SetCellFormula("aConstant+aFormula+SUM(aSet)");
IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();
Assert.AreEqual(3.14, fe.Evaluate(row0.GetCell(2)).NumberValue);
Assert.AreEqual(10.0, fe.Evaluate(row1.GetCell(2)).NumberValue);
Assert.AreEqual(15.0, fe.Evaluate(row2.GetCell(2)).NumberValue);
Assert.AreEqual(28.14, fe.Evaluate(row3.GetCell(2)).NumberValue);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
namespace Ets2Map
{
public class Ets2Prefab
{
private Ets2Mapper _map;
public string FilePath { get; private set; }
public Ets2Company Company { get; set; }
private byte[] Stream;
public int IDX;
public string IDSII;
public List<Ets2PrefabNode> Nodes = new List<Ets2PrefabNode>();
public List<Ets2PrefabCurve> Curves = new List<Ets2PrefabCurve>();
public Ets2Prefab(Ets2Mapper mapper, string file)
{
_map = mapper;
FilePath = file;
if (File.Exists(file))
{
Stream = File.ReadAllBytes(file);
Parse();
}
}
private void Parse()
{
var version = BitConverter.ToInt32(Stream, 0);
// Made for version 21, however not throwing any errors if mismatched yet
if (version != 21)
{
}
var nodes = BitConverter.ToInt32(Stream, 4);
var terrain = BitConverter.ToInt32(Stream, 12);
var navCurves = BitConverter.ToInt32(Stream, 8);
var signs = BitConverter.ToInt32(Stream, 16);
var spawns = BitConverter.ToInt32(Stream, 20);
var semaphores = BitConverter.ToInt32(Stream, 24);
var mappoints = BitConverter.ToInt32(Stream, 28);
var triggers = BitConverter.ToInt32(Stream, 32);
var intersections = BitConverter.ToInt32(Stream, 36);
var nodeOffset = BitConverter.ToInt32(Stream, 44);
var off2 = BitConverter.ToInt32(Stream, 48);
var off3 = BitConverter.ToInt32(Stream, 52);
var off4 = BitConverter.ToInt32(Stream, 56);
for (int navCurve = 0; navCurve < navCurves; navCurve++)
{
var curveOff = off2 + navCurve*128;
var nextCurve = new List<int>();
var prevCurve = new List<int>();
for (int k = 0; k < 4; k++)
{
nextCurve.Add(BitConverter.ToInt32(Stream, 76 + k*4 + curveOff));
prevCurve.Add(BitConverter.ToInt32(Stream, 92 + k*4 + curveOff));
}
var curve = new Ets2PrefabCurve
{
Index = navCurve,
StartX = BitConverter.ToSingle(Stream, 16 + curveOff),
StartY = BitConverter.ToSingle(Stream, 20 + curveOff),
StartZ = BitConverter.ToSingle(Stream, 24 + curveOff),
EndX = BitConverter.ToSingle(Stream, 28 + curveOff),
EndY = BitConverter.ToSingle(Stream, 32 + curveOff),
EndZ = BitConverter.ToSingle(Stream, 36 + curveOff),
StartRotationX = BitConverter.ToSingle(Stream, 40 + curveOff),
StartRotationY = BitConverter.ToSingle(Stream, 44 + curveOff),
StartRotationZ = BitConverter.ToSingle(Stream, 48 + curveOff),
EndRotationX = BitConverter.ToSingle(Stream, 52 + curveOff),
EndRotationY = BitConverter.ToSingle(Stream, 56 + curveOff),
EndRotationZ = BitConverter.ToSingle(Stream, 60 + curveOff),
StartYaw =
Math.Atan2(BitConverter.ToSingle(Stream, 48 + curveOff),
BitConverter.ToSingle(Stream, 40 + curveOff)),
EndYaw =
Math.Atan2(BitConverter.ToSingle(Stream, 60 + curveOff),
BitConverter.ToSingle(Stream, 52 + curveOff)),
Length = BitConverter.ToSingle(Stream, 72 + curveOff),
Next = nextCurve.Where(i => i != -1).ToArray(),
Prev = prevCurve.Where(i => i != -1).ToArray()
};
Curves.Add(curve);
}
for (int navCurve = 0; navCurve < navCurves; navCurve++)
{
Curves[navCurve].NextCurve = Curves[navCurve].Next.Select(x => Curves[x]).ToList();
Curves[navCurve].PrevCurve = Curves[navCurve].Prev.Select(x => Curves[x]).ToList();
}
for (int node = 0; node < nodes; node++)
{
var nodeOff = nodeOffset + 104*node;
var inputLanes = new List<int>();
var outputLanes = new List<int>();
for (var k = 0; k < 8; k++)
{
inputLanes.Add(BitConverter.ToInt32(Stream, 40 + k*4 + nodeOff));
outputLanes.Add(BitConverter.ToInt32(Stream, 72 + k*4 + nodeOff));
}
var prefabNode = new Ets2PrefabNode
{
Node = node,
X = BitConverter.ToSingle(Stream, 16 + nodeOff),
Y = BitConverter.ToSingle(Stream, 20 + nodeOff),
Z = BitConverter.ToSingle(Stream, 24 + nodeOff),
RotationX = BitConverter.ToSingle(Stream, 28 + nodeOff),
RotationY = BitConverter.ToSingle(Stream, 32 + nodeOff),
RotationZ = BitConverter.ToSingle(Stream, 36 + nodeOff),
InputCurve = inputLanes.Where(i => i != -1).Select(x => Curves[x]).ToList(),
OutputCurve = outputLanes.Where(i => i != -1).Select(x => Curves[x]).ToList(),
Yaw = Math.PI-
Math.Atan2(BitConverter.ToSingle(Stream, 36 + nodeOff),
BitConverter.ToSingle(Stream, 28 + nodeOff))
};
Nodes.Add(prefabNode);
}
}
public bool IsFile(string file)
{
return Path.GetFileNameWithoutExtension(file) == Path.GetFileNameWithoutExtension(FilePath);
}
private IEnumerable<List<Ets2PrefabCurve>> IterateCurves(IEnumerable<Ets2PrefabCurve> list, Ets2PrefabCurve curve, bool forwardDirection)
{
var curves = (forwardDirection ? curve.Next : curve.Prev).Select(x => Curves[x]);
if (curves.Any())
{
foreach (var c in curves)
{
var l = new List<Ets2PrefabCurve>(list);
if (list.Contains(c))
yield return l;
else
{
l.Add(c);
var res = IterateCurves(l, c, forwardDirection);
foreach (var r in res)
yield return r;
}
}
}
else
{
yield return list.ToList();
}
}
public IEnumerable<Ets2PrefabRoute> GetRouteOptions(int entryNodeId)
{
if (entryNodeId >= Nodes.Count() || entryNodeId < 0)
return new Ets2PrefabRoute[0];
var entryNode = Nodes[entryNodeId];
// This entry node has several entry and exit routes (in/out)
// IN is driving into
// OUT is coming out of
var routes = entryNode.InputCurve.Select(x => IterateCurves(new[] { x}, x, true)).SelectMany(x => x).Select(x => new Ets2PrefabRoute(x, entryNode, FindExitNode(x.LastOrDefault()))).ToList();
return routes;
}
public IEnumerable<Ets2PrefabRoute> GetAllRoutes()
{
return Nodes.SelectMany(x => GetRouteOptions(x.Node));
}
private Ets2PrefabNode FindExitNode(Ets2PrefabCurve c)
{
return Nodes.OrderBy(x => Math.Sqrt(Math.Pow(c.EndX - x.X, 2) + Math.Pow(c.EndZ - x.Z, 2))).FirstOrDefault();
}
private Ets2PrefabNode FindStartNode(Ets2PrefabCurve c)
{
return Nodes.OrderBy(x => Math.Sqrt(Math.Pow(c.StartX - x.X, 2) + Math.Pow(c.StartZ - x.Z, 2))).FirstOrDefault();
}
public IEnumerable<Ets2PrefabRoute> GetRoute(int entryNode, int exitNode)
{
var options = GetRouteOptions(entryNode);
if (options.Any(x => x.Exit.Node == exitNode))
return options.Where(x => x.Exit.Node == exitNode);
else
return new Ets2PrefabRoute[0];
}
public IEnumerable<Ets2Point> GeneratePolygonForRoute(Ets2PrefabRoute route, Ets2Node node, int nodeOr)
{
List<Ets2Point> p = new List<Ets2Point>();
if (route == null || route.Route == null)
return p;
/*
yaw -= this.Nodes[nodeOr].Yaw;
yaw += Math.PI/2;
*/
var xOr = node.X;
var yOr = node.Z;
var yaw = node.Yaw - this.Nodes[nodeOr].Yaw + Math.PI / 2;
foreach (var curve in route.Route)
{
var srx = curve.StartX - this.Nodes[nodeOr].X;
var erx = curve.EndX - this.Nodes[nodeOr].X;
var srz = curve.StartZ - this.Nodes[nodeOr].Z;
var erz = curve.EndZ - this.Nodes[nodeOr].Z;
var sr = (float) Math.Sqrt(srx*srx + srz*srz);
var er = (float) Math.Sqrt(erx*erx + erz*erz);
var ans = yaw - Math.Atan2(srz, srx);
var ane = yaw - Math.Atan2(erz, erx);
var sx = xOr - sr*(float) Math.Sin(ans);
var ex = xOr - er*(float) Math.Sin(ane);
var sz = yOr - sr*(float) Math.Cos(ans);
var ez = yOr - er*(float) Math.Cos(ane);
// TODO: Temporary linear interpolation
// TODO: Interpolate heading & Y value
var ps = new Ets2Point[2];
ps[0] = new Ets2Point(sx, node.Y, sz,(float) ans);
ps[1] = new Ets2Point(ex, node.Y, ez, (float)ane);
p.AddRange(ps);
}
return p;
}
public IEnumerable<IEnumerable<Ets2Point>> GeneratePolygonCurves(Ets2Node node, int nodeOr)
{
var ks = new List<IEnumerable<Ets2Point>>();
var steps = 16;
if (nodeOr >= this.Nodes.Count)
nodeOr = 0;
if (Nodes.Any() == false)
return ks;
var xOr = node.X;
var yOr = node.Z;
var yaw = node.Yaw - this.Nodes[nodeOr].Yaw + Math.PI/2;
foreach (var curve in Curves)
{
var ps = new Ets2Point[steps];
var srx = curve.StartX - this.Nodes[nodeOr].X;
var erx = curve.EndX - this.Nodes[nodeOr].X;
var srz = curve.StartZ - this.Nodes[nodeOr].Z;
var erz = curve.EndZ - this.Nodes[nodeOr].Z;
var sr = (float) Math.Sqrt(srx * srx + srz * srz);
var er = (float)Math.Sqrt(erx * erx + erz * erz);
var ans = yaw - Math.Atan2(srz,srx);
var ane = yaw - Math.Atan2(erz, erx);
var sx = xOr - sr * (float)Math.Sin(ans);
var ex = xOr - er * (float)Math.Sin(ane);
var sz = yOr - sr * (float)Math.Cos(ans);
var ez = yOr - er * (float)Math.Cos(ane);
// TODO: Temporary linear interpolation
// TODO: Interpolate heading & Y value
ps = new Ets2Point[2];
ps[0] = new Ets2Point(sx, 0, sz, 0);
ps[1] = new Ets2Point(ex, 0, ez, 0);
ks.Add(ps);
/*
var tangentSX = (float)Math.Cos(ans) * curve.Length;
var tangentEX = (float)Math.Cos(ane) * curve.Length;
var tangentSY = (float)Math.Sin(ans) * curve.Length;
var tangentEY = (float)Math.Sin(ane) * curve.Length;
for (int k = 0; k < steps; k++)
{
var s = (float)k / (float)steps;
var x = (float)Ets2CurveHelper.Hermite(s, sx, ex, tangentSX, tangentEX);
var z = (float)Ets2CurveHelper.Hermite(s, sz, ez, tangentSY, tangentEY);
ps[k] = new Ets2Point(x, 0, z, 0);
}
ks.Add(ps);
*/
}
return ks;
}
}
}
| |
using System;
namespace Versioning
{
public class InvoiceItem : Sage_Container, IMove
{
/* Autogenerated by sage_wrapper_generator.pl */
SageDataObject110.InvoiceItem ii11;
SageDataObject120.InvoiceItem ii12;
SageDataObject130.InvoiceItem ii13;
SageDataObject140.InvoiceItem ii14;
SageDataObject150.InvoiceItem ii15;
SageDataObject160.InvoiceItem ii16;
SageDataObject170.InvoiceItem ii17;
public InvoiceItem(object inner, int version)
: base(version) {
switch (m_version) {
case 11: {
ii11 = (SageDataObject110.InvoiceItem)inner;
m_fields = new Fields(ii11.Fields,m_version);
return;
}
case 12: {
ii12 = (SageDataObject120.InvoiceItem)inner;
m_fields = new Fields(ii12.Fields,m_version);
return;
}
case 13: {
ii13 = (SageDataObject130.InvoiceItem)inner;
m_fields = new Fields(ii13.Fields,m_version);
return;
}
case 14: {
ii14 = (SageDataObject140.InvoiceItem)inner;
m_fields = new Fields(ii14.Fields,m_version);
return;
}
case 15: {
ii15 = (SageDataObject150.InvoiceItem)inner;
m_fields = new Fields(ii15.Fields,m_version);
return;
}
case 16: {
ii16 = (SageDataObject160.InvoiceItem)inner;
m_fields = new Fields(ii16.Fields,m_version);
return;
}
case 17: {
ii17 = (SageDataObject170.InvoiceItem)inner;
m_fields = new Fields(ii17.Fields,m_version);
return;
}
default: throw new InvalidOperationException("ver");
}
}
/* Autogenerated with record_generator.pl */
const string ACCOUNT_REF = "ACCOUNT_REF";
const string INVOICEITEM = "INVOICEITEM";
public bool Deleted_Safe {
get {
if (m_version < 13)
return false;
return Deleted;
}
}
public override bool Deleted {
get {
bool ret;
switch (m_version) {
case 13: {
ret = ii13.IsDeleted();
break;
}
case 14: {
ret = ii14.IsDeleted();
break;
}
case 15: {
ret = ii15.IsDeleted();
break;
}
case 16: {
ret = ii16.IsDeleted();
break;
}
case 17: {
ret = ii17.IsDeleted();
break;
}
case 11:
case 12:
default: throw new InvalidOperationException("ver");
}
return ret;
}
}
///
//public bool AddNew() {
// bool ret;
// switch (m_version) {
// case 11: {
// ret = ii11.AddNew();
// break;
// }
// case 12: {
// ret = ii12.AddNew();
// break;
// }
// case 13: {
// ret = ii13.AddNew();
// break;
// }
// case 14: {
// ret = ii14.AddNew();
// break;
// }
// case 15: {
// ret = ii15.AddNew();
// break;
// }
// case 16: {
// ret = ii16.AddNew();
// break;
// }
// case 17: {
// ret = ii17.AddNew();
// break;
// }
// default: throw new InvalidOperationException("ver");
// }
// return ret;
//}
//public bool Update() {
// bool ret;
// switch (m_version) {
// case 11: {
// ret = ii11.Update();
// break;
// }
// case 12: {
// ret = ii12.Update();
// break;
// }
// case 13: {
// ret = ii13.Update();
// break;
// }
// case 14: {
// ret = ii14.Update();
// break;
// }
// case 15: {
// ret = ii15.Update();
// break;
// }
// case 16: {
// ret = ii16.Update();
// break;
// }
// case 17: {
// ret = ii17.Update();
// break;
// }
// default: throw new InvalidOperationException("ver");
// }
// return ret;
//}
//public bool Edit() {
// bool ret;
// switch (m_version) {
// case 11: {
// ret = ii11.Edit();
// break;
// }
// case 12: {
// ret = ii12.Edit();
// break;
// }
// case 13: {
// ret = ii13.Edit();
// break;
// }
// case 14: {
// ret = ii14.Edit();
// break;
// }
// case 15: {
// ret = ii15.Edit();
// break;
// }
// case 16: {
// ret = ii16.Edit();
// break;
// }
// case 17: {
// ret = ii17.Edit();
// break;
// }
// default: throw new InvalidOperationException("ver");
// }
// return ret;
//}
//public bool Find(bool partial) {
// bool ret;
// switch (m_version) {
// case 11: {
// ret = ii11.Find(partial);
// break;
// }
// case 12: {
// ret = ii12.Find(partial);
// break;
// }
// case 13: {
// ret = ii13.Find(partial);
// break;
// }
// case 14: {
// ret = ii14.Find(partial);
// break;
// }
// case 15: {
// ret = ii15.Find(partial);
// break;
// }
// case 16: {
// ret = ii16.Find(partial);
// break;
// }
// case 17: {
// ret = ii17.Find(partial);
// break;
// }
// default: throw new InvalidOperationException("ver");
// }
// return ret;
//}
//
public bool MoveFirst() {
bool ret;
switch (m_version) {
case 11: {
ret = ii11.MoveFirst();
break;
}
case 12: {
ret = ii12.MoveFirst();
break;
}
case 13: {
ret = ii13.MoveFirst();
break;
}
case 14: {
ret = ii14.MoveFirst();
break;
}
case 15: {
ret = ii15.MoveFirst();
break;
}
case 16: {
ret = ii16.MoveFirst();
break;
}
case 17: {
ret = ii17.MoveFirst();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool MoveNext() {
bool ret;
switch (m_version) {
case 11: {
ret = ii11.MoveNext();
break;
}
case 12: {
ret = ii12.MoveNext();
break;
}
case 13: {
ret = ii13.MoveNext();
break;
}
case 14: {
ret = ii14.MoveNext();
break;
}
case 15: {
ret = ii15.MoveNext();
break;
}
case 16: {
ret = ii16.MoveNext();
break;
}
case 17: {
ret = ii17.MoveNext();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool MoveLast() {
bool ret;
switch (m_version) {
case 11: {
ret = ii11.MoveLast();
break;
}
case 12: {
ret = ii12.MoveLast();
break;
}
case 13: {
ret = ii13.MoveLast();
break;
}
case 14: {
ret = ii14.MoveLast();
break;
}
case 15: {
ret = ii15.MoveLast();
break;
}
case 16: {
ret = ii16.MoveLast();
break;
}
case 17: {
ret = ii17.MoveLast();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool MovePrev() {
bool ret;
switch (m_version) {
case 11: {
ret = ii11.MovePrev();
break;
}
case 12: {
ret = ii12.MovePrev();
break;
}
case 13: {
ret = ii13.MovePrev();
break;
}
case 14: {
ret = ii14.MovePrev();
break;
}
case 15: {
ret = ii15.MovePrev();
break;
}
case 16: {
ret = ii16.MovePrev();
break;
}
case 17: {
ret = ii17.MovePrev();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Write(int RecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = ii11.Write(RecNo);
break;
}
case 12: {
ret = ii12.Write(RecNo);
break;
}
case 13: {
ret = ii13.Write(RecNo);
break;
}
case 14: {
ret = ii14.Write(RecNo);
break;
}
case 15: {
ret = ii15.Write(RecNo);
break;
}
case 16: {
ret = ii16.Write(RecNo);
break;
}
case 17: {
ret = ii17.Write(RecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Read(int RecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = ii11.Read(RecNo);
break;
}
case 12: {
ret = ii12.Read(RecNo);
break;
}
case 13: {
ret = ii13.Read(RecNo);
break;
}
case 14: {
ret = ii14.Read(RecNo);
break;
}
case 15: {
ret = ii15.Read(RecNo);
break;
}
case 16: {
ret = ii16.Read(RecNo);
break;
}
case 17: {
ret = ii17.Read(RecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
//public bool CanRemove() {
// bool ret;
// switch (m_version) {
// case 11: {
// ret = ii11.CanRemove();
// break;
// }
// case 12: {
// ret = ii12.CanRemove();
// break;
// }
// case 13: {
// ret = ii13.CanRemove();
// break;
// }
// case 14: {
// ret = ii14.CanRemove();
// break;
// }
// case 15: {
// ret = ii15.CanRemove();
// break;
// }
// case 16: {
// ret = ii16.CanRemove();
// break;
// }
// case 17: {
// ret = ii17.CanRemove();
// break;
// }
// default: throw new InvalidOperationException("ver");
// }
// return ret;
//}
//public bool Remove() {
// bool ret;
// switch (m_version) {
// case 11: {
// ret = ii11.Remove();
// break;
// }
// case 12: {
// ret = ii12.Remove();
// break;
// }
// case 13: {
// ret = ii13.Remove();
// break;
// }
// case 14: {
// ret = ii14.Remove();
// break;
// }
// case 15: {
// ret = ii15.Remove();
// break;
// }
// case 16: {
// ret = ii16.Remove();
// break;
// }
// case 17: {
// ret = ii17.Remove();
// break;
// }
// default: throw new InvalidOperationException("ver");
// }
// return ret;
//}
//public object Link {
// get {
// object ret;
// switch (m_version) {
// case 11: {
// ret = ii11.Link;
// break;
// }
// case 12: {
// ret = ii12.Link;
// break;
// }
// case 13: {
// ret = ii13.Link;
// break;
// }
// case 14: {
// ret = ii14.Link;
// break;
// }
// case 15: {
// ret = ii15.Link;
// break;
// }
// case 16: {
// ret = ii16.Link;
// break;
// }
// case 17: {
// ret = ii17.Link;
// break;
// }
// default: throw new InvalidOperationException("ver");
// }
// return ret;
// }
// set {
// switch (m_version) {
// case 11: {
// ii11.Link = value;
// break;
// }
// case 12: {
// ii12.Link = value;
// break;
// }
// case 13: {
// ii13.Link = value;
// break;
// }
// case 14: {
// ii14.Link = value;
// break;
// }
// case 15: {
// ii15.Link = value;
// break;
// }
// case 16: {
// ii16.Link = value;
// break;
// }
// case 17: {
// ii17.Link = value;
// break;
// }
// }
// }
//}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// 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
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class Method : CallableDefinition, IExplicitMember, INodeWithBody
{
protected Block _body;
protected LocalCollection _locals;
protected MethodImplementationFlags _implementationFlags;
protected ExplicitMemberInfo _explicitInfo;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Method CloneNode()
{
return (Method)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Method CleanClone()
{
return (Method)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.Method; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnMethod(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( Method)node;
if (_modifiers != other._modifiers) return NoMatch("Method._modifiers");
if (_name != other._name) return NoMatch("Method._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("Method._attributes");
if (!Node.AllMatch(_parameters, other._parameters)) return NoMatch("Method._parameters");
if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("Method._genericParameters");
if (!Node.Matches(_returnType, other._returnType)) return NoMatch("Method._returnType");
if (!Node.AllMatch(_returnTypeAttributes, other._returnTypeAttributes)) return NoMatch("Method._returnTypeAttributes");
if (!Node.Matches(_body, other._body)) return NoMatch("Method._body");
if (!Node.AllMatch(_locals, other._locals)) return NoMatch("Method._locals");
if (_implementationFlags != other._implementationFlags) return NoMatch("Method._implementationFlags");
if (!Node.Matches(_explicitInfo, other._explicitInfo)) return NoMatch("Method._explicitInfo");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_parameters != null)
{
ParameterDeclaration item = existing as ParameterDeclaration;
if (null != item)
{
ParameterDeclaration newItem = (ParameterDeclaration)newNode;
if (_parameters.Replace(item, newItem))
{
return true;
}
}
}
if (_genericParameters != null)
{
GenericParameterDeclaration item = existing as GenericParameterDeclaration;
if (null != item)
{
GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode;
if (_genericParameters.Replace(item, newItem))
{
return true;
}
}
}
if (_returnType == existing)
{
this.ReturnType = (TypeReference)newNode;
return true;
}
if (_returnTypeAttributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_returnTypeAttributes.Replace(item, newItem))
{
return true;
}
}
}
if (_body == existing)
{
this.Body = (Block)newNode;
return true;
}
if (_locals != null)
{
Local item = existing as Local;
if (null != item)
{
Local newItem = (Local)newNode;
if (_locals.Replace(item, newItem))
{
return true;
}
}
}
if (_explicitInfo == existing)
{
this.ExplicitInfo = (ExplicitMemberInfo)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
Method clone = (Method)FormatterServices.GetUninitializedObject(typeof(Method));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _parameters)
{
clone._parameters = _parameters.Clone() as ParameterDeclarationCollection;
clone._parameters.InitializeParent(clone);
}
if (null != _genericParameters)
{
clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection;
clone._genericParameters.InitializeParent(clone);
}
if (null != _returnType)
{
clone._returnType = _returnType.Clone() as TypeReference;
clone._returnType.InitializeParent(clone);
}
if (null != _returnTypeAttributes)
{
clone._returnTypeAttributes = _returnTypeAttributes.Clone() as AttributeCollection;
clone._returnTypeAttributes.InitializeParent(clone);
}
if (null != _body)
{
clone._body = _body.Clone() as Block;
clone._body.InitializeParent(clone);
}
if (null != _locals)
{
clone._locals = _locals.Clone() as LocalCollection;
clone._locals.InitializeParent(clone);
}
clone._implementationFlags = _implementationFlags;
if (null != _explicitInfo)
{
clone._explicitInfo = _explicitInfo.Clone() as ExplicitMemberInfo;
clone._explicitInfo.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _parameters)
{
_parameters.ClearTypeSystemBindings();
}
if (null != _genericParameters)
{
_genericParameters.ClearTypeSystemBindings();
}
if (null != _returnType)
{
_returnType.ClearTypeSystemBindings();
}
if (null != _returnTypeAttributes)
{
_returnTypeAttributes.ClearTypeSystemBindings();
}
if (null != _body)
{
_body.ClearTypeSystemBindings();
}
if (null != _locals)
{
_locals.ClearTypeSystemBindings();
}
if (null != _explicitInfo)
{
_explicitInfo.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Block Body
{
get
{
if (_body == null)
{
_body = new Block();
_body.InitializeParent(this);
}
return _body;
}
set
{
if (_body != value)
{
_body = value;
if (null != _body)
{
_body.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(Local))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public LocalCollection Locals
{
get { return _locals ?? (_locals = new LocalCollection(this)); }
set
{
if (_locals != value)
{
_locals = value;
if (null != _locals)
{
_locals.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public MethodImplementationFlags ImplementationFlags
{
get { return _implementationFlags; }
set { _implementationFlags = value; }
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ExplicitMemberInfo ExplicitInfo
{
get { return _explicitInfo; }
set
{
if (_explicitInfo != value)
{
_explicitInfo = value;
if (null != _explicitInfo)
{
_explicitInfo.InitializeParent(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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace MS.Internal.Xml.XPath
{
internal sealed class SortQuery : Query
{
private List<SortKey> _results;
private XPathSortComparer _comparer;
private Query _qyInput;
public SortQuery(Query qyInput)
{
Debug.Assert(qyInput != null, "Sort Query needs an input query tree to work on");
_results = new List<SortKey>();
_comparer = new XPathSortComparer();
_qyInput = qyInput;
count = 0;
}
private SortQuery(SortQuery other) : base(other)
{
_results = new List<SortKey>(other._results);
_comparer = other._comparer.Clone();
_qyInput = Clone(other._qyInput);
count = 0;
}
public override void Reset() { count = 0; }
public override void SetXsltContext(XsltContext xsltContext)
{
_qyInput.SetXsltContext(xsltContext);
if (
_qyInput.StaticType != XPathResultType.NodeSet &&
_qyInput.StaticType != XPathResultType.Any
)
{
throw XPathException.Create(SR.Xp_NodeSetExpected);
}
}
private void BuildResultsList()
{
int numSorts = _comparer.NumSorts;
Debug.Assert(numSorts > 0, "Why was the sort query created?");
XPathNavigator eNext;
while ((eNext = _qyInput.Advance()) != null)
{
SortKey key = new SortKey(numSorts, /*originalPosition:*/_results.Count, eNext.Clone());
for (int j = 0; j < numSorts; j++)
{
key[j] = _comparer.Expression(j).Evaluate(_qyInput);
}
_results.Add(key);
}
_results.Sort(_comparer);
}
public override object Evaluate(XPathNodeIterator context)
{
_qyInput.Evaluate(context);
_results.Clear();
BuildResultsList();
count = 0;
return this;
}
public override XPathNavigator Advance()
{
Debug.Assert(0 <= count && count <= _results.Count);
if (count < _results.Count)
{
return _results[count++].Node;
}
return null;
}
public override XPathNavigator Current
{
get
{
Debug.Assert(0 <= count && count <= _results.Count);
if (count == 0)
{
return null;
}
return _results[count - 1].Node;
}
}
internal void AddSort(Query evalQuery, IComparer comparer)
{
_comparer.AddSort(evalQuery, comparer);
}
public override XPathNodeIterator Clone() { return new SortQuery(this); }
public override XPathResultType StaticType { get { return XPathResultType.NodeSet; } }
public override int CurrentPosition { get { return count; } }
public override int Count { get { return _results.Count; } }
public override QueryProps Properties { get { return QueryProps.Cached | QueryProps.Position | QueryProps.Count; } }
} // class SortQuery
internal sealed class SortKey
{
private int _numKeys;
private object[] _keys;
private int _originalPosition;
private XPathNavigator _node;
public SortKey(int numKeys, int originalPosition, XPathNavigator node)
{
_numKeys = numKeys;
_keys = new object[numKeys];
_originalPosition = originalPosition;
_node = node;
}
public object this[int index]
{
get { return _keys[index]; }
set { _keys[index] = value; }
}
public int NumKeys { get { return _numKeys; } }
public int OriginalPosition { get { return _originalPosition; } }
public XPathNavigator Node { get { return _node; } }
} // class SortKey
internal sealed class XPathSortComparer : IComparer<SortKey>
{
private const int minSize = 3;
private Query[] _expressions;
private IComparer[] _comparers;
private int _numSorts;
public XPathSortComparer(int size)
{
if (size <= 0) size = minSize;
_expressions = new Query[size];
_comparers = new IComparer[size];
}
public XPathSortComparer() : this(minSize) { }
public void AddSort(Query evalQuery, IComparer comparer)
{
Debug.Assert(_expressions.Length == _comparers.Length);
Debug.Assert(0 < _expressions.Length);
Debug.Assert(0 <= _numSorts && _numSorts <= _expressions.Length);
// Adjust array sizes if needed.
if (_numSorts == _expressions.Length)
{
Query[] newExpressions = new Query[_numSorts * 2];
IComparer[] newComparers = new IComparer[_numSorts * 2];
for (int i = 0; i < _numSorts; i++)
{
newExpressions[i] = _expressions[i];
newComparers[i] = _comparers[i];
}
_expressions = newExpressions;
_comparers = newComparers;
}
Debug.Assert(_numSorts < _expressions.Length);
// Fixup expression to handle node-set return type:
if (evalQuery.StaticType == XPathResultType.NodeSet || evalQuery.StaticType == XPathResultType.Any)
{
evalQuery = new StringFunctions(Function.FunctionType.FuncString, new Query[] { evalQuery });
}
_expressions[_numSorts] = evalQuery;
_comparers[_numSorts] = comparer;
_numSorts++;
}
public int NumSorts { get { return _numSorts; } }
public Query Expression(int i)
{
return _expressions[i];
}
int IComparer<SortKey>.Compare(SortKey x, SortKey y)
{
Debug.Assert(x != null && y != null, "Oops!! what happened?");
int result = 0;
for (int i = 0; i < x.NumKeys; i++)
{
result = _comparers[i].Compare(x[i], y[i]);
if (result != 0)
{
return result;
}
}
// if after all comparisons, the two sort keys are still equal, preserve the doc order
return x.OriginalPosition - y.OriginalPosition;
}
internal XPathSortComparer Clone()
{
XPathSortComparer clone = new XPathSortComparer(_numSorts);
for (int i = 0; i < _numSorts; i++)
{
clone._comparers[i] = _comparers[i];
clone._expressions[i] = (Query)_expressions[i].Clone(); // Expressions should be cloned because Query should be cloned
}
clone._numSorts = _numSorts;
return clone;
}
} // class XPathSortComparer
} // namespace
| |
/*
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
*************************************************************************
*/
using System;
using System.Text;
using HANDLE = System.IntPtr;
using i16 = System.Int16;
using sqlite3_int64 = System.Int64;
using u32 = System.UInt32;
namespace System.Data.SQLite
{
using DbPage = Sqlite3.PgHdr;
using sqlite3_pcache = Sqlite3.PCache1;
using sqlite3_stmt = Sqlite3.Vdbe;
using sqlite3_value = Sqlite3.Mem;
internal partial class Sqlite3
{
public delegate void dxAuth(object pAuthArg, int b, string c, string d, string e, string f);
public delegate int dxBusy(object pBtShared, int iValue);
public delegate void dxFreeAux(object pAuxArg);
public delegate int dxCallback(object pCallbackArg, sqlite3_int64 argc, object p2, object p3);
public delegate void dxalarmCallback(object pNotUsed, sqlite3_int64 iNotUsed, int size);
public delegate void dxCollNeeded(object pCollNeededArg, sqlite3 db, int eTextRep, string collationName);
public delegate int dxCommitCallback(object pCommitArg);
public delegate int dxCompare(object pCompareArg, int size1, string Key1, int size2, string Key2);
public delegate bool dxCompare4(string Key1, int size1, string Key2, int size2);
public delegate void dxDel(ref string pDelArg); // needs ref
public delegate void dxDelCollSeq(ref object pDelArg); // needs ref
public delegate void dxLog(object pLogArg, int i, string msg);
public delegate void dxLogcallback(object pCallbackArg, int argc, string p2);
public delegate void dxProfile(object pProfileArg, string msg, sqlite3_int64 time);
public delegate int dxProgress(object pProgressArg);
public delegate void dxRollbackCallback(object pRollbackArg);
public delegate void dxTrace(object pTraceArg, string msg);
public delegate void dxUpdateCallback(object pUpdateArg, int b, string c, string d, sqlite3_int64 e);
public delegate int dxWalCallback(object pWalArg, sqlite3 db, string zDb, int nEntry);
/*
* FUNCTIONS
*
*/
public delegate void dxFunc(sqlite3_context ctx, int intValue, sqlite3_value[] value);
public delegate void dxStep(sqlite3_context ctx, int intValue, sqlite3_value[] value);
public delegate void dxFinal(sqlite3_context ctx);
public delegate void dxFDestroy(object pArg);
//
public delegate string dxColname(sqlite3_value pVal);
public delegate int dxFuncBtree(Btree p);
public delegate int dxExprTreeFunction(ref int pArg, Expr pExpr);
public delegate int dxExprTreeFunction_NC(NameContext pArg, ref Expr pExpr);
public delegate int dxExprTreeFunction_OBJ(object pArg, Expr pExpr);
/*
VFS Delegates
*/
public delegate int dxClose(sqlite3_file File_ID);
public delegate int dxCheckReservedLock(sqlite3_file File_ID, ref int pRes);
public delegate int dxDeviceCharacteristics(sqlite3_file File_ID);
public delegate int dxFileControl(sqlite3_file File_ID, int op, ref sqlite3_int64 pArgs);
public delegate int dxFileSize(sqlite3_file File_ID, ref long size);
public delegate int dxLock(sqlite3_file File_ID, int locktype);
public delegate int dxRead(sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset);
public delegate int dxSectorSize(sqlite3_file File_ID);
public delegate int dxSync(sqlite3_file File_ID, int flags);
public delegate int dxTruncate(sqlite3_file File_ID, sqlite3_int64 size);
public delegate int dxUnlock(sqlite3_file File_ID, int locktype);
public delegate int dxWrite(sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset);
public delegate int dxShmMap(sqlite3_file File_ID, int iPg, int pgsz, int pInt, out object pvolatile);
public delegate int dxShmLock(sqlite3_file File_ID, int offset, int n, int flags);
public delegate void dxShmBarrier(sqlite3_file File_ID);
public delegate int dxShmUnmap(sqlite3_file File_ID, int deleteFlag);
/*
sqlite_vfs Delegates
*/
public delegate int dxOpen(sqlite3_vfs vfs, string zName, sqlite3_file db, int flags, out int pOutFlags);
public delegate int dxDelete(sqlite3_vfs vfs, string zName, int syncDir);
public delegate int dxAccess(sqlite3_vfs vfs, string zName, int flags, out int pResOut);
public delegate int dxFullPathname(sqlite3_vfs vfs, string zName, int nOut, StringBuilder zOut);
public delegate HANDLE dxDlOpen(sqlite3_vfs vfs, string zFilename);
public delegate int dxDlError(sqlite3_vfs vfs, int nByte, string zErrMsg);
public delegate HANDLE dxDlSym(sqlite3_vfs vfs, HANDLE data, string zSymbol);
public delegate int dxDlClose(sqlite3_vfs vfs, HANDLE data);
public delegate int dxRandomness(sqlite3_vfs vfs, int nByte, byte[] buffer);
public delegate int dxSleep(sqlite3_vfs vfs, int microseconds);
public delegate int dxCurrentTime(sqlite3_vfs vfs, ref double currenttime);
public delegate int dxGetLastError(sqlite3_vfs pVfs, int nBuf, ref string zBuf);
public delegate int dxCurrentTimeInt64(sqlite3_vfs pVfs, ref sqlite3_int64 pTime);
public delegate int dxSetSystemCall(sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr);
public delegate int dxGetSystemCall(sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr);
public delegate int dxNextSystemCall(sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr);
/*
* Pager Delegates
*/
public delegate void dxDestructor(DbPage dbPage); /* Call this routine when freeing pages */
public delegate int dxBusyHandler(object pBusyHandlerArg);
public delegate void dxReiniter(DbPage dbPage); /* Call this routine when reloading pages */
public delegate void dxFreeSchema(Schema schema);
#if SQLITE_HAS_CODEC
public delegate byte[] dxCodec( codec_ctx pCodec, byte[] D, uint pageNumber, int X ); //void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
public delegate void dxCodecSizeChng( codec_ctx pCodec, int pageSize, i16 nReserve ); //void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
public delegate void dxCodecFree( ref codec_ctx pCodec ); //void (*xCodecFree)(void); /* Destructor for the codec */
#endif
//Module
public delegate void dxDestroy(ref PgHdr pDestroyArg);
public delegate int dxStress(object obj, PgHdr pPhHdr);
//sqlite3_module
public delegate int smdxCreateConnect(sqlite3 db, object pAux, int argc, string[] constargv, out sqlite3_vtab ppVTab, out string pError);
public delegate int smdxBestIndex(sqlite3_vtab pVTab, ref sqlite3_index_info pIndex);
public delegate int smdxDisconnect(ref object pVTab);
public delegate int smdxDestroy(ref object pVTab);
public delegate int smdxOpen(sqlite3_vtab pVTab, out sqlite3_vtab_cursor ppCursor);
public delegate int smdxClose(ref sqlite3_vtab_cursor pCursor);
public delegate int smdxFilter(sqlite3_vtab_cursor pCursor, int idxNum, string idxStr, int argc, sqlite3_value[] argv);
public delegate int smdxNext(sqlite3_vtab_cursor pCursor);
public delegate int smdxEof(sqlite3_vtab_cursor pCursor);
public delegate int smdxColumn(sqlite3_vtab_cursor pCursor, sqlite3_context p2, int p3);
public delegate int smdxRowid(sqlite3_vtab_cursor pCursor, out sqlite3_int64 pRowid);
public delegate int smdxUpdate(sqlite3_vtab pVTab, int p1, sqlite3_value[] p2, out sqlite3_int64 p3);
public delegate int smdxFunction(sqlite3_vtab pVTab);
public delegate int smdxFindFunction(sqlite3_vtab pVtab, int nArg, string zName, ref dxFunc pxFunc, ref object ppArg);
public delegate int smdxRename(sqlite3_vtab pVtab, string zNew);
public delegate int smdxFunctionArg(sqlite3_vtab pVTab, int nArg);
//AutoExtention
public delegate int dxInit(sqlite3 db, ref string zMessage, sqlite3_api_routines sar);
#if !SQLITE_OMIT_VIRTUALTABLE
public delegate int dmxCreate(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7);
public delegate int dmxConnect(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7);
public delegate int dmxBestIndex(sqlite3_vtab pVTab, ref sqlite3_index_info pIndexInfo);
public delegate int dmxDisconnect(sqlite3_vtab pVTab);
public delegate int dmxDestroy(sqlite3_vtab pVTab);
public delegate int dmxOpen(sqlite3_vtab pVTab, sqlite3_vtab_cursor ppCursor);
public delegate int dmxClose(sqlite3_vtab_cursor pCursor);
public delegate int dmxFilter(sqlite3_vtab_cursor pCursor, int idmxNum, string idmxStr, int argc, sqlite3_value argv);
public delegate int dmxNext(sqlite3_vtab_cursor pCursor);
public delegate int dmxEof(sqlite3_vtab_cursor pCursor);
public delegate int dmxColumn(sqlite3_vtab_cursor pCursor, sqlite3_context ctx, int i3);
public delegate int dmxRowid(sqlite3_vtab_cursor pCursor, sqlite3_int64 pRowid);
public delegate int dmxUpdate(sqlite3_vtab pVTab, int i2, sqlite3_value sv3, sqlite3_int64 v4);
public delegate int dmxBegin(sqlite3_vtab pVTab);
public delegate int dmxSync(sqlite3_vtab pVTab);
public delegate int dmxCommit(sqlite3_vtab pVTab);
public delegate int dmxRollback(sqlite3_vtab pVTab);
public delegate int dmxFindFunction(sqlite3_vtab pVtab, int nArg, string zName);
public delegate int dmxRename(sqlite3_vtab pVtab, string zNew);
#endif
//Faults
public delegate void void_function();
//Mem Methods
public delegate int dxMemInit(object o);
public delegate void dxMemShutdown(object o);
public delegate byte[] dxMalloc(int nSize);
public delegate int[] dxMallocInt(int nSize);
public delegate Mem dxMallocMem(Mem pMem);
public delegate void dxFree(ref byte[] pOld);
public delegate void dxFreeInt(ref int[] pOld);
public delegate void dxFreeMem(ref Mem pOld);
public delegate byte[] dxRealloc(byte[] pOld, int nSize);
public delegate int dxSize(byte[] pArray);
public delegate int dxRoundup(int nSize);
//Mutex Methods
public delegate int dxMutexInit();
public delegate int dxMutexEnd();
public delegate sqlite3_mutex dxMutexAlloc(int iNumber);
public delegate void dxMutexFree(sqlite3_mutex sm);
public delegate void dxMutexEnter(sqlite3_mutex sm);
public delegate int dxMutexTry(sqlite3_mutex sm);
public delegate void dxMutexLeave(sqlite3_mutex sm);
public delegate bool dxMutexHeld(sqlite3_mutex sm);
public delegate bool dxMutexNotheld(sqlite3_mutex sm);
public delegate object dxColumn(sqlite3_stmt pStmt, int i);
public delegate int dxColumn_I(sqlite3_stmt pStmt, int i);
// Walker Methods
public delegate int dxExprCallback(Walker W, ref Expr E); /* Callback for expressions */
public delegate int dxSelectCallback(Walker W, Select S); /* Callback for SELECTs */
// pcache Methods
public delegate int dxPC_Init(object NotUsed);
public delegate void dxPC_Shutdown(object NotUsed);
public delegate sqlite3_pcache dxPC_Create(int szPage, bool bPurgeable);
public delegate void dxPC_Cachesize(sqlite3_pcache pCache, int nCachesize);
public delegate int dxPC_Pagecount(sqlite3_pcache pCache);
public delegate PgHdr dxPC_Fetch(sqlite3_pcache pCache, u32 key, int createFlag);
public delegate void dxPC_Unpin(sqlite3_pcache pCache, PgHdr p2, bool discard);
public delegate void dxPC_Rekey(sqlite3_pcache pCache, PgHdr p2, u32 oldKey, u32 newKey);
public delegate void dxPC_Truncate(sqlite3_pcache pCache, u32 iLimit);
public delegate void dxPC_Destroy(ref sqlite3_pcache pCache);
public delegate void dxIter(PgHdr p);
#if NET_35 || NET_40
//API Simplifications -- Actions
public static Action<sqlite3_context, String, Int32, dxDel> ResultBlob = sqlite3_result_blob;
public static Action<sqlite3_context, Double> ResultDouble = sqlite3_result_double;
public static Action<sqlite3_context, String, Int32> ResultError = sqlite3_result_error;
public static Action<sqlite3_context, Int32> ResultErrorCode = sqlite3_result_error_code;
public static Action<sqlite3_context> ResultErrorNoMem = sqlite3_result_error_nomem;
public static Action<sqlite3_context> ResultErrorTooBig = sqlite3_result_error_toobig;
public static Action<sqlite3_context, Int32> ResultInt = sqlite3_result_int;
public static Action<sqlite3_context, Int64> ResultInt64 = sqlite3_result_int64;
public static Action<sqlite3_context> ResultNull = sqlite3_result_null;
public static Action<sqlite3_context, String, Int32, dxDel> ResultText = sqlite3_result_text;
public static Action<sqlite3_context, String, Int32, Int32, dxDel> ResultText_Offset = sqlite3_result_text;
public static Action<sqlite3_context, sqlite3_value> ResultValue = sqlite3_result_value;
public static Action<sqlite3_context, Int32> ResultZeroblob = sqlite3_result_zeroblob;
public static Action<sqlite3_context, Int32, String> SetAuxdata = sqlite3_set_auxdata;
//API Simplifications -- Functions
public delegate Int32 FinalizeDelegate( sqlite3_stmt pStmt );
public static FinalizeDelegate Finalize = sqlite3_finalize;
public static Func<sqlite3_stmt, Int32> ClearBindings = sqlite3_clear_bindings;
public static Func<sqlite3_stmt, Int32, Byte[]> ColumnBlob = sqlite3_column_blob;
public static Func<sqlite3_stmt, Int32, Int32> ColumnBytes = sqlite3_column_bytes;
public static Func<sqlite3_stmt, Int32, Int32> ColumnBytes16 = sqlite3_column_bytes16;
public static Func<sqlite3_stmt, Int32> ColumnCount = sqlite3_column_count;
public static Func<sqlite3_stmt, Int32, String> ColumnDecltype = sqlite3_column_decltype;
public static Func<sqlite3_stmt, Int32, Double> ColumnDouble = sqlite3_column_double;
public static Func<sqlite3_stmt, Int32, Int32> ColumnInt = sqlite3_column_int;
public static Func<sqlite3_stmt, Int32, Int64> ColumnInt64 = sqlite3_column_int64;
public static Func<sqlite3_stmt, Int32, String> ColumnName = sqlite3_column_name;
public static Func<sqlite3_stmt, Int32, String> ColumnText = sqlite3_column_text;
public static Func<sqlite3_stmt, Int32, Int32> ColumnType = sqlite3_column_type;
public static Func<sqlite3_stmt, Int32, sqlite3_value> ColumnValue = sqlite3_column_value;
public static Func<sqlite3_stmt, Int32> DataCount = sqlite3_data_count;
public static Func<sqlite3_stmt, Int32> Reset = sqlite3_reset;
public static Func<sqlite3_stmt, Int32> Step = sqlite3_step;
public static Func<sqlite3_stmt, Int32, Byte[], Int32, dxDel, Int32> BindBlob = sqlite3_bind_blob;
public static Func<sqlite3_stmt, Int32, Double, Int32> BindDouble = sqlite3_bind_double;
public static Func<sqlite3_stmt, Int32, Int32, Int32> BindInt = sqlite3_bind_int;
public static Func<sqlite3_stmt, Int32, Int64, Int32> BindInt64 = sqlite3_bind_int64;
public static Func<sqlite3_stmt, Int32, Int32> BindNull = sqlite3_bind_null;
public static Func<sqlite3_stmt, Int32> BindParameterCount = sqlite3_bind_parameter_count;
public static Func<sqlite3_stmt, String, Int32> BindParameterIndex = sqlite3_bind_parameter_index;
public static Func<sqlite3_stmt, Int32, String> BindParameterName = sqlite3_bind_parameter_name;
public static Func<sqlite3_stmt, Int32, String, Int32, dxDel, Int32> BindText = sqlite3_bind_text;
public static Func<sqlite3_stmt, Int32, sqlite3_value, Int32> BindValue = sqlite3_bind_value;
public static Func<sqlite3_stmt, Int32, Int32, Int32> BindZeroblob = sqlite3_bind_zeroblob;
public delegate Int32 OpenDelegate( string zFilename, out sqlite3 ppDb );
public static Func<sqlite3, Int32> Close = sqlite3_close;
public static Func<sqlite3_stmt, sqlite3> DbHandle = sqlite3_db_handle;
public static Func<sqlite3, String> Errmsg = sqlite3_errmsg;
public static OpenDelegate Open = sqlite3_open;
public static Func<sqlite3, sqlite3_stmt, sqlite3_stmt> NextStmt = sqlite3_next_stmt;
public static Func<Int32> Shutdown = sqlite3_shutdown;
public static Func<sqlite3_stmt, Int32, Int32, Int32> StmtStatus = sqlite3_stmt_status;
public delegate Int32 PrepareDelegate( sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, ref string pzTail );
public delegate Int32 PrepareDelegateNoTail( sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, Int32 iDummy );
public static PrepareDelegate Prepare = sqlite3_prepare;
public static PrepareDelegate PrepareV2 = sqlite3_prepare_v2;
public static PrepareDelegateNoTail PrepareV2NoTail = sqlite3_prepare_v2;
public static Func<sqlite3_context, Int32, Mem> AggregateContext = sqlite3_aggregate_context;
public static Func<sqlite3_context, Int32, Object> GetAuxdata = sqlite3_get_auxdata;
public static Func<sqlite3_context, sqlite3> ContextDbHandle = sqlite3_context_db_handle;
public static Func<sqlite3_context, Object> UserData = sqlite3_user_data;
public static Func<sqlite3_value, Byte[]> ValueBlob = sqlite3_value_blob;
public static Func<sqlite3_value, Int32> ValueBytes = sqlite3_value_bytes;
public static Func<sqlite3_value, Int32> ValueBytes16 = sqlite3_value_bytes16;
public static Func<sqlite3_value, Double> ValueDouble = sqlite3_value_double;
public static Func<sqlite3_value, Int32> ValueInt = sqlite3_value_int;
public static Func<sqlite3_value, Int64> ValueInt64 = sqlite3_value_int64;
public static Func<sqlite3_value, String> ValueText = sqlite3_value_text;
public static Func<sqlite3_value, Int32> ValueType = sqlite3_value_type;
#endif
}
}
#if( NET_35 && !NET_40) || WINDOWS_PHONE
namespace System
{
// Summary:
// Encapsulates a method that has four parameters and does not return a value.
//
// Parameters:
// arg1:
// The first parameter of the method that this delegate encapsulates.
//
// arg2:
// The second parameter of the method that this delegate encapsulates.
//
// arg3:
// The third parameter of the method that this delegate encapsulates.
//
// arg4:
// The fourth parameter of the method that this delegate encapsulates.
//
// arg5:
// The fifth parameter of the method that this delegate encapsulates.
//
// Type parameters:
// T1:
// The type of the first parameter of the method that this delegate encapsulates.
//
// T2:
// The type of the second parameter of the method that this delegate encapsulates.
//
// T3:
// The type of the third parameter of the method that this delegate encapsulates.
//
// T4:
// The type of the fourth parameter of the method that this delegate encapsulates.
//
// T5:
// The type of the fifth parameter of the method that this delegate encapsulates.
public delegate void Action<T1, T2, T3, T4, T5>( T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5 );
// Summary:
// Encapsulates a method that has three parameters and returns a value of the
// type specified by the TResult parameter.
//
// Parameters:
// arg1:
// The first parameter of the method that this delegate encapsulates.
//
// arg2:
// The second parameter of the method that this delegate encapsulates.
//
// arg3:
// The third parameter of the method that this delegate encapsulates.
//
// arg4:
// The fourth parameter of the method that this delegate encapsulates.
//
// arg5:
// The fifth parameter of the method that this delegate encapsulates.
//
// Type parameters:
// T1:
// The type of the first parameter of the method that this delegate encapsulates.
//
// T2:
// The type of the second parameter of the method that this delegate encapsulates.
//
// T3:
// The type of the third parameter of the method that this delegate encapsulates.
//
// T4:
// The type of the fourth parameter of the method that this delegate encapsulates.
//
// T5:
// The type of the fifth parameter of the method that this delegate encapsulates.
//
// TResult:
// The type of the return value of the method that this delegate encapsulates.
//
// Returns:
// The return value of the method that this delegate encapsulates.
public delegate TResult Func<T1, T2, T3, T4, TResult>( T1 arg1, T2 arg2, T3 arg3, T4 arg4 );
public delegate TResult Func<T1, T2, T3, T4, T5, TResult>( T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5 );
}
#endif
| |
using System;
using System.Collections;
using System.Globalization;
using System.Security.Principal;
using System.Web;
using System.Web.Caching;
using System.Web.Profile;
namespace Coevery.Mvc.Wrappers {
public abstract class HttpContextBaseWrapper : HttpContextBase {
protected readonly HttpContextBase _httpContextBase;
protected HttpContextBaseWrapper(HttpContextBase httpContextBase) {
_httpContextBase = httpContextBase;
}
public override void AddError(Exception errorInfo) {
_httpContextBase.AddError(errorInfo);
}
public override void ClearError() {
_httpContextBase.ClearError();
}
public override object GetGlobalResourceObject(string classKey, string resourceKey) {
return _httpContextBase.GetGlobalResourceObject(classKey, resourceKey);
}
public override object GetGlobalResourceObject(string classKey, string resourceKey, CultureInfo culture) {
return _httpContextBase.GetGlobalResourceObject(classKey, resourceKey, culture);
}
public override object GetLocalResourceObject(string virtualPath, string resourceKey) {
return _httpContextBase.GetLocalResourceObject(virtualPath, resourceKey);
}
public override object GetLocalResourceObject(string virtualPath, string resourceKey, CultureInfo culture) {
return _httpContextBase.GetLocalResourceObject(virtualPath, resourceKey, culture);
}
public override object GetSection(string sectionName) {
return _httpContextBase.GetSection(sectionName);
}
public override object GetService(Type serviceType) {
return ((IServiceProvider)_httpContextBase).GetService(serviceType);
}
public override void RewritePath(string path) {
_httpContextBase.RewritePath(path);
}
public override void RewritePath(string path, bool rebaseClientPath) {
_httpContextBase.RewritePath(path, rebaseClientPath);
}
public override void RewritePath(string filePath, string pathInfo, string queryString) {
_httpContextBase.RewritePath(filePath, pathInfo, queryString);
}
public override void RewritePath(string filePath, string pathInfo, string queryString, bool setClientFilePath) {
_httpContextBase.RewritePath(filePath, pathInfo, queryString, setClientFilePath);
}
public override Exception[] AllErrors {
get {
return _httpContextBase.AllErrors;
}
}
public override HttpApplicationStateBase Application {
get {
return _httpContextBase.Application;
}
}
public override HttpApplication ApplicationInstance {
get {
return _httpContextBase.ApplicationInstance;
}
set {
_httpContextBase.ApplicationInstance = value;
}
}
public override Cache Cache {
get {
return _httpContextBase.Cache;
}
}
public override IHttpHandler CurrentHandler {
get {
return _httpContextBase.CurrentHandler;
}
}
public override RequestNotification CurrentNotification {
get {
return _httpContextBase.CurrentNotification;
}
}
public override Exception Error {
get {
return _httpContextBase.Error;
}
}
public override IHttpHandler Handler {
get {
return _httpContextBase.Handler;
}
set {
_httpContextBase.Handler = value;
}
}
public override bool IsCustomErrorEnabled {
get {
return _httpContextBase.IsCustomErrorEnabled;
}
}
public override bool IsDebuggingEnabled {
get {
return _httpContextBase.IsDebuggingEnabled;
}
}
public override bool IsPostNotification {
get {
return _httpContextBase.IsDebuggingEnabled;
}
}
public override IDictionary Items {
get {
return _httpContextBase.Items;
}
}
public override IHttpHandler PreviousHandler {
get {
return _httpContextBase.PreviousHandler;
}
}
public override ProfileBase Profile {
get {
return _httpContextBase.Profile;
}
}
public override HttpRequestBase Request {
get {
return _httpContextBase.Request;
}
}
public override HttpResponseBase Response {
get {
return _httpContextBase.Response;
}
}
public override HttpServerUtilityBase Server {
get {
return _httpContextBase.Server;
}
}
public override HttpSessionStateBase Session {
get {
return _httpContextBase.Session;
}
}
public override bool SkipAuthorization {
get {
return _httpContextBase.SkipAuthorization;
}
set {
_httpContextBase.SkipAuthorization = value;
}
}
public override DateTime Timestamp {
get {
return _httpContextBase.Timestamp;
}
}
public override TraceContext Trace {
get {
return _httpContextBase.Trace;
}
}
public override IPrincipal User {
get {
return _httpContextBase.User;
}
set {
_httpContextBase.User = value;
}
}
}
}
| |
// <copyright file="SafariDriverServer.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Safari.Internal;
namespace OpenQA.Selenium.Safari
{
/// <summary>
/// Provides the WebSockets server for communicating with the Safari extension.
/// </summary>
public class SafariDriverServer : ICommandServer
{
private WebSocketServer webSocketServer;
private Queue<SafariDriverConnection> connections = new Queue<SafariDriverConnection>();
private Uri serverUri;
private string temporaryDirectoryPath;
private string safariExecutableLocation;
private Process safariProcess;
private SafariDriverConnection connection;
/// <summary>
/// Initializes a new instance of the <see cref="SafariDriverServer"/> class using the specified options.
/// </summary>
/// <param name="options">The <see cref="SafariOptions"/> defining the browser settings.</param>
public SafariDriverServer(SafariOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options", "options must not be null");
}
int webSocketPort = options.Port;
if (webSocketPort == 0)
{
webSocketPort = PortUtilities.FindFreePort();
}
this.webSocketServer = new WebSocketServer(webSocketPort, "ws://localhost/wd");
this.webSocketServer.Opened += new EventHandler<ConnectionEventArgs>(this.ServerOpenedEventHandler);
this.webSocketServer.Closed += new EventHandler<ConnectionEventArgs>(this.ServerClosedEventHandler);
this.webSocketServer.StandardHttpRequestReceived += new EventHandler<StandardHttpRequestReceivedEventArgs>(this.ServerStandardHttpRequestReceivedEventHandler);
this.serverUri = new Uri(string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}/", webSocketPort.ToString(CultureInfo.InvariantCulture)));
if (string.IsNullOrEmpty(options.SafariLocation))
{
this.safariExecutableLocation = GetDefaultSafariLocation();
}
else
{
this.safariExecutableLocation = options.SafariLocation;
}
}
/// <summary>
/// Starts the server.
/// </summary>
public void Start()
{
this.webSocketServer.Start();
string connectFileName = this.PrepareConnectFile();
this.LaunchSafariProcess(connectFileName);
this.connection = this.WaitForConnection(TimeSpan.FromSeconds(45));
this.DeleteConnectFile();
if (this.connection == null)
{
throw new WebDriverException("Did not receive a connection from the Safari extension. Please verify that it is properly installed and is the proper version.");
}
}
/// <summary>
/// Sends a command to the server.
/// </summary>
/// <param name="commandToSend">The <see cref="Command"/> to send.</param>
/// <returns>The command <see cref="Response"/>.</returns>
public Response SendCommand(Command commandToSend)
{
return this.connection.Send(commandToSend);
}
/// <summary>
/// Waits for a connection to be established with the server by the Safari browser extension.
/// </summary>
/// <param name="timeout">A <see cref="TimeSpan"/> containing the amount of time to wait for the connection.</param>
/// <returns>A <see cref="SafariDriverConnection"/> representing the connection to the browser.</returns>
public SafariDriverConnection WaitForConnection(TimeSpan timeout)
{
SafariDriverConnection foundConnection = null;
DateTime end = DateTime.Now.Add(timeout);
while (this.connections.Count == 0 && DateTime.Now < end)
{
Thread.Sleep(250);
}
if (this.connections.Count > 0)
{
foundConnection = this.connections.Dequeue();
}
return foundConnection;
}
/// <summary>
/// Releases all resources used by the <see cref="SafariDriverServer"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="SafariDriverServer"/> and optionally
/// releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release managed and resources;
/// <see langword="false"/> to only release unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.webSocketServer.Dispose();
if (this.safariProcess != null)
{
this.CloseSafariProcess();
this.safariProcess.Dispose();
}
}
}
private static string GetDefaultSafariLocation()
{
string safariPath = string.Empty;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
// Safari remains a 32-bit application. Use a hack to look for it
// in the 32-bit program files directory. If a 64-bit version of
// Safari for Windows is released, this needs to be revisited.
string programFilesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
if (Directory.Exists(programFilesDirectory + " (x86)"))
{
programFilesDirectory += " (x86)";
}
safariPath = Path.Combine(programFilesDirectory, Path.Combine("Safari", "safari.exe"));
}
else
{
safariPath = "/Applications/Safari.app/Contents/MacOS/Safari";
}
return safariPath;
}
[SecurityPermission(SecurityAction.Demand)]
private void LaunchSafariProcess(string initialPage)
{
this.safariProcess = new Process();
this.safariProcess.StartInfo.FileName = this.safariExecutableLocation;
this.safariProcess.StartInfo.Arguments = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", initialPage);
this.safariProcess.Start();
}
[SecurityPermission(SecurityAction.Demand)]
private void CloseSafariProcess()
{
if (this.safariProcess != null && !this.safariProcess.HasExited)
{
this.safariProcess.Kill();
while (!this.safariProcess.HasExited)
{
Thread.Sleep(250);
}
}
}
private string PrepareConnectFile()
{
string directoryName = FileUtilities.GenerateRandomTempDirectoryName("SafariDriverConnect.{0}");
this.temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), directoryName);
string tempFileName = Path.Combine(this.temporaryDirectoryPath, "connect.html");
string contents = string.Format(CultureInfo.InvariantCulture, "<!DOCTYPE html><script>window.location = '{0}';</script>", this.serverUri.ToString());
Directory.CreateDirectory(this.temporaryDirectoryPath);
using (FileStream stream = File.Create(tempFileName))
{
stream.Write(Encoding.UTF8.GetBytes(contents), 0, Encoding.UTF8.GetByteCount(contents));
}
return tempFileName;
}
private void DeleteConnectFile()
{
Directory.Delete(this.temporaryDirectoryPath, true);
}
private void ServerOpenedEventHandler(object sender, ConnectionEventArgs e)
{
this.connections.Enqueue(new SafariDriverConnection(e.Connection));
}
private void ServerClosedEventHandler(object sender, ConnectionEventArgs e)
{
}
private void ServerStandardHttpRequestReceivedEventHandler(object sender, StandardHttpRequestReceivedEventArgs e)
{
const string PageSource = @"<!DOCTYPE html>
<script>
window.onload = function() {{
window.postMessage({{
'type': 'connect',
'origin': 'webdriver',
'url': 'ws://localhost:{0}/wd'
}}, '*');
}};
</script>";
string redirectPage = string.Format(CultureInfo.InvariantCulture, PageSource, this.webSocketServer.Port.ToString(CultureInfo.InvariantCulture));
StringBuilder builder = new StringBuilder();
builder.AppendLine("HTTP/1.1 200");
builder.AppendLine("Content-Length: " + redirectPage.Length.ToString(CultureInfo.InvariantCulture));
builder.AppendLine("Connection:close");
builder.AppendLine();
builder.AppendLine(redirectPage);
e.Connection.SendRaw(builder.ToString());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Dynamic.Utils;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Runtime.CompilerServices
{
//
// A CallSite provides a fast mechanism for call-site caching of dynamic dispatch
// behavior. Each site will hold onto a delegate that provides a fast-path dispatch
// based on previous types that have been seen at the call-site. This delegate will
// call UpdateAndExecute if it is called with types that it hasn't seen before.
// Updating the binding will typically create (or lookup) a new delegate
// that supports fast-paths for both the new type and for any types that
// have been seen previously.
//
// DynamicSites will generate the fast-paths specialized for sets of runtime argument
// types. However, they will generate exactly the right amount of code for the types
// that are seen in the program so that int addition will remain as fast as it would
// be with custom implementation of the addition, and the user-defined types can be
// as fast as ints because they will all have the same optimal dynamically generated
// fast-paths.
//
// DynamicSites don't encode any particular caching policy, but use their
// CallSiteBinding to encode a caching policy.
//
/// <summary>
/// A Dynamic Call Site base class. This type is used as a parameter type to the
/// dynamic site targets. The first parameter of the delegate (T) below must be
/// of this type.
/// </summary>
public class CallSite
{
/// <summary>
/// String used for generated CallSite methods.
/// </summary>
internal const string CallSiteTargetMethodName = "CallSite.Target";
/// <summary>
/// Cache of CallSite constructors for a given delegate type.
/// </summary>
private static volatile CacheDict<Type, Func<CallSiteBinder, CallSite>> s_siteCtors;
/// <summary>
/// The Binder responsible for binding operations at this call site.
/// This binder is invoked by the UpdateAndExecute below if all Level 0,
/// Level 1 and Level 2 caches experience cache miss.
/// </summary>
internal readonly CallSiteBinder _binder;
// only CallSite<T> derives from this
internal CallSite(CallSiteBinder binder)
{
_binder = binder;
}
/// <summary>
/// Used by Matchmaker sites to indicate rule match.
/// </summary>
internal bool _match;
/// <summary>
/// Class responsible for binding dynamic operations on the dynamic site.
/// </summary>
public CallSiteBinder Binder => _binder;
/// <summary>
/// Creates a CallSite with the given delegate type and binder.
/// </summary>
/// <param name="delegateType">The CallSite delegate type.</param>
/// <param name="binder">The CallSite binder.</param>
/// <returns>The new CallSite.</returns>
public static CallSite Create(Type delegateType, CallSiteBinder binder)
{
ContractUtils.RequiresNotNull(delegateType, nameof(delegateType));
ContractUtils.RequiresNotNull(binder, nameof(binder));
if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw System.Linq.Expressions.Error.TypeMustBeDerivedFromSystemDelegate();
CacheDict<Type, Func<CallSiteBinder, CallSite>> ctors = s_siteCtors;
if (ctors == null)
{
// It's okay to just set this, worst case we're just throwing away some data
s_siteCtors = ctors = new CacheDict<Type, Func<CallSiteBinder, CallSite>>(100);
}
if (!ctors.TryGetValue(delegateType, out Func<CallSiteBinder, CallSite> ctor))
{
MethodInfo method = typeof(CallSite<>).MakeGenericType(delegateType).GetMethod(nameof(Create));
if (delegateType.IsCollectible)
{
// slow path
return (CallSite)method.Invoke(null, new object[] { binder });
}
ctor = (Func<CallSiteBinder, CallSite>)method.CreateDelegate(typeof(Func<CallSiteBinder, CallSite>));
ctors.Add(delegateType, ctor);
}
return ctor(binder);
}
}
/// <summary>
/// Dynamic site type.
/// </summary>
/// <typeparam name="T">The delegate type.</typeparam>
public class CallSite<T> : CallSite where T : class
{
/// <summary>
/// The update delegate. Called when the dynamic site experiences cache miss.
/// </summary>
/// <returns>The update delegate.</returns>
public T Update
{
get
{
// if this site is set up for match making, then use NoMatch as an Update
if (_match)
{
Debug.Assert(s_cachedNoMatch != null, "all normal sites should have Update cached once there is an instance.");
return s_cachedNoMatch;
}
else
{
Debug.Assert(s_cachedUpdate != null, "all normal sites should have Update cached once there is an instance.");
return s_cachedUpdate;
}
}
}
/// <summary>
/// The Level 0 cache - a delegate specialized based on the site history.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
public T Target;
/// <summary>
/// The Level 1 cache - a history of the dynamic site.
/// </summary>
internal T[] Rules;
/// <summary>
/// an instance of matchmaker site to opportunistically reuse when site is polymorphic
/// </summary>
internal CallSite _cachedMatchmaker;
// Cached update delegate for all sites with a given T
private static T s_cachedUpdate;
// Cached noMatch delegate for all sites with a given T
private static volatile T s_cachedNoMatch;
private CallSite(CallSiteBinder binder)
: base(binder)
{
Target = GetUpdateDelegate();
}
private CallSite()
: base(null)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
internal CallSite<T> CreateMatchMaker()
{
return new CallSite<T>();
}
internal CallSite GetMatchmaker()
{
// check if we have a cached matchmaker and attempt to atomically grab it.
var matchmaker = _cachedMatchmaker;
if (matchmaker != null)
{
matchmaker = Interlocked.Exchange(ref _cachedMatchmaker, null);
Debug.Assert(matchmaker?._match != false, "cached site should be set up for matchmaking");
}
return matchmaker ?? new CallSite<T>() { _match = true };
}
internal void ReleaseMatchmaker(CallSite matchMaker)
{
// If "Rules" has not been created, this is the first (and likely the only) Update of the site.
// 90% sites stay monomorphic and will never need a matchmaker again.
// Otherwise store the matchmaker for the future use.
if (Rules != null)
{
_cachedMatchmaker = matchMaker;
}
}
/// <summary>
/// Creates an instance of the dynamic call site, initialized with the binder responsible for the
/// runtime binding of the dynamic operations at this call site.
/// </summary>
/// <param name="binder">The binder responsible for the runtime binding of the dynamic operations at this call site.</param>
/// <returns>The new instance of dynamic call site.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
public static CallSite<T> Create(CallSiteBinder binder)
{
if (!typeof(T).IsSubclassOf(typeof(MulticastDelegate))) throw System.Linq.Expressions.Error.TypeMustBeDerivedFromSystemDelegate();
ContractUtils.RequiresNotNull(binder, nameof(binder));
return new CallSite<T>(binder);
}
private T GetUpdateDelegate()
{
// This is intentionally non-static to speed up creation - in particular MakeUpdateDelegate
// as static generic methods are more expensive than instance methods. We call a ref helper
// so we only access the generic static field once.
return GetUpdateDelegate(ref s_cachedUpdate);
}
private T GetUpdateDelegate(ref T addr)
{
if (addr == null)
{
// reduce creation cost by not using Interlocked.CompareExchange. Calling I.CE causes
// us to spend 25% of our creation time in JIT_GenericHandle. Instead we'll rarely
// create 2 delegates with no other harm caused.
addr = MakeUpdateDelegate();
}
return addr;
}
private const int MaxRules = 10;
internal void AddRule(T newRule)
{
T[] rules = Rules;
if (rules == null)
{
Rules = new[] { newRule };
return;
}
T[] temp;
if (rules.Length < (MaxRules - 1))
{
temp = new T[rules.Length + 1];
Array.Copy(rules, 0, temp, 1, rules.Length);
}
else
{
temp = new T[MaxRules];
Array.Copy(rules, 0, temp, 1, MaxRules - 1);
}
temp[0] = newRule;
Rules = temp;
}
// moves rule +2 up.
internal void MoveRule(int i)
{
if (i > 1)
{
T[] rules = Rules;
T rule = rules[i];
rules[i] = rules[i - 1];
rules[i - 1] = rules[i - 2];
rules[i - 2] = rule;
}
}
internal T MakeUpdateDelegate()
{
#if !FEATURE_COMPILE
Type target = typeof(T);
MethodInfo invoke = target.GetInvokeMethod();
s_cachedNoMatch = CreateCustomNoMatchDelegate(invoke);
return CreateCustomUpdateDelegate(invoke);
#else
Type target = typeof(T);
Type[] args;
MethodInfo invoke = target.GetInvokeMethod();
if (target.IsGenericType && IsSimpleSignature(invoke, out args))
{
MethodInfo method = null;
MethodInfo noMatchMethod = null;
if (invoke.ReturnType == typeof(void))
{
if (target == System.Linq.Expressions.Compiler.DelegateHelpers.GetActionType(args.AddFirst(typeof(CallSite))))
{
method = typeof(UpdateDelegates).GetMethod("UpdateAndExecuteVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static);
noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatchVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static);
}
}
else
{
if (target == System.Linq.Expressions.Compiler.DelegateHelpers.GetFuncType(args.AddFirst(typeof(CallSite))))
{
method = typeof(UpdateDelegates).GetMethod("UpdateAndExecute" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static);
noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatch" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static);
}
}
if (method != null)
{
s_cachedNoMatch = (T)(object)noMatchMethod.MakeGenericMethod(args).CreateDelegate(target);
return (T)(object)method.MakeGenericMethod(args).CreateDelegate(target);
}
}
s_cachedNoMatch = CreateCustomNoMatchDelegate(invoke);
return CreateCustomUpdateDelegate(invoke);
#endif
}
#if FEATURE_COMPILE
private static bool IsSimpleSignature(MethodInfo invoke, out Type[] sig)
{
ParameterInfo[] pis = invoke.GetParametersCached();
ContractUtils.Requires(pis.Length > 0 && pis[0].ParameterType == typeof(CallSite), nameof(T));
Type[] args = new Type[invoke.ReturnType != typeof(void) ? pis.Length : pis.Length - 1];
bool supported = true;
for (int i = 1; i < pis.Length; i++)
{
ParameterInfo pi = pis[i];
if (pi.IsByRefParameter())
{
supported = false;
}
args[i - 1] = pi.ParameterType;
}
if (invoke.ReturnType != typeof(void))
{
args[args.Length - 1] = invoke.ReturnType;
}
sig = args;
return supported;
}
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
private T CreateCustomUpdateDelegate(MethodInfo invoke)
{
Type returnType = invoke.GetReturnType();
bool isVoid = returnType == typeof(void);
var body = new ArrayBuilder<Expression>(13);
var vars = new ArrayBuilder<ParameterExpression>(8 + (isVoid ? 0 : 1));
ParameterExpression[] @params = Array.ConvertAll(invoke.GetParametersCached(), p => Expression.Parameter(p.ParameterType, p.Name));
LabelTarget @return = Expression.Label(returnType);
Type[] typeArgs = new[] { typeof(T) };
ParameterExpression site = @params[0];
ParameterExpression[] arguments = @params.RemoveFirst();
ParameterExpression @this = Expression.Variable(typeof(CallSite<T>), "this");
vars.UncheckedAdd(@this);
body.UncheckedAdd(Expression.Assign(@this, Expression.Convert(site, @this.Type)));
ParameterExpression applicable = Expression.Variable(typeof(T[]), "applicable");
vars.UncheckedAdd(applicable);
ParameterExpression rule = Expression.Variable(typeof(T), "rule");
vars.UncheckedAdd(rule);
ParameterExpression originalRule = Expression.Variable(typeof(T), "originalRule");
vars.UncheckedAdd(originalRule);
Expression target = Expression.Field(@this, nameof(Target));
body.UncheckedAdd(Expression.Assign(originalRule, target));
ParameterExpression result = null;
if (!isVoid)
{
vars.UncheckedAdd(result = Expression.Variable(@return.Type, "result"));
}
ParameterExpression count = Expression.Variable(typeof(int), "count");
vars.UncheckedAdd(count);
ParameterExpression index = Expression.Variable(typeof(int), "index");
vars.UncheckedAdd(index);
body.UncheckedAdd(
Expression.Assign(
site,
Expression.Call(
CallSiteOps_CreateMatchmaker.MakeGenericMethod(typeArgs),
@this
)
)
);
Expression processRule;
Expression getMatch = Expression.Call(CallSiteOps_GetMatch, site);
Expression resetMatch = Expression.Call(CallSiteOps_ClearMatch, site);
Expression invokeRule = Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params));
Expression onMatch = Expression.Call(
CallSiteOps_UpdateRules.MakeGenericMethod(typeArgs),
@this,
index
);
if (isVoid)
{
processRule = Expression.Block(
invokeRule,
Expression.IfThen(
getMatch,
Expression.Block(onMatch, Expression.Return(@return))
)
);
}
else
{
processRule = Expression.Block(
Expression.Assign(result, invokeRule),
Expression.IfThen(
getMatch,
Expression.Block(onMatch, Expression.Return(@return, result))
)
);
}
Expression getApplicableRuleAtIndex = Expression.Assign(rule, Expression.ArrayAccess(applicable, new TrueReadOnlyCollection<Expression>(index)));
Expression getRule = getApplicableRuleAtIndex;
LabelTarget @break = Expression.Label();
Expression breakIfDone = Expression.IfThen(
Expression.Equal(index, count),
Expression.Break(@break)
);
Expression incrementIndex = Expression.PreIncrementAssign(index);
body.UncheckedAdd(
Expression.IfThen(
Expression.NotEqual(
Expression.Assign(
applicable,
Expression.Call(
CallSiteOps_GetRules.MakeGenericMethod(typeArgs),
@this
)
),
Expression.Constant(null, applicable.Type)
),
Expression.Block(
Expression.Assign(count, Expression.ArrayLength(applicable)),
Expression.Assign(index, Utils.Constant(0)),
Expression.Loop(
Expression.Block(
breakIfDone,
getRule,
Expression.IfThen(
Expression.NotEqual(
Expression.Convert(rule, typeof(object)),
Expression.Convert(originalRule, typeof(object))
),
Expression.Block(
Expression.Assign(
target,
rule
),
processRule,
resetMatch
)
),
incrementIndex
),
@break,
@continue: null
)
)
)
);
////
//// Level 2 cache lookup
////
//
////
//// Any applicable rules in level 2 cache?
////
ParameterExpression cache = Expression.Variable(typeof(RuleCache<T>), "cache");
vars.UncheckedAdd(cache);
body.UncheckedAdd(
Expression.Assign(
cache,
Expression.Call(CallSiteOps_GetRuleCache.MakeGenericMethod(typeArgs), @this)
)
);
body.UncheckedAdd(
Expression.Assign(
applicable,
Expression.Call(CallSiteOps_GetCachedRules.MakeGenericMethod(typeArgs), cache)
)
);
// L2 invokeRule is different (no onMatch)
if (isVoid)
{
processRule = Expression.Block(
invokeRule,
Expression.IfThen(
getMatch,
Expression.Return(@return)
)
);
}
else
{
processRule = Expression.Block(
Expression.Assign(result, invokeRule),
Expression.IfThen(
getMatch,
Expression.Return(@return, result)
)
);
}
Expression tryRule = Expression.TryFinally(
processRule,
Expression.IfThen(
getMatch,
Expression.Block(
Expression.Call(CallSiteOps_AddRule.MakeGenericMethod(typeArgs), @this, rule),
Expression.Call(CallSiteOps_MoveRule.MakeGenericMethod(typeArgs), cache, rule, index)
)
)
);
getRule = Expression.Assign(
target,
getApplicableRuleAtIndex
);
body.UncheckedAdd(Expression.Assign(index, Utils.Constant(0)));
body.UncheckedAdd(Expression.Assign(count, Expression.ArrayLength(applicable)));
body.UncheckedAdd(
Expression.Loop(
Expression.Block(
breakIfDone,
getRule,
tryRule,
resetMatch,
incrementIndex
),
@break,
@continue: null
)
);
////
//// Miss on Level 0, 1 and 2 caches. Create new rule
////
body.UncheckedAdd(Expression.Assign(rule, Expression.Constant(null, rule.Type)));
ParameterExpression args = Expression.Variable(typeof(object[]), "args");
Expression[] argsElements = Array.ConvertAll(arguments, p => Convert(p, typeof(object)));
vars.UncheckedAdd(args);
body.UncheckedAdd(
Expression.Assign(
args,
Expression.NewArrayInit(typeof(object), new TrueReadOnlyCollection<Expression>(argsElements))
)
);
Expression setOldTarget = Expression.Assign(
target,
originalRule
);
getRule = Expression.Assign(
target,
Expression.Assign(
rule,
Expression.Call(
CallSiteOps_Bind.MakeGenericMethod(typeArgs),
Expression.Property(@this, nameof(Binder)),
@this,
args
)
)
);
tryRule = Expression.TryFinally(
processRule,
Expression.IfThen(
getMatch,
Expression.Call(
CallSiteOps_AddRule.MakeGenericMethod(typeArgs),
@this,
rule
)
)
);
body.UncheckedAdd(
Expression.Loop(
Expression.Block(setOldTarget, getRule, tryRule, resetMatch),
@break: null,
@continue: null
)
);
body.UncheckedAdd(Expression.Default(@return.Type));
Expression<T> lambda = Expression.Lambda<T>(
Expression.Label(
@return,
Expression.Block(
vars.ToReadOnly(),
body.ToReadOnly()
)
),
CallSiteTargetMethodName,
true, // always compile the rules with tail call optimization
new TrueReadOnlyCollection<ParameterExpression>(@params)
);
// Need to compile with forceDynamic because T could be invisible,
// or one of the argument types could be invisible
return lambda.Compile();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
private T CreateCustomNoMatchDelegate(MethodInfo invoke)
{
ParameterExpression[] @params = Array.ConvertAll(invoke.GetParametersCached(), p => Expression.Parameter(p.ParameterType, p.Name));
return Expression.Lambda<T>(
Expression.Block(
Expression.Call(
typeof(CallSiteOps).GetMethod(nameof(CallSiteOps.SetNotMatched)),
@params[0]
),
Expression.Default(invoke.GetReturnType())
),
new TrueReadOnlyCollection<ParameterExpression>(@params)
).Compile();
}
private static Expression Convert(Expression arg, Type type)
{
if (TypeUtils.AreReferenceAssignable(type, arg.Type))
{
return arg;
}
return Expression.Convert(arg, type);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.