content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using Hive.Backend.DataModels;
using Hive.Backend.Repositories;
using Hive.Backend.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Hive.Backend.Services
{
public class SurveyService : ISurveyService
{
private readonly ISurveyRepository _repository;
public SurveyService(ISurveyRepository repository)
{
_repository = repository;
}
public IQueryable<Survey> GetAll()
{
return _repository.GetAllWithReferences();
}
public async Task<Survey> GetById(Guid id)
{
return await _repository.GetByIdWithReferences(id);
}
public async Task<Survey> InsertSurvey(Survey survey, List<Question> questions)
{
if (survey == null)
{
throw new ArgumentNullException(nameof(survey));
}
return await _repository.InsertSurvey(survey, questions);
}
public async Task Save(Survey entity, List<Question> questions)
{
if (entity == null)
{
throw new ArgumentNullException(nameof(entity));
}
var oldEntity = await GetById(entity.Id);
await _repository.UpdateSurvey(oldEntity, entity, questions);
}
public async Task<EditableSurveyVM> GetEditableSurvey(Guid surveyId)
{
return await _repository.GetEditableSurvey(surveyId);
}
public async Task<IQueryable<Card>> GetSurveyquestions(Guid surveyId)
{
return await _repository.GetSurveyquestions(surveyId);
}
public async Task<IQueryable<Card>> GetSurveyReportsquestions(Guid surveyReportId)
{
return await _repository.GetSurveyReportsquestions(surveyReportId);
}
#region HELPERS
public async Task<string> GetContentsurvey(Guid surveyId)
{
return await _repository.GetContentsurvey(surveyId);
}
public async Task<int> GetMaxQuestions(Guid surveyId)
{
return await _repository.GetMaxQuestions(surveyId);
}
public async Task<string> GetPictureSurvey(Guid surveyReportId)
{
return await _repository.GetPictureSurvey(surveyReportId);
}
#endregion
}
}
| 27.712644 | 90 | 0.621319 | [
"MIT"
] | Mobioos/SmartApp-Hive | backend/Services/SurveyService.cs | 2,413 | C# |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
namespace AmplifyShaderEditor
{
public enum AvailableSurfaceInputs
{
DEPTH = 0,
UV_COORDS,
UV2_COORDS,
VIEW_DIR,
COLOR,
SCREEN_POS,
WORLD_POS,
WORLD_REFL,
WORLD_NORMAL
}
public enum CustomStyle
{
NodeWindowOff = 0,
NodeWindowOn,
NodeTitle,
NodeHeader,
CommentaryHeader,
ShaderLibraryTitle,
ShaderLibraryAddToList,
ShaderLibraryRemoveFromList,
ShaderLibraryOpenListed,
ShaderLibrarySelectionAsTemplate,
ShaderLibraryItem,
CommentaryTitle,
PortEmptyIcon,
PortFullIcon,
InputPortlabel,
OutputPortLabel,
CommentaryResizeButton,
CommentaryResizeButtonInv,
CommentaryBackground,
MinimizeButton,
MaximizeButton,
NodePropertiesTitle,
ShaderModeTitle,
MaterialModeTitle,
ShaderNoMaterialModeTitle,
PropertyValuesTitle,
ShaderModeNoShader,
MainCanvasTitle,
ShaderBorder,
MaterialBorder,
SamplerTextureRef,
SamplerTextureIcon,
CustomExpressionAddItem,
CustomExpressionRemoveItem,
CustomExpressionSmallAddItem,
CustomExpressionSmallRemoveItem,
ResetToDefaultInspectorButton,
SliderStyle,
ObjectPicker,
NodePropertyPicker,
NodePreviewExpander,
NodePreviewCollapser,
SamplerButton,
SamplerFrame,
CommentarySuperTitle,
MiniButtonTopLeft,
MiniButtonTopMid,
MiniButtonTopRight,
ShaderFunctionBorder,
ShaderFunctionMode,
RightShaderMode,
FlatBackground,
DocumentationLink
}
public enum MasterNodePortCategory
{
Vertex = 1 << 0,
Fragment = 1 << 1,
Tessellation = 1 << 2,
Debug = 1 << 3
}
public struct NodeData
{
public MasterNodePortCategory Category;
public int OrderIndex;
public int GraphDepth;
public NodeData( MasterNodePortCategory category )
{
Category = category;
OrderIndex = 0;
GraphDepth = -1;
}
}
public struct NodeCastInfo
{
public int NodeId;
public int PortId;
public NodeCastInfo( int nodeId, int portId )
{
NodeId = nodeId;
PortId = portId;
}
public override string ToString()
{
return NodeId.ToString() + PortId.ToString();
}
};
public struct ButtonClickId
{
public const int LeftMouseButton = 0;
public const int RightMouseButton = 1;
public const int MiddleMouseButton = 2;
}
public enum ASESelectionMode
{
Shader = 0,
Material,
ShaderFunction
}
public enum DrawOrder
{
Background,
Default
}
public enum NodeConnectionStatus
{
Not_Connected = 0,
Connected,
Error,
Island
}
public enum InteractionMode
{
Target,
Other,
Both
}
public enum FunctionNodeCategories
{
Custom,
CameraAndScreen,
ConstantsAndProperties,
Functions,
ImageEffects,
Light,
LogicalOperators,
MathOperators,
MatrixOperators,
Miscellaneous,
ObjectTransform,
SurfaceData,
Textures,
Time,
TrignometryOperators,
UVCoordinates,
VectorOpertors,
VexterData
}
public class UIUtils
{
public static int SerializeHelperCounter = 0;
public static bool IgnoreDeselectAll = false;
public static bool DirtyMask = true;
public static bool Initialized = false;
public static float HeaderMaxHeight;
public static float CurrentHeaderHeight;
public static GUISkin MainSkin = null;
public static GUIStyle PlusStyle;
public static GUIStyle MinusStyle;
public static GUIStyle RangedFloatSliderStyle;
public static GUIStyle RangedFloatSliderThumbStyle;
public static GUIStyle SwitchNodePopUp;
public static GUIStyle PropertyPopUp;
public static GUIStyle ObjectField;
public static GUIStyle PreviewExpander;
public static GUIStyle PreviewCollapser;
public static GUIStyle ObjectFieldThumb;
public static GUIStyle ObjectFieldThumbOverlay;
public static GUIStyle InspectorPopdropdownStyle;
public static GUIStyle BoldErrorStyle;
public static GUIStyle BoldWarningStyle;
public static GUIStyle BoldInfoStyle;
public static GUIStyle Separator;
public static GUIStyle ToolbarSearchTextfield;
public static GUIStyle ToolbarSearchCancelButton;
public static GUIStyle MiniButtonTopLeft;
public static GUIStyle MiniButtonTopMid;
public static GUIStyle MiniButtonTopRight;
public static GUIStyle MiniObjectFieldThumbOverlay;
public static GUIStyle MiniSamplerButton;
public static GUIStyle EmptyStyle = new GUIStyle();
public static GUIStyle TooltipBox;
public static GUIStyle Box;
public static GUIStyle Button;
public static GUIStyle TextArea;
public static GUIStyle Label;
public static GUIStyle Toggle;
public static GUIStyle Textfield;
public static GUIStyle UnZoomedNodeTitleStyle;
public static GUIStyle UnZoomedPropertyValuesTitleStyle;
public static GUIStyle UnZoomedInputPortStyle;
public static GUIStyle UnZoomedOutputPortPortStyle;
// Node Property Menu items
public static GUIStyle MenuItemToggleStyle;
public static GUIStyle MenuItemEnableStyle;
public static GUIStyle MenuItemBackgroundStyle;
public static GUIStyle MenuItemToolbarStyle;
public static GUIStyle MenuItemInspectorDropdownStyle;
public static bool UsingProSkin = false;
public static Texture ShaderIcon { get { return EditorGUIUtility.IconContent( "Shader Icon" ).image; } }
public static Texture MaterialIcon { get { return EditorGUIUtility.IconContent( "Material Icon" ).image; } }
//50be8291f9514914aa55c66c49da67cf
public static Texture ShaderFunctionIcon { get { return AssetDatabase.LoadAssetAtPath<Texture>( AssetDatabase.GUIDToAssetPath( "50be8291f9514914aa55c66c49da67cf" ) ); } }
public static Texture2D WireNodeSelection = null;
public static Texture2D SliderButton = null;
public static Texture2D SmallErrorIcon = null;
public static Texture2D SmallWarningIcon = null;
public static Texture2D SmallInfoIcon = null;
public static Texture2D CheckmarkIcon = null;
public static Texture2D MasterNodeOnTexture = null;
public static Texture2D MasterNodeOffTexture = null;
public static Texture2D GPUInstancedOnTexture = null;
public static Texture2D GPUInstancedOffTexture = null;
public static bool ShowContextOnPick = true;
private static AmplifyShaderEditorWindow m_currentWindow = null;
public static AmplifyShaderEditorWindow CurrentWindow
{
get
{
if( m_currentWindow == null )
{
for( int i = 0; i < IOUtils.AllOpenedWindows.Count; i++ )
{
if( IOUtils.AllOpenedWindows[ i ] != null )
{
m_currentWindow = IOUtils.AllOpenedWindows[ i ];
}
else
{
//Debug.Log("No Window Found!");
}
}
}
return m_currentWindow;
}
set { m_currentWindow = value; }
}
public static Vector2 PortsSize;
public static Vector3 PortsDelta;
public static Vector3 ScaledPortsDelta;
public static Material LinearMaterial = null;
public static Shader IntShader = null;
public static Shader FloatShader = null;
public static Shader Vector2Shader = null;
public static Shader Vector3Shader = null;
public static Shader Vector4Shader = null;
public static Shader ColorShader = null;
public static Shader MaskingShader = null;
public static bool InhibitMessages = false;
private static int m_shaderIndentLevel = 0;
private static string m_shaderIndentTabs = string.Empty;
//Label Vars
private static TextAnchor m_alignment;
private static TextClipping m_clipping;
private static bool m_wordWrap;
private static int m_fontSize;
private static Color m_fontColor;
private static FontStyle m_fontStyle;
private static TextInfo m_textInfo;
private static string m_latestOpenedFolder = string.Empty;
private static Dictionary<int, UndoParentNode> m_undoHelper = new Dictionary<int, UndoParentNode>();
private static Dictionary<string, int> AvailableKeywordsDict = new Dictionary<string, int>();
public static readonly string[] AvailableKeywords =
{
"Custom",
"ETC1_EXTERNAL_ALPHA",
"PIXELSNAP_ON"
};
public static readonly string[] CategoryPresets =
{
"<Custom>",
"Camera And Screen",
"Constants And Properties",
"Functions",
"Image Effects",
"Light",
"Logical Operators",
"Math Operators",
"Matrix Operators",
"Miscellaneous",
"Object Transform",
"Surface Data",
"Textures",
"Time",
"Trignometry Operators",
"UV Coordinates",
"Vector Opertors",
"Vexter Data"
};
private static Dictionary<string, string> m_exampleMaterialIDs = new Dictionary<string, string>()
{
//Community
{"2Sided", "8ebbbf2c99a544ca780a2573ef1450fc" },
{"DissolveBurn", "f144f2d7ff3daf349a2b7f0fd81ec8ac" },
{"MourEnvironmentGradient", "b64adae401bc073408ac7bff0993c107" },
{"ForceShield", "0119aa6226e2a4cfdb6c9a5ba9df7820" },
{"HighlightAnimated", "3d232e7526f6e426cab994cbec1fc287" },
{"Hologram", "b422c600f1c3941b8bc7e95db33476ad" },
{"LowPolyWater", "0557703d3791a4286a62f8ee709d5bef"},
//Official
{"AnimatedFire", "63ea5eae6d954a14292033589d0d4275" },
{"AnimatedFire-ShaderFunction", "9c6c9fcb82afe874a825a9e680e694b2" },
{"BurnEffect", "0b019675a8064414b97862a02f644166" },
{"CubemapReflections", "2c299f827334e9c459a60931aea62260" },
{"DitheringFade", "610507217b7dcad4d97e6e03e9844171" },
{"DoubleLayerCustomSurface", "846aec4914103104d99e9e31a217b548" },
{"NormalExtrusion", "70a5800fbba039f46b438a2055bc6c71" },
{"MatcapSample", "da8aaaf01fe8f2b46b2fbcb803bd7af4" },
{"ParallaxMappingIterations", "a0cea9c3f318ac74d89cd09134aad000" },
{"SandPOM", "905481dc696211145b88dc4bac2545f3" },
{"ParallaxWindow", "63ad0e7afb1717b4e95adda8904ab0c3" },
{"LocalPosCutoff", "fed8c9d33a691084c801573feeed5a62" },
{"ImprovedReadFromAtlasTiled", "941b31b251ea8e74f9198d788a604c9b" },
{"ReadFromAtlasTiled", "2d5537aa702f24645a1446dc3be92bbf" },
{"ReflectRefractSoapBubble", "a844987c9f2e7334abaa34f12feda3b9" },
{"RimLight", "e2d3a4d723cf1dc4eab1d919f3324dbc" },
{"RefractedShadows", "11818aa28edbeb04098f3b395a5bfc1d" },
{"TextureArray", "0f572993ab788a346aea45f2f797b7fa" },
{"ObjectNormalRefraction", "f1a0a645876302547b608ce881c94e6d" },
{"ShaderBallInterior", "e47ee174f55b6144b9c1a942bb23d82a" },
{"ScreenSpaceCurvature", "2e794cb9b3900b043a37ba28cdc2f907" },
{"ScreenSpaceDetail", "3a0163d12fede4d47a1f818a66a115de" },
{"SimpleNoise", "cc167bc6c2063a14f84a5a77be541194" },
{"SimpleBlur", "1d283ff911af20e429180bb15d023661" },
{"SimpleGPUInstancing", "9d609a7c8d00c7c4c9bdcdcdba154b81" },
{"SimpleLambert", "54b29030f7d7ffe4b84f2f215dede5ac" },
{"SimpleRefraction", "58c94d2f48acdc049a53b4ca53d6d98a" },
{"SimpleTexture", "9661085a7d249a54c95078ac8e7ff004" },
{"SnowAccum", "e3bd639f50ae1a247823079047a8dc01" },
{"StencilDiffuse01", "9f47f529fdeddd948a2d2722f73e6ac4" },
{"StencilMask01", "6f870834077d59b44ac421c36f619d59" },
{"StencilDiffuse02", "11cdb862d5ba68c4eae526765099305b" },
{"StencilMask02", "344696733b065c646b18c1aa2eacfdb7" },
{"StencilDiffuse03", "75e851f6c686a5f42ab900222b29355b" },
{"StencilMask03", "c7b3018ad495c6b479f2e3f8564aa6dc" },
{"SubstanceExample", "a515e243b476d7e4bb37eb9f82c87a12" },
{"AnimatedRefraction", "e414af1524d258047bb6b82b8860062c" },
{"Tessellation", "efb669a245f17384c88824d769d0087c" },
{"Translucency", "842ba3dcdd461ea48bdcfcea316cbcc4" },
{"Transmission", "1b21506b7afef734facfc42c596caa7b" },
{"Transparency", "e323a62068140c2408d5601877e8de2c" },
{"TriplanarProjection", "663d512de06d4e24db5205c679f394cb" },
{"TwoSideWithFace", "c953c4b601ba78e4f870d24d038b67f6" },
{"Ground", "48df9bdf7b922d94bb3167e6db39c943" },
{"WaterSample", "288137d67ce790e41903020c572ab4d7" },
{"WorldPosSlices", "013cc03f77f3d034692f902db8928787" }
};
private static Dictionary<TextureType, string> m_textureTypeToCgType = new Dictionary<TextureType, string>()
{
{TextureType.Texture1D, "sampler1D" },
{TextureType.Texture2D, "sampler2D" },
{TextureType.Texture3D, "sampler3D" },
{TextureType.Cube , "samplerCUBE"},
{TextureType.Texture2DArray, "sampler2D" },
{TextureType.ProceduralTexture, "sampler2D" }
};
private static Dictionary<string, Color> m_nodeCategoryToColor = new Dictionary<string, Color>()
{
{ "Master", new Color( 0.6f, 0.52f, 0.43f, 1.0f )},
{ "Default", new Color( 0.26f, 0.35f, 0.44f, 1.0f )},
{ "Vertex Data", new Color( 0.8f, 0.07f, 0.18f, 1.0f)},//new Color( 0.75f, 0.10f, 0.30f, 1.0f )},
{ "Math Operators", new Color( 0.26f, 0.35f, 0.44f, 1.0f )},//new Color( 0.10f, 0.27f, 0.45f, 1.0f) },
{ "Logical Operators", new Color( 0.0f, 0.55f, 0.45f, 1.0f)},//new Color( 0.11f, 0.28f, 0.47f, 1.0f) },
{ "Trigonometry Operators", new Color( 0.1f, 0.20f, 0.35f, 1.0f)},//new Color( 0.8f, 0.07f, 0.18f, 1.0f)},
{ "Image Effects", new Color( 0.5f, 0.2f, 0.90f, 1.0f)},//new Color( 0.12f, 0.47f, 0.88f, 1.0f)},
{ "Miscellaneous", new Color( 0.49f, 0.32f, 0.60f, 1.0f)},
{ "Camera And Screen", new Color( 0.75f, 0.10f, 0.30f, 1.0f )},//new Color( 0.17f, 0.22f, 0.07f, 1.0f) },
{ "Constants And Properties", new Color( 0.42f, 0.70f, 0.22f, 1.0f) },
{ "Surface Data", new Color( 0.92f, 0.73f, 0.03f, 1.0f)},
{ "Matrix Transform", new Color( 0.09f, 0.43f, 0.2f, 1.0f) },
{ "Time", new Color( 0.25f, 0.25f, 0.25f, 1.0f)},//new Color( 0.89f, 0.59f, 0.0f, 1.0f) },
{ "Functions", new Color( 1.00f, 0.4f, 0.0f, 1.0f) },
{ "Vector Operators", new Color( 0.22f, 0.20f, 0.45f, 1.0f)},
{ "Matrix Operators", new Color( 0.45f, 0.9f, 0.20f, 1.0f) },
{ "Light", new Color( 1.0f, 0.9f, 0.0f, 1.0f) },
{ "Textures", new Color( 0.15f, 0.40f, 0.8f, 1.0f)},
{ "Commentary", new Color( 0.7f, 0.7f, 0.7f, 1.0f)},
{ "UV Coordinates", new Color( 0.89f, 0.59f, 0.0f, 1.0f) },
{ "Object Transform", new Color( 0.15f, 0.4f, 0.49f, 1.0f)},
{ "Vertex Transform", new Color( 0.15f, 0.4f, 0.49f, 1.0f)}
};
private static Dictionary<ToolButtonType, List<string>> m_toolButtonTooltips = new Dictionary<ToolButtonType, List<string>>
{
{ ToolButtonType.New, new List<string>() { "Create new shader." } },
{ ToolButtonType.Open, new List<string>() { "Open existing shader." } },
{ ToolButtonType.Save, new List<string>() { "No changes to save.", "Save current changes." } },
{ ToolButtonType.Library, new List<string>() { "Lists custom shader selection." } },
{ ToolButtonType.Options, new List<string>() { "Open Options menu." } },
{ ToolButtonType.Update, new List<string>() { "Open or create a new shader first.", "Click to enable to update current shader.", "Shader up-to-date." } },
{ ToolButtonType.Live, new List<string>() { "Open or create a new shader first.", "Click to enable live shader preview", "Click to enable live shader and material preview." , "Live preview active, click to disable." } },
{ ToolButtonType.CleanUnusedNodes, new List<string>() { "No unconnected nodes to clean.", "Remove all nodes not connected( directly or indirectly) to the master node." }},
{ ToolButtonType.Help, new List<string>() { "Show help window." } },
{ ToolButtonType.FocusOnMasterNode,new List<string>() { "Focus on active master node." } },
{ ToolButtonType.FocusOnSelection, new List<string>() { "Focus on selection fit to screen ( if none selected )." } }
};
private static Color[] m_dataTypeToColorMonoMode = { new Color( 0.5f, 0.5f, 0.5f, 1.0f ), Color.white };
private static Dictionary<WirePortDataType, Color> m_dataTypeToColor = new Dictionary<WirePortDataType, Color>( new WirePortDataTypeComparer() )
{
{ WirePortDataType.OBJECT, Color.white},
{ WirePortDataType.FLOAT, Color.gray},
{ WirePortDataType.FLOAT2, new Color(1f,1f,0f,1f)},
{ WirePortDataType.FLOAT3, new Color(0.5f,0.5f,1f,1f)},
{ WirePortDataType.FLOAT4, new Color(1f,0,1f,1f)},
{ WirePortDataType.FLOAT3x3, new Color(0.5f,1f,0.5f,1f)},
{ WirePortDataType.FLOAT4x4, new Color(0.5f,1f,0.5f,1f)},
{ WirePortDataType.COLOR, new Color(1f,0,1f,1f)},
{ WirePortDataType.INT, Color.gray},
{ WirePortDataType.SAMPLER1D, new Color(1f,0.5f,0f,1f)},
{ WirePortDataType.SAMPLER2D, new Color(1f,0.5f,0f,1f)},
{ WirePortDataType.SAMPLER3D, new Color(1f,0.5f,0f,1f)},
{ WirePortDataType.SAMPLERCUBE, new Color(1f,0.5f,0f,1f)}
};
private static Dictionary<WirePortDataType, string> m_dataTypeToName = new Dictionary<WirePortDataType, string>()
{
{ WirePortDataType.OBJECT, "Generic Object"},
{ WirePortDataType.FLOAT, "Float"},
{ WirePortDataType.FLOAT2, "Vector2"},
{ WirePortDataType.FLOAT3, "Vector3"},
{ WirePortDataType.FLOAT4, "Vector4"},
{ WirePortDataType.FLOAT3x3, "3x3 Matrix"},
{ WirePortDataType.FLOAT4x4, "4x4 Matrix"},
{ WirePortDataType.COLOR, "Color"},
{ WirePortDataType.INT, "Int"},
{ WirePortDataType.SAMPLER1D, "Sampler1D"},
{ WirePortDataType.SAMPLER2D, "Sampler2D"},
{ WirePortDataType.SAMPLER3D, "Sampler3D"},
{ WirePortDataType.SAMPLERCUBE, "SamplerCUBE"}
};
private static Dictionary<AvailableSurfaceInputs, string> m_inputTypeDeclaration = new Dictionary<AvailableSurfaceInputs, string>()
{
{ AvailableSurfaceInputs.DEPTH, "{0} Depth : SV_Depth"},
{ AvailableSurfaceInputs.UV_COORDS, "{0}2 uv"},// texture uv must have uv or uv2 followed by the texture name
{ AvailableSurfaceInputs.UV2_COORDS, "{0}2 uv2"},
{ AvailableSurfaceInputs.VIEW_DIR, "{0}3 viewDir"},
{ AvailableSurfaceInputs.COLOR, "{0}4 color : COLOR"},
{ AvailableSurfaceInputs.SCREEN_POS, "{0}4 screenPos"},
{ AvailableSurfaceInputs.WORLD_POS, "{0}3 worldPos"},
{ AvailableSurfaceInputs.WORLD_REFL, "{0}3 worldRefl"},
{ AvailableSurfaceInputs.WORLD_NORMAL,"{0}3 worldNormal"}
};
private static Dictionary<AvailableSurfaceInputs, string> m_inputTypeName = new Dictionary<AvailableSurfaceInputs, string>()
{
{ AvailableSurfaceInputs.DEPTH, "Depth"},
{ AvailableSurfaceInputs.UV_COORDS, "uv"},// texture uv must have uv or uv2 followed by the texture name
{ AvailableSurfaceInputs.UV2_COORDS, "uv2"},
{ AvailableSurfaceInputs.VIEW_DIR, "viewDir"},
{ AvailableSurfaceInputs.COLOR, "color"},
{ AvailableSurfaceInputs.SCREEN_POS, "screenPos"},
{ AvailableSurfaceInputs.WORLD_POS, "worldPos"},
{ AvailableSurfaceInputs.WORLD_REFL, "worldRefl"},
{ AvailableSurfaceInputs.WORLD_NORMAL, "worldNormal"}
};
private static Dictionary<PrecisionType, string> m_precisionTypeToCg = new Dictionary<PrecisionType, string>()
{
{ PrecisionType.Float, "float"},
{PrecisionType.Half, "half"},
{PrecisionType.Fixed, "fixed"}
};
private static Dictionary<VariableQualifiers, string> m_qualifierToCg = new Dictionary<VariableQualifiers, string>()
{
{ VariableQualifiers.In, string.Empty},
{VariableQualifiers.Out, "out"},
{VariableQualifiers.InOut, "inout"}
};
private static Dictionary<WirePortDataType, string> m_precisionWirePortToCgType = new Dictionary<WirePortDataType, string>()
{
{WirePortDataType.FLOAT, "{0}"},
{WirePortDataType.FLOAT2, "{0}2"},
{WirePortDataType.FLOAT3, "{0}3"},
{WirePortDataType.FLOAT4, "{0}4"},
{WirePortDataType.FLOAT3x3, "{0}3x3"},
{WirePortDataType.FLOAT4x4, "{0}4x4"},
{WirePortDataType.COLOR, "{0}4"},
{WirePortDataType.INT, "int"},
{WirePortDataType.SAMPLER1D, "sampler1D"},
{WirePortDataType.SAMPLER2D, "sampler2D"},
{WirePortDataType.SAMPLER3D, "sampler3D"},
{WirePortDataType.SAMPLERCUBE, "samplerCUBE"}
};
private static Dictionary<WirePortDataType, string> m_wirePortToCgType = new Dictionary<WirePortDataType, string>()
{
{ WirePortDataType.FLOAT, "float"},
{WirePortDataType.FLOAT2, "float2"},
{WirePortDataType.FLOAT3, "float3"},
{WirePortDataType.FLOAT4, "float4"},
{WirePortDataType.FLOAT3x3, "float3x3"},
{WirePortDataType.FLOAT4x4, "float4x4"},
{WirePortDataType.COLOR, "float4"},
{WirePortDataType.INT, "int"},
{WirePortDataType.SAMPLER1D, "sampler1D"},
{WirePortDataType.SAMPLER2D, "sampler2D"},
{WirePortDataType.SAMPLER3D, "sampler3D"},
{WirePortDataType.SAMPLERCUBE, "samplerCUBE"}
};
private static Dictionary<KeyCode, string> m_keycodeToString = new Dictionary<KeyCode, string>()
{
{KeyCode.Alpha0,"0" },
{KeyCode.Alpha1,"1" },
{KeyCode.Alpha2,"2" },
{KeyCode.Alpha3,"3" },
{KeyCode.Alpha4,"4" },
{KeyCode.Alpha5,"5" },
{KeyCode.Alpha6,"6" },
{KeyCode.Alpha7,"7" },
{KeyCode.Alpha8,"8" },
{KeyCode.Alpha9,"9" }
};
private static Dictionary<WireStatus, Color> m_wireStatusToColor = new Dictionary<WireStatus, Color>()
{
{ WireStatus.Default,new Color(0.7f,0.7f,0.7f,1.0f) },
{WireStatus.Highlighted,Color.yellow },
{WireStatus.Selected,Color.white}
};
private static Dictionary<string, bool> m_unityNativeShaderPaths = new Dictionary<string, bool>
{
{ "Resources/unity_builtin_extra", true },
{ "Library/unity default resources", true }
};
private static Dictionary<WirePortDataType, int> m_portPriority = new Dictionary<WirePortDataType, int>()
{
{ WirePortDataType.OBJECT, 0},
{WirePortDataType.SAMPLER1D, 0},
{WirePortDataType.SAMPLER2D, 0},
{WirePortDataType.SAMPLER3D, 0},
{WirePortDataType.SAMPLERCUBE, 0},
{WirePortDataType.FLOAT3x3, 1},
{WirePortDataType.FLOAT4x4, 2},
{WirePortDataType.INT, 3},
{WirePortDataType.FLOAT, 4},
{WirePortDataType.FLOAT2, 5},
{WirePortDataType.FLOAT3, 6},
{WirePortDataType.FLOAT4, 7},
{WirePortDataType.COLOR, 7}
};
private static readonly string IncorrectInputConnectionErrorMsg = "Input Port {0} from node {1} has type {2}\nwhich is incompatible with connection of type {3} from port {4} on node {5}";
private static readonly string IncorrectOutputConnectionErrorMsg = "Output Port {0} from node {1} has type {2}\nwhich is incompatible with connection of type {3} from port {4} on node {5}";
private static readonly string NoVertexModeNodeWarning = "{0} is unable to generate code in vertex function";
private static float SwitchFixedHeight;
private static float SwitchFontSize;
private static RectOffset SwitchNodeBorder;
private static RectOffset SwitchNodeMargin;
private static RectOffset SwitchNodeOverflow;
private static RectOffset SwitchNodePadding;
public static void ForceExampleShaderCompilation()
{
CurrentWindow.ForceMaterialsToUpdate( ref m_exampleMaterialIDs );
}
public static void Destroy()
{
if( IOUtils.AllOpenedWindows != null && IOUtils.AllOpenedWindows.Count > 0 )
{
return;
}
else
{
IOUtils.AllOpenedWindows.Clear();
}
Initialized = false;
PlusStyle = null;
MinusStyle = null;
m_textInfo = null;
RangedFloatSliderStyle = null;
RangedFloatSliderThumbStyle = null;
PropertyPopUp = null;
ObjectField = null;
PreviewExpander = null;
PreviewCollapser = null;
MenuItemToggleStyle = null;
MenuItemEnableStyle = null;
MenuItemBackgroundStyle = null;
MenuItemToolbarStyle = null;
MenuItemInspectorDropdownStyle = null;
ObjectFieldThumb = null;
ObjectFieldThumbOverlay = null;
InspectorPopdropdownStyle = null;
TooltipBox = null;
UnZoomedNodeTitleStyle = null;
UnZoomedPropertyValuesTitleStyle = null;
UnZoomedInputPortStyle = null;
UnZoomedOutputPortPortStyle = null;
ToolbarSearchTextfield = null;
ToolbarSearchCancelButton = null;
Box = null;
Button = null;
TextArea = null;
Label = null;
Toggle = null;
Textfield = null;
IntShader = null;
FloatShader = null;
Vector2Shader = null;
Vector3Shader = null;
Vector4Shader = null;
ColorShader = null;
MaskingShader = null;
BoldErrorStyle = null;
BoldWarningStyle = null;
BoldInfoStyle = null;
Separator = null;
MiniButtonTopLeft = null;
MiniButtonTopMid = null;
MiniButtonTopRight = null;
MiniObjectFieldThumbOverlay = null;
MiniSamplerButton = null;
Resources.UnloadAsset( SmallErrorIcon );
SmallErrorIcon = null;
Resources.UnloadAsset( SmallWarningIcon );
SmallWarningIcon = null;
Resources.UnloadAsset( SmallInfoIcon );
SmallInfoIcon = null;
Resources.UnloadAsset( CheckmarkIcon );
CheckmarkIcon = null;
Resources.UnloadAsset( MasterNodeOnTexture );
MasterNodeOnTexture = null;
Resources.UnloadAsset( MasterNodeOffTexture );
MasterNodeOffTexture = null;
Resources.UnloadAsset( GPUInstancedOnTexture );
GPUInstancedOnTexture = null;
Resources.UnloadAsset( GPUInstancedOffTexture );
GPUInstancedOffTexture = null;
MainSkin = null;
if( LinearMaterial != null )
GameObject.DestroyImmediate( LinearMaterial );
LinearMaterial = null;
if( m_undoHelper == null )
{
m_undoHelper.Clear();
m_undoHelper = null;
}
ASEMaterialInspector.Instance = null;
}
public static void ResetMainSkin()
{
if( (object)MainSkin != null )
{
CurrentHeaderHeight = HeaderMaxHeight;
ScaledPortsDelta = PortsDelta;
MainSkin.textField.fontSize = (int)( Constants.TextFieldFontSize );
MainSkin.customStyles[ (int)CustomStyle.NodeTitle ].fontSize = (int)( Constants.DefaultTitleFontSize );
MainSkin.label.fontSize = (int)( Constants.DefaultFontSize );
MainSkin.customStyles[ (int)CustomStyle.InputPortlabel ].fontSize = (int)( Constants.DefaultFontSize );
MainSkin.customStyles[ (int)CustomStyle.OutputPortLabel ].fontSize = (int)( Constants.DefaultFontSize );
MainSkin.customStyles[ (int)CustomStyle.CommentaryTitle ].fontSize = (int)( Constants.DefaultFontSize );
}
}
public static void InitMainSkin()
{
MainSkin = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath( IOUtils.MainSkinGUID ), typeof( GUISkin ) ) as GUISkin;
Initialized = true;
Texture2D portTex = GetCustomStyle( CustomStyle.PortEmptyIcon ).normal.background;
PortsSize = new Vector2( portTex.width, portTex.height );
PortsDelta = new Vector3( 0.5f * PortsSize.x, 0.5f * PortsSize.y );
HeaderMaxHeight = MainSkin.customStyles[ (int)CustomStyle.NodeHeader ].normal.background.height;
PropertyPopUp = GetCustomStyle( CustomStyle.NodePropertyPicker );
ObjectField = new GUIStyle( (GUIStyle)"ObjectField" );
PreviewExpander = GetCustomStyle( CustomStyle.NodePreviewExpander );
PreviewCollapser = GetCustomStyle( CustomStyle.NodePreviewCollapser );
WireNodeSelection = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath( "bfe0b03d5d60cea4f9d4b2d1d121e592" ), typeof( Texture2D ) ) as Texture2D;
SliderButton = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath( "dd563e33152bb6443b099b4139ceecb9" ), typeof( Texture2D ) ) as Texture2D;
SmallErrorIcon = EditorGUIUtility.Load( "icons/d_console.erroricon.sml.png" ) as Texture2D;
SmallWarningIcon = EditorGUIUtility.Load( "icons/d_console.warnicon.sml.png" ) as Texture2D;
SmallInfoIcon = EditorGUIUtility.Load( "icons/d_console.infoicon.sml.png" ) as Texture2D;
CheckmarkIcon = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath( "e9c4642eaa083a54ab91406d8449e6ac" ), typeof( Texture2D ) ) as Texture2D;
BoldErrorStyle = new GUIStyle( (GUIStyle)"BoldLabel" );
BoldErrorStyle.normal.textColor = Color.red;
BoldErrorStyle.alignment = TextAnchor.MiddleCenter;
BoldWarningStyle = new GUIStyle( (GUIStyle)"BoldLabel" );
BoldWarningStyle.normal.textColor = Color.yellow;
BoldWarningStyle.alignment = TextAnchor.MiddleCenter;
BoldInfoStyle = new GUIStyle( (GUIStyle)"BoldLabel" );
BoldInfoStyle.normal.textColor = Color.white;
BoldInfoStyle.alignment = TextAnchor.MiddleCenter;
Separator = new GUIStyle( MainSkin.customStyles[ (int)CustomStyle.FlatBackground ] );
MiniButtonTopLeft = new GUIStyle( MainSkin.customStyles[ (int)CustomStyle.MiniButtonTopLeft ] );
MiniButtonTopMid = new GUIStyle( MainSkin.customStyles[ (int)CustomStyle.MiniButtonTopMid ] );
MiniButtonTopRight = new GUIStyle( MainSkin.customStyles[ (int)CustomStyle.MiniButtonTopRight ] );
MiniObjectFieldThumbOverlay = new GUIStyle( (GUIStyle)"ObjectFieldThumbOverlay" );
MiniSamplerButton = new GUIStyle( MainSkin.customStyles[ (int)CustomStyle.SamplerButton ] );
m_textInfo = new CultureInfo( "en-US", false ).TextInfo;
RangedFloatSliderStyle = new GUIStyle( GUI.skin.horizontalSlider );
RangedFloatSliderThumbStyle = new GUIStyle( GUI.skin.horizontalSliderThumb );
RangedFloatSliderThumbStyle.normal.background = SliderButton;
RangedFloatSliderThumbStyle.active.background = null;
RangedFloatSliderThumbStyle.hover.background = null;
RangedFloatSliderThumbStyle.focused.background = null;
SwitchNodePopUp = new GUIStyle( (GUIStyle)"Popup" );
// RectOffset cannot be initiliazed on constructor
SwitchNodeBorder = new RectOffset( 4, 15, 3, 3 );
SwitchNodeMargin = new RectOffset( 4, 4, 3, 3 );
SwitchNodeOverflow = new RectOffset( 0, 0, -1, 2 );
SwitchNodePadding = new RectOffset( 6, 14, 2, 3 );
SwitchFixedHeight = 18;
SwitchFontSize = 10;
Box = new GUIStyle( GUI.skin.box );
Button = new GUIStyle( GUI.skin.button );
TextArea = new GUIStyle( GUI.skin.textArea );
Label = new GUIStyle( GUI.skin.label );
Toggle = new GUIStyle( GUI.skin.toggle );
Textfield = new GUIStyle( GUI.skin.textField );
//ShaderIcon = EditorGUIUtility.IconContent( "Shader Icon" ).image;
//MaterialIcon = EditorGUIUtility.IconContent( "Material Icon" ).image;
UnZoomedNodeTitleStyle = new GUIStyle( GetCustomStyle( CustomStyle.NodeTitle ) );
UnZoomedNodeTitleStyle.fontSize = 13;
UnZoomedPropertyValuesTitleStyle = new GUIStyle( GetCustomStyle( CustomStyle.PropertyValuesTitle ) );
UnZoomedPropertyValuesTitleStyle.fontSize = 11;
UnZoomedInputPortStyle = new GUIStyle( GetCustomStyle( CustomStyle.InputPortlabel ) );
UnZoomedInputPortStyle.fontSize = (int)Constants.DefaultFontSize;
UnZoomedOutputPortPortStyle = new GUIStyle( GetCustomStyle( CustomStyle.OutputPortLabel ) );
UnZoomedOutputPortPortStyle.fontSize = (int)Constants.DefaultFontSize;
ObjectFieldThumb = new GUIStyle( (GUIStyle)"ObjectFieldThumb" );
ObjectFieldThumbOverlay = new GUIStyle( (GUIStyle)"ObjectFieldThumbOverlay" );
TooltipBox = new GUIStyle( (GUIStyle)"Tooltip" );
TooltipBox.richText = true;
MasterNodeOnTexture = AssetDatabase.LoadAssetAtPath<Texture2D>( AssetDatabase.GUIDToAssetPath( IOUtils.MasterNodeOnTextureGUID ) );
MasterNodeOffTexture = AssetDatabase.LoadAssetAtPath<Texture2D>( AssetDatabase.GUIDToAssetPath( IOUtils.MasterNodeOnTextureGUID ) );
GPUInstancedOnTexture = AssetDatabase.LoadAssetAtPath<Texture2D>( AssetDatabase.GUIDToAssetPath( IOUtils.GPUInstancedOnTextureGUID ) );
GPUInstancedOffTexture = AssetDatabase.LoadAssetAtPath<Texture2D>( AssetDatabase.GUIDToAssetPath( IOUtils.GPUInstancedOffTextureGUID ) );
CheckNullMaterials();
UsingProSkin = EditorGUIUtility.isProSkin;
FetchMenuItemStyles();
}
public static void CheckNullMaterials()
{
if( LinearMaterial == null )
{
Shader linearShader = AssetDatabase.LoadAssetAtPath<Shader>( AssetDatabase.GUIDToAssetPath( "e90ef6ea05743b84baf9549874c52e47" ) ); //linear previews
LinearMaterial = new Material( linearShader );
}
if( IntShader == null )
IntShader = AssetDatabase.LoadAssetAtPath<Shader>( AssetDatabase.GUIDToAssetPath( "0f64d695b6ffacc469f2dd31432a232a" ) ); //int
if( FloatShader == null )
FloatShader = AssetDatabase.LoadAssetAtPath<Shader>( AssetDatabase.GUIDToAssetPath( "d9ca47581ac157145bff6f72ac5dd73e" ) ); //ranged float
if( Vector2Shader == null )
Vector2Shader = AssetDatabase.LoadAssetAtPath<Shader>( AssetDatabase.GUIDToAssetPath( "88b4191eb06084d4da85d1dd2f984085" ) ); //vector2
if( Vector3Shader == null )
Vector3Shader = AssetDatabase.LoadAssetAtPath<Shader>( AssetDatabase.GUIDToAssetPath( "8a44d38f06246bf48944b3f314bc7920" ) ); //vector3
if( Vector4Shader == null )
Vector4Shader = AssetDatabase.LoadAssetAtPath<Shader>( AssetDatabase.GUIDToAssetPath( "aac241d0e47a5a84fbd2edcd640788dc" ) ); //vector4
if( ColorShader == null )
ColorShader = AssetDatabase.LoadAssetAtPath<Shader>( AssetDatabase.GUIDToAssetPath( "6cf365ccc7ae776488ae8960d6d134c3" ) ); //color node
if( MaskingShader == null )
MaskingShader = AssetDatabase.LoadAssetAtPath<Shader>( AssetDatabase.GUIDToAssetPath( "9c34f18ebe2be3e48b201b748c73dec0" ) ); //masking shader
}
private static void FetchMenuItemStyles()
{
ObjectFieldThumb = new GUIStyle( (GUIStyle)"ObjectFieldThumb" );
ObjectFieldThumbOverlay = new GUIStyle( (GUIStyle)"ObjectFieldThumbOverlay" );
MenuItemToggleStyle = new GUIStyle( (GUIStyle)"foldout" );
MenuItemEnableStyle = UsingProSkin ? new GUIStyle( (GUIStyle)"OL ToggleWhite" ) : new GUIStyle( (GUIStyle)"OL Toggle" );
MenuItemBackgroundStyle = new GUIStyle( (GUIStyle)"TE NodeBackground" );
MenuItemToolbarStyle = new GUIStyle( (GUIStyle)"toolbarbutton" ) { fixedHeight = 20 };
MenuItemInspectorDropdownStyle = new GUIStyle( (GUIStyle)"toolbardropdown" ) { fixedHeight = 20 };
MenuItemInspectorDropdownStyle.margin.bottom = 2;
InspectorPopdropdownStyle = new GUIStyle( GUI.skin.GetStyle( "PopupCurveDropdown" ) );
InspectorPopdropdownStyle.alignment = TextAnchor.MiddleRight;
InspectorPopdropdownStyle.border.bottom = 16;
PlusStyle = ( EditorGUIUtility.isProSkin ) ? new GUIStyle( GetCustomStyle( CustomStyle.CustomExpressionAddItem ) ) : new GUIStyle( (GUIStyle)"OL Plus" );
PlusStyle.imagePosition = ImagePosition.ImageOnly;
PlusStyle.overflow = new RectOffset( -2, 0, -4, 0 );
MinusStyle = ( EditorGUIUtility.isProSkin ) ? new GUIStyle( GetCustomStyle( CustomStyle.CustomExpressionRemoveItem ) ) : new GUIStyle( (GUIStyle)"OL Minus" );
MinusStyle.contentOffset = Vector2.zero;
MinusStyle.imagePosition = ImagePosition.ImageOnly;
MinusStyle.overflow = new RectOffset( -2, 0, -4, 0 );
ToolbarSearchTextfield = new GUIStyle( (GUIStyle)"ToolbarSeachTextField" );
ToolbarSearchCancelButton = new GUIStyle( (GUIStyle)"ToolbarSeachCancelButton" );
}
public static void UpdateMainSkin( DrawInfo drawInfo )
{
CurrentHeaderHeight = HeaderMaxHeight * drawInfo.InvertedZoom;
ScaledPortsDelta = drawInfo.InvertedZoom * PortsDelta;
MainSkin.textField.fontSize = (int)( Constants.TextFieldFontSize * drawInfo.InvertedZoom );
MainSkin.customStyles[ (int)CustomStyle.NodeTitle ].fontSize = (int)( Constants.DefaultTitleFontSize * drawInfo.InvertedZoom );
MainSkin.customStyles[ (int)CustomStyle.PropertyValuesTitle ].fontSize = (int)( Constants.PropertiesTitleFontSize * drawInfo.InvertedZoom );
MainSkin.label.fontSize = (int)( Constants.DefaultFontSize * drawInfo.InvertedZoom );
MainSkin.customStyles[ (int)CustomStyle.InputPortlabel ].fontSize = (int)( Constants.DefaultFontSize * drawInfo.InvertedZoom );
MainSkin.customStyles[ (int)CustomStyle.OutputPortLabel ].fontSize = (int)( Constants.DefaultFontSize * drawInfo.InvertedZoom );
MainSkin.customStyles[ (int)CustomStyle.CommentaryTitle ].fontSize = (int)( Constants.DefaultFontSize * drawInfo.InvertedZoom );
RangedFloatSliderStyle.fixedHeight = 18 * drawInfo.InvertedZoom;
RangedFloatSliderThumbStyle.fixedHeight = 12 * drawInfo.InvertedZoom;
RangedFloatSliderThumbStyle.fixedWidth = 10 * drawInfo.InvertedZoom;
RangedFloatSliderThumbStyle.overflow.left = (int)( 1 * drawInfo.InvertedZoom );
RangedFloatSliderThumbStyle.overflow.right = (int)( 1 * drawInfo.InvertedZoom );
RangedFloatSliderThumbStyle.overflow.top = (int)( -4 * drawInfo.InvertedZoom );
RangedFloatSliderThumbStyle.overflow.bottom = (int)( 4 * drawInfo.InvertedZoom );
SwitchNodePopUp.fixedHeight = SwitchFixedHeight * drawInfo.InvertedZoom;
SwitchNodePopUp.border.left = (int)( SwitchNodeBorder.left * drawInfo.InvertedZoom );
SwitchNodePopUp.border.right = (int)( SwitchNodeBorder.right * drawInfo.InvertedZoom );
SwitchNodePopUp.border.top = (int)( SwitchNodeBorder.top * drawInfo.InvertedZoom );
SwitchNodePopUp.border.bottom = (int)( SwitchNodeBorder.bottom * drawInfo.InvertedZoom );
SwitchNodePopUp.margin.left = (int)( SwitchNodeMargin.left * drawInfo.InvertedZoom );
SwitchNodePopUp.margin.right = (int)( SwitchNodeMargin.right * drawInfo.InvertedZoom );
SwitchNodePopUp.margin.top = (int)( SwitchNodeMargin.top * drawInfo.InvertedZoom );
SwitchNodePopUp.margin.bottom = (int)( SwitchNodeMargin.bottom * drawInfo.InvertedZoom );
SwitchNodePopUp.overflow.left = (int)( SwitchNodeOverflow.left * drawInfo.InvertedZoom );
SwitchNodePopUp.overflow.right = (int)( SwitchNodeOverflow.right * drawInfo.InvertedZoom );
SwitchNodePopUp.overflow.top = (int)( SwitchNodeOverflow.top * drawInfo.InvertedZoom );
SwitchNodePopUp.overflow.bottom = (int)( SwitchNodeOverflow.bottom * drawInfo.InvertedZoom );
SwitchNodePopUp.padding.left = (int)( SwitchNodePadding.left * drawInfo.InvertedZoom );
SwitchNodePopUp.padding.right = (int)( SwitchNodePadding.right * drawInfo.InvertedZoom );
SwitchNodePopUp.padding.top = (int)( SwitchNodePadding.top * drawInfo.InvertedZoom );
SwitchNodePopUp.padding.bottom = (int)( SwitchNodePadding.bottom * drawInfo.InvertedZoom );
SwitchNodePopUp.fontSize = (int)( SwitchFontSize * drawInfo.InvertedZoom );
BoldErrorStyle.fontSize = (int)( 12 * drawInfo.InvertedZoom );
BoldWarningStyle.fontSize = (int)( 12 * drawInfo.InvertedZoom );
BoldInfoStyle.fontSize = (int)( 12 * drawInfo.InvertedZoom );
PropertyPopUp.fixedHeight = Constants.PropertyPickerHeight * drawInfo.InvertedZoom;
PropertyPopUp.fixedWidth = Constants.PropertyPickerWidth * drawInfo.InvertedZoom;
if( UsingProSkin != EditorGUIUtility.isProSkin )
{
UsingProSkin = EditorGUIUtility.isProSkin;
FetchMenuItemStyles();
}
PreviewExpander.fixedHeight = Constants.PreviewExpanderHeight * drawInfo.InvertedZoom;
PreviewExpander.fixedWidth = Constants.PreviewExpanderWidth * drawInfo.InvertedZoom;
PreviewCollapser.fixedHeight = Constants.PreviewExpanderHeight * drawInfo.InvertedZoom;
PreviewCollapser.fixedWidth = Constants.PreviewExpanderWidth * drawInfo.InvertedZoom;
MainSkin.customStyles[ (int)CustomStyle.SamplerButton ].fontSize = (int)( 9 * drawInfo.InvertedZoom );
ObjectFieldThumbOverlay.fontSize = (int)( 9 * drawInfo.InvertedZoom );
MiniButtonTopLeft.fontSize = (int)( 9 * drawInfo.InvertedZoom );
MiniButtonTopMid.fontSize = (int)( 9 * drawInfo.InvertedZoom );
MiniButtonTopRight.fontSize = (int)( 9 * drawInfo.InvertedZoom );
MiniObjectFieldThumbOverlay.fontSize = (int)( 7 * drawInfo.InvertedZoom );
MiniSamplerButton.fontSize = (int)( 8 * drawInfo.InvertedZoom );
//MainSkin.customStyles[ ( int ) CustomStyle.MiniButtonTopLeft ].fontSize = ( int ) ( 9 * drawInfo.InvertedZoom );
//MainSkin.customStyles[ ( int ) CustomStyle.MiniButtonTopMid ].fontSize = ( int ) ( 9 * drawInfo.InvertedZoom );
//MainSkin.customStyles[ ( int ) CustomStyle.MiniButtonTopRight ].fontSize = ( int ) ( 9 * drawInfo.InvertedZoom );
CheckNullMaterials();
}
public static void CacheLabelVars()
{
m_alignment = GUI.skin.label.alignment;
m_clipping = GUI.skin.label.clipping;
m_wordWrap = GUI.skin.label.wordWrap;
m_fontSize = GUI.skin.label.fontSize;
m_fontStyle = GUI.skin.label.fontStyle;
m_fontColor = GUI.skin.label.normal.textColor;
}
public static void RestoreLabelVars()
{
GUI.skin.label.alignment = m_alignment;
GUI.skin.label.clipping = m_clipping;
GUI.skin.label.wordWrap = m_wordWrap;
GUI.skin.label.fontSize = m_fontSize;
GUI.skin.label.fontStyle = m_fontStyle;
GUI.skin.label.normal.textColor = m_fontColor;
}
public static string GetTooltipForToolButton( ToolButtonType toolButtonType, int state ) { return m_toolButtonTooltips[ toolButtonType ][ state ]; }
public static string KeyCodeToString( KeyCode keyCode )
{
if( m_keycodeToString.ContainsKey( keyCode ) )
return m_keycodeToString[ keyCode ];
return keyCode.ToString();
}
public static string TextureTypeToCgType( TextureType type ) { return m_textureTypeToCgType[ type ]; }
public static string QualifierToCg( VariableQualifiers qualifier )
{
return m_qualifierToCg[ qualifier ];
}
public static string WirePortToCgType( WirePortDataType type )
{
if( type == WirePortDataType.OBJECT )
return string.Empty;
return m_wirePortToCgType[ type ];
}
public static string FinalPrecisionWirePortToCgType( PrecisionType precisionType, WirePortDataType type )
{
PrecisionType finalPrecision = GetFinalPrecision( precisionType );
if( type == WirePortDataType.OBJECT )
return string.Empty;
if( type == WirePortDataType.INT )
return m_wirePortToCgType[ type ];
return string.Format( m_precisionWirePortToCgType[ type ], m_precisionTypeToCg[ finalPrecision ] );
}
public static string PrecisionWirePortToCgType( PrecisionType precisionType, WirePortDataType type )
{
if( type == WirePortDataType.OBJECT )
return string.Empty;
if( type == WirePortDataType.INT )
return m_wirePortToCgType[ type ];
return string.Format( m_precisionWirePortToCgType[ type ], m_precisionTypeToCg[ precisionType ] );
}
public static Color GetColorForDataType( WirePortDataType dataType, bool monochromeMode = true, bool isInput = true )
{
if( monochromeMode )
{
return isInput ? m_dataTypeToColorMonoMode[ 0 ] : m_dataTypeToColorMonoMode[ 1 ];
}
else
{
return m_dataTypeToColor[ dataType ];
}
}
public static string GetNameForDataType( WirePortDataType dataType ) { return m_dataTypeToName[ dataType ]; }
public static string GetInputDeclarationFromType( PrecisionType precision, AvailableSurfaceInputs inputType )
{
string precisionStr = m_precisionTypeToCg[ precision ];
return string.Format( m_inputTypeDeclaration[ inputType ], precisionStr );
}
public static string GetInputValueFromType( AvailableSurfaceInputs inputType ) { return m_inputTypeName[ inputType ]; }
private static string CreateLocalValueName( PrecisionType precision, WirePortDataType dataType, string localOutputValue, string value ) { return string.Format( Constants.LocalValueDecWithoutIdent, PrecisionWirePortToCgType( precision, dataType ), localOutputValue, value ); }
public static string CastPortType( ref MasterNodeDataCollector dataCollector, PrecisionType nodePrecision, NodeCastInfo castInfo, object value, WirePortDataType oldType, WirePortDataType newType, string parameterName = null )
{
if( oldType == newType || newType == WirePortDataType.OBJECT )
{
return ( parameterName != null ) ? parameterName : value.ToString();
}
PrecisionType currentPrecision = GetFinalPrecision( nodePrecision );
string precisionStr = m_precisionTypeToCg[ currentPrecision ];
string newTypeStr = m_wirePortToCgType[ newType ];
newTypeStr = m_textInfo.ToTitleCase( newTypeStr );
int castId = ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation ) ? dataCollector.AvailableVertexTempId : dataCollector.AvailableFragTempId;
string localVarName = "temp_cast_" + castId;//m_wirePortToCgType[ oldType ] + "To" + newTypeStr + "_" + castInfo.ToString();
string result = string.Empty;
bool useRealValue = ( parameterName == null );
switch( oldType )
{
case WirePortDataType.FLOAT:
{
switch( newType )
{
case WirePortDataType.OBJECT: result = useRealValue ? value.ToString() : parameterName; break;
case WirePortDataType.FLOAT2:
{
string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, string.Format( Constants.CastHelper, ( ( useRealValue ) ? value.ToString() : parameterName ), "xx" ) );
dataCollector.AddToLocalVariables( dataCollector.PortCategory, -1, localVal );
result = localVarName;
}
break;
case WirePortDataType.FLOAT3:
{
string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, string.Format( Constants.CastHelper, ( ( useRealValue ) ? value.ToString() : parameterName ), "xxx" ) );
dataCollector.AddToLocalVariables( dataCollector.PortCategory, -1, localVal );
result = localVarName;
}
break;
case WirePortDataType.COLOR:
{
string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, string.Format( Constants.CastHelper, ( ( useRealValue ) ? value.ToString() : parameterName ), "xxxx" ) );
dataCollector.AddToLocalVariables( dataCollector.PortCategory, -1, localVal );
result = localVarName;
}
break;
case WirePortDataType.FLOAT4:
{
string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, string.Format( Constants.CastHelper, ( ( useRealValue ) ? value.ToString() : parameterName ), "xxxx" ) );
dataCollector.AddToLocalVariables( dataCollector.PortCategory, -1, localVal );
result = localVarName;
}
break;
case WirePortDataType.FLOAT3x3:
{
string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, ( ( useRealValue ) ? value.ToString() : parameterName ) );
dataCollector.AddToLocalVariables( dataCollector.PortCategory, -1, localVal );
result = localVarName;
}
break;
case WirePortDataType.FLOAT4x4:
{
string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, ( ( useRealValue ) ? value.ToString() : parameterName ) );
dataCollector.AddToLocalVariables( dataCollector.PortCategory, -1, localVal );
result = localVarName;
}
break;
case WirePortDataType.INT:
{
result = ( useRealValue ) ? ( (int)value ).ToString() : "(int)" + parameterName;
}
break;
}
}
break;
case WirePortDataType.FLOAT2:
{
Vector2 vecVal = useRealValue ? (Vector2)value : Vector2.zero;
switch( newType )
{
case WirePortDataType.OBJECT: result = useRealValue ? precisionStr + "2( " + vecVal.x + " , " + vecVal.y + " )" : parameterName; break;
case WirePortDataType.FLOAT:
{
result = ( useRealValue ) ? vecVal.x.ToString() : parameterName + ".x";
}
break;
case WirePortDataType.FLOAT3:
{
result = ( useRealValue ) ? precisionStr + "3( " + vecVal.x + " , " + vecVal.y + " , " + " 0.0 )" : precisionStr + "3( " + parameterName + " , 0.0 )";
}
break;
case WirePortDataType.COLOR:
case WirePortDataType.FLOAT4:
{
result = ( useRealValue ) ? precisionStr + "4( " + vecVal.x + " , " + vecVal.y + " , " + " 0.0 , 0.0 )" : precisionStr + "4( " + parameterName + ", 0.0 , 0.0 )";
}
break;
}
}
break;
case WirePortDataType.FLOAT3:
{
Vector3 vecVal = useRealValue ? (Vector3)value : Vector3.zero;
switch( newType )
{
case WirePortDataType.OBJECT: result = useRealValue ? precisionStr + "3( " + vecVal.x + " , " + vecVal.y + " , " + vecVal.z + " )" : parameterName; break;
case WirePortDataType.FLOAT:
{
result = ( useRealValue ) ? vecVal.x.ToString() : parameterName + ".x";
}
break;
case WirePortDataType.FLOAT2:
{
result = ( useRealValue ) ? precisionStr + "2( " + vecVal.x + " , " + vecVal.y + " )" : parameterName + ".xy";
}
break;
case WirePortDataType.COLOR:
case WirePortDataType.FLOAT4:
{
result = ( useRealValue ) ? precisionStr + "4( " + vecVal.x + " , " + vecVal.y + " , " + vecVal.z + " , 0.0 )" : precisionStr + "4( " + parameterName + " , 0.0 )";
}
break;
//case WirePortDataType.FLOAT3x3:
//{
// if ( useRealValue )
// {
// result = precisionStr + "3x3( " + vecVal.x + " , " + vecVal.y + " , " + vecVal.z + " , " +
// vecVal.x + " , " + vecVal.y + " , " + vecVal.z + " , " +
// vecVal.x + " , " + vecVal.y + " , " + vecVal.z + " )";
// }
// else
// {
// string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, parameterName );
// CurrentDataCollector.AddToLocalVariables( portCategory, -1, localVal );
// result = precisionStr + "3x3( " + localVarName + ".x , " + localVarName + ".y , " + localVarName + ".x , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".y , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z )";
// }
//}
//break;
//case WirePortDataType.FLOAT4x4:
//{
// if ( useRealValue )
// {
// result = precisionStr + "4x4( " + vecVal + ".x , " + vecVal + ".y , " + vecVal + ".z , 0 , " +
// vecVal + ".x , " + vecVal + ".y , " + vecVal + ".z , 0 , " +
// vecVal + ".x , " + vecVal + ".y , " + vecVal + ".z , 0 , " +
// vecVal + ".x , " + vecVal + ".y , " + vecVal + ".z , 0 )";
// }
// else
// {
// string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, parameterName );
// CurrentDataCollector.AddToLocalVariables( portCategory, -1, localVal );
// result = precisionStr + "4x4( " + localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , 0 , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , 0 , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , 0 , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , 0 )";
// }
//}
//break;
}
}
break;
case WirePortDataType.FLOAT4:
{
Vector4 vecVal = useRealValue ? (Vector4)value : Vector4.zero;
switch( newType )
{
case WirePortDataType.OBJECT: result = useRealValue ? precisionStr + "4( " + vecVal.x + " , " + vecVal.y + " , " + vecVal.z + " , " + vecVal.w + " )" : parameterName; break;
case WirePortDataType.FLOAT:
{
result = ( useRealValue ) ? vecVal.x.ToString() : parameterName + ".x";
}
break;
case WirePortDataType.FLOAT2:
{
result = ( useRealValue ) ? precisionStr + "2( " + vecVal.x + " , " + vecVal.y + " )" : parameterName + ".xy";
}
break;
case WirePortDataType.FLOAT3:
{
result = ( useRealValue ) ? precisionStr + "3( " + vecVal.x + " , " + vecVal.y + " , " + vecVal.z + " )" : parameterName + ".xyz";
}
break;
//case WirePortDataType.FLOAT4x4:
//{
// if ( useRealValue )
// {
// result = precisionStr + "4x4( " + vecVal + ".x , " + vecVal + ".y , " + vecVal + ".z , " + vecVal + ".w , " +
// vecVal + ".x , " + vecVal + ".y , " + vecVal + ".z , " + vecVal + ".w , " +
// vecVal + ".x , " + vecVal + ".y , " + vecVal + ".z , " + vecVal + ".w , " +
// vecVal + ".x , " + vecVal + ".y , " + vecVal + ".z , " + vecVal + ".w )";
// }
// else
// {
// string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, parameterName );
// CurrentDataCollector.AddToLocalVariables( portCategory, -1, localVal );
// result = precisionStr + "4x4( " + localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , " + localVarName + ".w , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , " + localVarName + ".w , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , " + localVarName + ".w , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , " + localVarName + ".w )";
// }
//}
//break;
case WirePortDataType.COLOR:
{
result = useRealValue ? precisionStr + "4( " + vecVal.x + " , " + vecVal.y + " , " + vecVal.z + " , " + vecVal.w + " )" : parameterName;
}
break;
}
}
break;
case WirePortDataType.FLOAT3x3:
{
//Matrix4x4 matrixVal = useRealValue ? ( Matrix4x4 ) value : Matrix4x4.identity;
//switch ( newType )
//{
// case WirePortDataType.OBJECT:
// case WirePortDataType.FLOAT4x4:
// {
// result = ( useRealValue ) ? precisionStr + "4x4(" + matrixVal.m00 + " , " + matrixVal.m01 + " , " + matrixVal.m02 + " , " + matrixVal.m03 + " , " +
// matrixVal.m10 + " , " + matrixVal.m11 + " , " + matrixVal.m12 + " , " + matrixVal.m10 + " , " +
// matrixVal.m20 + " , " + matrixVal.m21 + " , " + matrixVal.m22 + " , " + matrixVal.m20 + " , " +
// matrixVal.m30 + " , " + matrixVal.m31 + " , " + matrixVal.m32 + " , " + matrixVal.m30 + " )" : precisionStr + "4x4(" + parameterName + ")";
// }
// break;
//}
}
break;
case WirePortDataType.FLOAT4x4:
{
Matrix4x4 matrixVal = useRealValue ? (Matrix4x4)value : Matrix4x4.identity;
switch( newType )
{
case WirePortDataType.OBJECT:
{
result = ( useRealValue ) ? precisionStr + "4x4(" + matrixVal.m00 + " , " + matrixVal.m01 + " , " + matrixVal.m02 + " , " + matrixVal.m03 + " , " +
matrixVal.m10 + " , " + matrixVal.m11 + " , " + matrixVal.m12 + " , " + matrixVal.m10 + " , " +
matrixVal.m20 + " , " + matrixVal.m21 + " , " + matrixVal.m22 + " , " + matrixVal.m20 + " , " +
matrixVal.m30 + " , " + matrixVal.m31 + " , " + matrixVal.m32 + " , " + matrixVal.m30 + " )" : parameterName;
}
break;
}
}
break;
case WirePortDataType.COLOR:
{
Color colorValue = ( useRealValue ) ? (Color)value : Color.black;
switch( newType )
{
case WirePortDataType.OBJECT: result = useRealValue ? precisionStr + "4( " + colorValue.r + " , " + colorValue.g + " , " + colorValue.b + " , " + colorValue.a + " )" : parameterName; break;
case WirePortDataType.FLOAT:
{
result = ( useRealValue ) ? colorValue.r.ToString() : parameterName + ".r";
}
break;
case WirePortDataType.FLOAT2:
{
result = ( useRealValue ) ? precisionStr + "2( " + colorValue.r + " , " + colorValue.g + " )" : parameterName + ".rg";
}
break;
case WirePortDataType.FLOAT3:
{
result = ( useRealValue ) ? precisionStr + "3( " + colorValue.r + " , " + colorValue.g + " , " + colorValue.b + " )" : parameterName + ".rgb";
}
break;
case WirePortDataType.FLOAT4:
{
result = useRealValue ? precisionStr + "4( " + colorValue.r + " , " + colorValue.g + " , " + colorValue.b + " , " + colorValue.a + " )" : parameterName;
}
break;
//case WirePortDataType.FLOAT4x4:
//{
// if ( useRealValue )
// {
// result = precisionStr + "4x4( " + colorValue.r + " , " + colorValue.g + " , " + colorValue.b + " , " + colorValue.a + " , " +
// colorValue.r + " , " + colorValue.g + " , " + colorValue.b + " , " + colorValue.a + " , " +
// colorValue.r + " , " + colorValue.g + " , " + colorValue.b + " , " + colorValue.a + " , " +
// colorValue.r + " , " + colorValue.g + " , " + colorValue.b + " , " + colorValue.a + " )";
// }
// else
// {
// string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, parameterName );
// CurrentDataCollector.AddToLocalVariables( portCategory, -1, localVal );
// result = precisionStr + "4x4( " + localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , " + localVarName + ".w , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , " + localVarName + ".w , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , " + localVarName + ".w , " +
// localVarName + ".x , " + localVarName + ".y , " + localVarName + ".z , " + localVarName + ".w )";
// }
//}
//break;
}
}
break;
case WirePortDataType.INT:
{
switch( newType )
{
case WirePortDataType.OBJECT: result = useRealValue ? value.ToString() : parameterName; break;
case WirePortDataType.FLOAT2:
case WirePortDataType.FLOAT3:
case WirePortDataType.COLOR:
case WirePortDataType.FLOAT4:
{
string localVal = CreateLocalValueName( currentPrecision, newType, localVarName, ( ( useRealValue ) ? value.ToString() : parameterName ) );
dataCollector.AddToLocalVariables( dataCollector.PortCategory, -1, localVal );
result = localVarName;
}
break;
case WirePortDataType.FLOAT3x3:
{
string localVal = CreateLocalValueName( currentPrecision, oldType, localVarName, ( ( useRealValue ) ? value.ToString() : parameterName ) );
dataCollector.AddToLocalVariables( dataCollector.PortCategory, -1, localVal );
result = localVarName;
}
break;
case WirePortDataType.FLOAT4x4:
{
string localVal = CreateLocalValueName( currentPrecision, oldType, localVarName, ( ( useRealValue ) ? value.ToString() : parameterName ) );
dataCollector.AddToLocalVariables( dataCollector.PortCategory, -1, localVal );
result = localVarName;
}
break;
case WirePortDataType.FLOAT:
{
result = ( useRealValue ) ? ( (int)value ).ToString() : "(float)" + parameterName;
}
break;
}
}
break;
}
if( result.Equals( string.Empty ) )
{
result = "0";
string warningStr = string.Format( "Unable to cast from {0} to {1}. Generating dummy data ( {2} )", oldType, newType, result );
if( oldType == WirePortDataType.SAMPLER1D || oldType == WirePortDataType.SAMPLER2D || oldType == WirePortDataType.SAMPLER3D || oldType == WirePortDataType.SAMPLERCUBE )
{
warningStr = string.Format( "Unable to cast from {0} to {1}. You might want to use a Texture Sample node and connect it to the 'Tex' port. Generating dummy data ( {2} )", oldType, newType, result );
}
ShowMessage( warningStr, MessageSeverity.Warning );
}
return result;
}
public static bool CanCast( WirePortDataType from, WirePortDataType to )
{
if( from == WirePortDataType.OBJECT || to == WirePortDataType.OBJECT || from == to )
return true;
switch( from )
{
case WirePortDataType.FLOAT:
{
if( to == WirePortDataType.INT )
return true;
}
break;
case WirePortDataType.FLOAT2:
{
return false;
}
case WirePortDataType.FLOAT3:
{
if( to == WirePortDataType.COLOR ||
to == WirePortDataType.FLOAT4 )
return true;
}
break;
case WirePortDataType.FLOAT4:
{
if( to == WirePortDataType.FLOAT3 ||
to == WirePortDataType.COLOR )
return true;
}
break;
case WirePortDataType.FLOAT3x3:
{
if( to == WirePortDataType.FLOAT4x4 )
return true;
}
break;
case WirePortDataType.FLOAT4x4:
{
if( to == WirePortDataType.FLOAT3x3 )
return true;
}
break;
case WirePortDataType.COLOR:
{
if( to == WirePortDataType.FLOAT3 ||
to == WirePortDataType.FLOAT4 )
return true;
}
break;
case WirePortDataType.INT:
{
if( to == WirePortDataType.FLOAT )
return true;
}
break;
}
return false;
}
public static int GetChannelsAmount( WirePortDataType type )
{
switch( type )
{
case WirePortDataType.OBJECT: return 0;
case WirePortDataType.FLOAT: return 1;
case WirePortDataType.FLOAT2: return 2;
case WirePortDataType.FLOAT3: return 3;
case WirePortDataType.FLOAT4: return 4;
case WirePortDataType.FLOAT3x3: return 9;
case WirePortDataType.FLOAT4x4: return 16;
case WirePortDataType.COLOR: return 4;
case WirePortDataType.INT: return 1;
}
return 0;
}
public static WirePortDataType GetWireTypeForChannelAmount( int channelAmount )
{
switch( channelAmount )
{
case 1: return WirePortDataType.FLOAT;
case 2: return WirePortDataType.FLOAT2;
case 3: return WirePortDataType.FLOAT3;
case 4: return WirePortDataType.FLOAT4;
case 9: return WirePortDataType.FLOAT3x3;
case 16: return WirePortDataType.FLOAT4x4;
}
return WirePortDataType.FLOAT;
}
public static string GenerateUniformName( string dataType, string dataName ) { return string.Format( Constants.UniformDec, dataType, dataName ); }
public static string GeneratePropertyName( string name, PropertyType propertyType, bool forceUnderscore = false )
{
if( string.IsNullOrEmpty( name ) )
return name;
name = RemoveInvalidCharacters( name );
if( propertyType != PropertyType.Global || forceUnderscore )
{
if( name[ 0 ] != '_' )
{
name = '_' + name;
}
}
return name;
}
public static string UrlReplaceInvalidStrings( string originalString )
{
foreach( KeyValuePair<string, string> kvp in Constants.UrlReplacementStringValues )
{
originalString = originalString.Replace( kvp.Key, kvp.Value );
}
return originalString;
}
public static string ReplaceInvalidStrings( string originalString )
{
foreach( KeyValuePair<string, string> kvp in Constants.ReplacementStringValues )
{
originalString = originalString.Replace( kvp.Key, kvp.Value );
}
return originalString;
}
public static string RemoveWikiInvalidCharacters( string originalString )
{
for( int i = 0; i < Constants.WikiInvalidChars.Length; i++ )
{
originalString = originalString.Replace( Constants.WikiInvalidChars[ i ], string.Empty );
}
return originalString;
}
public static string RemoveInvalidCharacters( string originalString )
{
for( int i = 0; i < Constants.OverallInvalidChars.Length; i++ )
{
originalString = originalString.Replace( Constants.OverallInvalidChars[ i ], string.Empty );
}
return originalString;
}
public static string RemoveShaderInvalidCharacters( string originalString )
{
originalString = originalString.Replace( '\\', '/' );
for( int i = 0; i < Constants.ShaderInvalidChars.Length; i++ )
{
originalString = originalString.Replace( Constants.ShaderInvalidChars[ i ], string.Empty );
}
return originalString;
}
public static bool IsUnityNativeShader( string path ) { return m_unityNativeShaderPaths.ContainsKey( path ); }
public static string GetComponentForPosition( int pos, WirePortDataType type, bool addDot = false )
{
string result = addDot ? "." : string.Empty;
switch( pos )
{
case 0:
{
return ( ( type == WirePortDataType.COLOR ) ? ( result + "r" ) : ( result + "x" ) );
}
case 1:
{
return ( ( type == WirePortDataType.COLOR ) ? ( result + "g" ) : ( result + "y" ) );
}
case 2:
{
return ( ( type == WirePortDataType.COLOR ) ? ( result + "b" ) : ( result + "z" ) );
}
case 3:
{
return ( ( type == WirePortDataType.COLOR ) ? ( result + "a" ) : ( result + "w" ) );
}
}
return string.Empty;
}
public static string InvalidParameter( ParentNode node )
{
ShowMessage( "Invalid entrance type on node" + node, MessageSeverity.Error );
return "0";
}
public static string NoConnection( ParentNode node )
{
ShowMessage( "No Input connection on node" + node, MessageSeverity.Error );
return "0";
}
public static string UnknownError( ParentNode node )
{
ShowMessage( "Unknown error on node" + node, MessageSeverity.Error );
return "0";
}
public static string GetTex2DProperty( string name, TexturePropertyValues defaultValue ) { return name + "(\"" + name + "\", 2D) = \"" + defaultValue + "\" {}"; }
public static string AddBrackets( string value ) { return "( " + value + " )"; }
public static Color GetColorFromWireStatus( WireStatus status ) { return m_wireStatusToColor[ status ]; }
public static bool HasColorCategory( string category ) { return m_nodeCategoryToColor.ContainsKey( category ); }
public static void AddColorCategory( string category, Color color ) { m_nodeCategoryToColor.Add( category, color ); }
public static Color GetColorFromCategory( string category )
{
if( m_nodeCategoryToColor.ContainsKey( category ) )
return m_nodeCategoryToColor[ category ];
Debug.LogWarning( category + " category does not contain an associated color" );
return m_nodeCategoryToColor[ "Default" ];
}
public static string LatestOpenedFolder
{
get { return m_latestOpenedFolder; }
set { m_latestOpenedFolder = value; }
}
public static Shader CreateNewUnlit()
{
if( CurrentWindow == null )
return null;
string shaderName;
string pathName;
Shader newShader = null;
IOUtils.GetShaderName( out shaderName, out pathName, "MyUnlitShader", m_latestOpenedFolder );
if( !System.String.IsNullOrEmpty( shaderName ) && !System.String.IsNullOrEmpty( pathName ) )
{
CurrentWindow.CreateNewGraph( shaderName );
CurrentWindow.PreMadeShadersInstance.FlatColorSequence.Execute();
CurrentWindow.CurrentGraph.CurrentMasterNode.SetName( shaderName );
newShader = CurrentWindow.CurrentGraph.FireMasterNode( pathName, true );
AssetDatabase.Refresh();
}
return newShader;
}
public static Shader CreateNewEmpty( string customPath = null )
{
if( CurrentWindow == null )
return null;
string shaderName;
string pathName;
Shader newShader = null;
string path = AssetDatabase.GetAssetPath( Selection.activeObject );
if( path == "" )
{
path = "Assets";
}
else if( System.IO.Path.GetExtension( path ) != "" )
{
path = path.Replace( System.IO.Path.GetFileName( AssetDatabase.GetAssetPath( Selection.activeObject ) ), "" );
}
if( string.IsNullOrEmpty( customPath ) )
{
IOUtils.GetShaderName( out shaderName, out pathName, "New AmplifyShader", m_latestOpenedFolder );
}
else
{
pathName = customPath;
shaderName = "New AmplifyShader";
string uniquePath = pathName.Remove( 0, pathName.IndexOf( "Assets" ) );
string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath( uniquePath + shaderName + ".shader" );
pathName = assetPathAndName;
shaderName = assetPathAndName.Remove( 0, assetPathAndName.IndexOf( shaderName ) );
shaderName = shaderName.Remove( shaderName.Length - 7 );
}
if( !System.String.IsNullOrEmpty( shaderName ) && !System.String.IsNullOrEmpty( pathName ) )
{
m_latestOpenedFolder = pathName;
CurrentWindow.titleContent.text = AmplifyShaderEditorWindow.GenerateTabTitle( shaderName );
CurrentWindow.titleContent.image = ShaderIcon;
CurrentWindow.CreateNewGraph( shaderName );
CurrentWindow.LastOpenedLocation = pathName;
CurrentWindow.CurrentGraph.CurrentMasterNode.SetName( shaderName );
newShader = CurrentWindow.CurrentGraph.FireMasterNode( pathName, true );
AssetDatabase.Refresh();
}
return newShader;
}
public static Shader CreateNewEmptyTemplate( string templateGUID, string customPath = null )
{
if( CurrentWindow == null )
return null;
string shaderName;
string pathName;
Shader newShader = null;
string path = AssetDatabase.GetAssetPath( Selection.activeObject );
if( path == "" )
{
path = "Assets";
}
else if( System.IO.Path.GetExtension( path ) != "" )
{
path = path.Replace( System.IO.Path.GetFileName( AssetDatabase.GetAssetPath( Selection.activeObject ) ), "" );
}
if( string.IsNullOrEmpty( customPath ) )
{
IOUtils.GetShaderName( out shaderName, out pathName, "New AmplifyShader", m_latestOpenedFolder );
}
else
{
pathName = customPath;
shaderName = "New AmplifyShader";
string uniquePath = pathName.Remove( 0, pathName.IndexOf( "Assets" ) );
string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath( uniquePath + shaderName + ".shader" );
pathName = assetPathAndName;
shaderName = assetPathAndName.Remove( 0, assetPathAndName.IndexOf( shaderName ) );
shaderName = shaderName.Remove( shaderName.Length - 7 );
}
if( !System.String.IsNullOrEmpty( shaderName ) && !System.String.IsNullOrEmpty( pathName ) )
{
m_latestOpenedFolder = pathName;
CurrentWindow.titleContent.text = AmplifyShaderEditorWindow.GenerateTabTitle( shaderName );
CurrentWindow.titleContent.image = UIUtils.ShaderIcon;
CurrentWindow.CreateNewTemplateGraph( templateGUID );
CurrentWindow.CurrentGraph.CurrentMasterNode.SetName( shaderName );
newShader = CurrentWindow.CurrentGraph.FireMasterNode( pathName, true );
AssetDatabase.Refresh();
}
return newShader;
}
public static void SetDelayedMaterialMode( Material material )
{
if( CurrentWindow == null )
return;
CurrentWindow.SetDelayedMaterialMode( material );
}
public static void CreateEmptyFromInvalid( Shader shader )
{
if( CurrentWindow == null )
return;
CurrentWindow.CreateNewGraph( shader );
CurrentWindow.ForceRepaint();
}
public static void CreateEmptyFunction( AmplifyShaderFunction shaderFunction )
{
if( CurrentWindow == null )
return;
CurrentWindow.CreateNewFunctionGraph( shaderFunction );
CurrentWindow.SaveToDisk( false );
CurrentWindow.ForceRepaint();
}
public static void DrawFloat( UndoParentNode owner, ref Rect propertyDrawPos, ref float value, float newLabelWidth = 8 )
{
float labelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = newLabelWidth;
value = owner.EditorGUIFloatField( propertyDrawPos, " ", value, UIUtils.MainSkin.textField );
EditorGUIUtility.labelWidth = labelWidth;
}
public static GUIStyle GetCustomStyle( CustomStyle style )
{
return ( Initialized ) ? MainSkin.customStyles[ (int)style ] : null;
}
public static void SetCustomStyle( CustomStyle style, GUIStyle guiStyle )
{
if( MainSkin != null )
MainSkin.customStyles[ (int)style ] = new GUIStyle( guiStyle );
}
public static void OpenFile()
{
if( CurrentWindow == null )
return;
string newShader = EditorUtility.OpenFilePanel( "Select Shader to open", m_latestOpenedFolder, "shader" );
if( !System.String.IsNullOrEmpty( newShader ) )
{
m_latestOpenedFolder = newShader.Substring( 0, newShader.LastIndexOf( '/' ) + 1 );
int relFilenameId = newShader.IndexOf( Application.dataPath );
if( relFilenameId > -1 )
{
string relFilename = newShader.Substring( relFilenameId + Application.dataPath.Length - 6 );// -6 need to also copy the assets/ part
CurrentWindow.LoadFromDisk( relFilename );
}
else
{
ShowMessage( "Can only load shaders\nfrom inside the projects folder", MessageSeverity.Error );
}
}
}
public static bool DetectNodeLoopsFrom( ParentNode node, Dictionary<int, int> currentNodes )
{
if( currentNodes.ContainsKey( node.UniqueId ) )
{
currentNodes.Clear();
currentNodes = null;
return true;
}
currentNodes.Add( node.UniqueId, 1 );
bool foundLoop = false;
for( int i = 0; i < node.InputPorts.Count; i++ )
{
if( node.InputPorts[ i ].IsConnected )
{
ParentNode newNode = node.InputPorts[ i ].GetOutputNode();
if( newNode.InputPorts.Count > 0 )
{
Dictionary<int, int> newDict = new Dictionary<int, int>();
foreach( KeyValuePair<int, int> entry in currentNodes )
{
newDict.Add( entry.Key, entry.Value );
}
foundLoop = foundLoop || DetectNodeLoopsFrom( newNode, newDict );
if( foundLoop )
break;
}
}
}
currentNodes.Clear();
currentNodes = null;
return foundLoop;
}
public static ParentNode CreateNode( System.Type type, bool registerUndo, Vector2 pos, int nodeId = -1, bool addLast = true )
{
if( CurrentWindow != null )
{
return CurrentWindow.CurrentGraph.CreateNode( type, registerUndo, pos, nodeId, addLast );
}
return null;
}
public static void DestroyNode( int nodeId )
{
if( CurrentWindow != null )
{
CurrentWindow.CurrentGraph.DestroyNode( nodeId );
}
}
public static void ShowMessage( string message, MessageSeverity severity = MessageSeverity.Normal, bool registerTimestamp = true )
{
if( CurrentWindow != null )
{
CurrentWindow.ShowMessage( message, severity, registerTimestamp );
}
}
public static ParentNode GetNode( int nodeId )
{
if( CurrentWindow != null )
{
return CurrentWindow.CurrentGraph.GetNode( nodeId );
}
return null;
}
public static void DeleteConnection( bool isInput, int nodeId, int portId, bool registerOnLog, bool propagateCallback )
{
if( CurrentWindow != null )
{
CurrentWindow.DeleteConnection( isInput, nodeId, portId, registerOnLog, propagateCallback );
}
}
public static void ConnectInputToOutput( int inNodeId, int inPortId, int outNodeId, int outPortId )
{
if( CurrentWindow != null )
{
CurrentWindow.ConnectInputToOutput( inNodeId, inPortId, outNodeId, outPortId );
}
}
public static Shader CreateNewGraph( string name )
{
if( CurrentWindow != null )
{
return CurrentWindow.CreateNewGraph( name );
}
return null;
}
public static void SetConnection( int InNodeId, int InPortId, int OutNodeId, int OutPortId )
{
if( CurrentWindow != null )
{
CurrentWindow.CurrentGraph.SetConnection( InNodeId, InPortId, OutNodeId, OutPortId );
}
}
public static bool IsChannelAvailable( int channelId )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.IsChannelAvailable( channelId );
}
return false;
}
public static bool ReleaseUVChannel( int nodeId, int channelId )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.ReleaseUVChannel( nodeId, channelId );
}
return false;
}
public static bool RegisterUVChannel( int nodeId, int channelId, string name )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.RegisterUVChannel( nodeId, channelId, name );
}
return false;
}
public static void GetFirstAvailableName( int nodeId, WirePortDataType type, out string outProperty, out string outInspector, bool useCustomPrefix = false, string customPrefix = null )
{
outProperty = string.Empty;
outInspector = string.Empty;
if( CurrentWindow != null )
{
CurrentWindow.DuplicatePrevBufferInstance.GetFirstAvailableName( nodeId, type, out outProperty, out outInspector, useCustomPrefix, customPrefix );
}
}
public static bool RegisterUniformName( int nodeId, string name )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.RegisterUniformName( nodeId, name );
}
return false;
}
public static bool ReleaseUniformName( int nodeId, string name )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.ReleaseUniformName( nodeId, name );
}
return false;
}
public static bool IsUniformNameAvailable( string name )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.IsUniformNameAvailable( name );
}
return false;
}
public static int CheckUniformNameOwner( string name )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.CheckUniformNameOwner( name );
}
return -1;
}
public static bool RegisterLocalVariableName( int nodeId, string name )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.RegisterLocalVariableName( nodeId, name );
}
return false;
}
public static bool ReleaseLocalVariableName( int nodeId, string name )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.ReleaseLocalVariableName( nodeId, name );
}
return false;
}
public static bool IsLocalvariableNameAvailable( string name )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.IsLocalvariableNameAvailable( name );
}
return false;
}
public static string GetChannelName( int channelId )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.GetChannelName( channelId );
}
return string.Empty;
}
public static void SetChannelName( int channelId, string name )
{
if( CurrentWindow != null )
{
CurrentWindow.DuplicatePrevBufferInstance.SetChannelName( channelId, name );
}
}
public static int RegisterFirstAvailableChannel( int nodeId, string name )
{
if( CurrentWindow != null )
{
return CurrentWindow.DuplicatePrevBufferInstance.RegisterFirstAvailableChannel( nodeId, name );
}
return -1;
}
public static bool DisplayDialog( string shaderPath )
{
string value = System.String.Format( "Save changes to the shader {0} before closing?", shaderPath );
return EditorUtility.DisplayDialog( "Load selected", value, "Yes", "No" );
}
public static void ForceUpdateFromMaterial()
{
if( CurrentWindow != null )
{
// CurrentWindow.Focus();
CurrentWindow.ForceUpdateFromMaterial();
}
}
public static void MarkToRepaint() { if( CurrentWindow != null ) CurrentWindow.MarkToRepaint(); }
public static void RequestSave() { if( CurrentWindow != null ) CurrentWindow.RequestSave(); }
public static string FloatToString( float value )
{
string floatStr = value.ToString();
if( value % 1 == 0 )
{
floatStr += ".0";
}
return floatStr;
}
public static int CurrentVersion()
{
if( CurrentWindow != null )
{
return CurrentWindow.CurrentVersion;
}
return -1;
}
public static int CurrentShaderVersion()
{
if( CurrentWindow != null )
{
return CurrentWindow.CurrentGraph.LoadedShaderVersion;
}
return -1;
}
public static bool IsProperty( PropertyType type ) { return ( type == PropertyType.Property || type == PropertyType.InstancedProperty ); }
public static MasterNode CurrentMasterNode()
{
if( CurrentWindow != null )
{
return CurrentWindow.CurrentGraph.CurrentMasterNode;
}
return null;
}
public static void AddVirtualTextureCount() { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.AddVirtualTextureCount(); } }
public static bool HasVirtualTexture()
{
if( CurrentWindow != null )
{
return CurrentWindow.CurrentGraph.HasVirtualTexture;
}
return false;
}
public static void RemoveVirtualTextureCount() { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.RemoveVirtualTextureCount(); } }
public static void AddInstancePropertyCount() { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.AddInstancePropertyCount(); } }
public static bool IsInstancedShader()
{
if( CurrentWindow != null )
{
return CurrentWindow.CurrentGraph.IsInstancedShader;
}
return false;
}
public static void RemoveInstancePropertyCount() { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.RemoveInstancePropertyCount(); } }
//public static void AddNormalDependentCount() { if ( CurrentWindow != null ) { CurrentWindow.CurrentGraph.AddNormalDependentCount(); } }
//public static void RemoveNormalDependentCount() { if ( CurrentWindow != null ) { CurrentWindow.CurrentGraph.RemoveNormalDependentCount(); } }
//public static bool IsNormalDependent()
//{
// if ( CurrentWindow != null )
// {
// return CurrentWindow.CurrentGraph.IsNormalDependent;
// }
// return false;
//}
public static void CopyValuesFromMaterial( Material mat )
{
if( CurrentWindow != null )
{
CurrentWindow.CurrentGraph.CopyValuesFromMaterial( mat );
}
}
// Sampler Node
public static void RegisterSamplerNode( SamplerNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.SamplerNodes.AddNode( node ); } }
public static void UnregisterSamplerNode( SamplerNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.SamplerNodes.RemoveNode( node ); } }
public static string[] SamplerNodeArr() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.SamplerNodes.NodesArr; } return null; }
public static SamplerNode GetSamplerNode( int idx ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.SamplerNodes.GetNode( idx ); } return null; }
public static void UpdateSamplerDataNode( int nodeIdx, string data ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.SamplerNodes.UpdateDataOnNode( nodeIdx, data ); } }
public static int GetSamplerNodeRegisterId( int uniqueId ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.SamplerNodes.GetNodeRegisterId( uniqueId ); } return -1; }
public static int GetSamplerNodeAmount() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.SamplerNodes.NodesList.Count; } return -1; }
// Texture Property
public static void RegisterTexturePropertyNode( TexturePropertyNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.TexturePropertyNodes.AddNode( node ); } }
public static void UnregisterTexturePropertyNode( TexturePropertyNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.TexturePropertyNodes.RemoveNode( node ); } }
public static string[] TexturePropertyNodeArr() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.TexturePropertyNodes.NodesArr; } return null; }
public static TexturePropertyNode GetTexturePropertyNode( int idx ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.TexturePropertyNodes.GetNode( idx ); } return null; }
public static void UpdateTexturePropertyDataNode( int nodeIdx, string data ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.TexturePropertyNodes.UpdateDataOnNode( nodeIdx, data ); } }
public static int GetTexturePropertyNodeRegisterId( int uniqueId ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.TexturePropertyNodes.GetNodeRegisterId( uniqueId ); } return -1; }
public static int GetTexturePropertyNodeAmount() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.TexturePropertyNodes.NodesList.Count; } return -1; }
// Texture Array
public static void RegisterTextureArrayNode( TextureArrayNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.TextureArrayNodes.AddNode( node ); } }
public static void UnregisterTextureArrayNode( TextureArrayNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.TextureArrayNodes.RemoveNode( node ); } }
public static string[] TextureArrayNodeArr() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.TextureArrayNodes.NodesArr; } return null; }
public static TextureArrayNode GetTextureArrayNode( int idx ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.TextureArrayNodes.GetNode( idx ); } return null; }
public static void UpdateTextureArrayDataNode( int nodeIdx, string data ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.TextureArrayNodes.UpdateDataOnNode( nodeIdx, data ); } }
public static int GetTextureArrayNodeRegisterId( int uniqueId ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.TextureArrayNodes.GetNodeRegisterId( uniqueId ); } return -1; }
public static int GetTextureArrayNodeAmount() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.TextureArrayNodes.NodesList.Count; } return -1; }
// Property Node
public static void RegisterPropertyNode( PropertyNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.PropertyNodes.AddNode( node ); } }
public static void UnregisterPropertyNode( PropertyNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.PropertyNodes.RemoveNode( node ); } }
public static string[] PropertyNodeNodeArr() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.PropertyNodes.NodesArr; } return null; }
public static PropertyNode GetPropertyNode( int idx ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.PropertyNodes.GetNode( idx ); } return null; }
public static void UpdatePropertyDataNode( int nodeIdx, string data ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.PropertyNodes.UpdateDataOnNode( nodeIdx, data ); } }
public static int GetPropertyNodeRegisterId( int uniqueId ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.PropertyNodes.GetNodeRegisterId( uniqueId ); } return -1; }
public static List<PropertyNode> PropertyNodesList() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.PropertyNodes.NodesList; } return null; }
public static int GetPropertyNodeAmount() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.PropertyNodes.NodesList.Count; } return -1; }
// Function Inputs
public static void RegisterFunctionInputNode( FunctionInput node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.FunctionInputNodes.AddNode( node ); } }
public static void UnregisterFunctionInputNode( FunctionInput node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.FunctionInputNodes.RemoveNode( node ); } }
public static void UpdateFunctionInputData( int nodeIdx, string data ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.FunctionInputNodes.UpdateDataOnNode( nodeIdx, data ); } }
public static List<FunctionInput> FunctionInputList() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.FunctionInputNodes.NodesList; } return null; }
// Function Nodes
public static void RegisterFunctionNode( FunctionNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.FunctionNodes.AddNode( node ); } }
public static void UnregisterFunctionNode( FunctionNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.FunctionNodes.RemoveNode( node ); } }
public static void UpdateFunctionData( int nodeIdx, string data ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.FunctionNodes.UpdateDataOnNode( nodeIdx, data ); } }
public static List<FunctionNode> FunctionList() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.FunctionNodes.NodesList; } return null; }
// Function Outputs
public static void RegisterFunctionOutputNode( FunctionOutput node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.FunctionOutputNodes.AddNode( node ); } }
public static void UnregisterFunctionOutputNode( FunctionOutput node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.FunctionOutputNodes.RemoveNode( node ); } }
public static void UpdateFunctionOutputData( int nodeIdx, string data ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.FunctionOutputNodes.UpdateDataOnNode( nodeIdx, data ); } }
public static List<FunctionOutput> FunctionOutputList() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.FunctionOutputNodes.NodesList; } return null; }
// Screen Color Node
public static void RegisterScreenColorNode( ScreenColorNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.ScreenColorNodes.AddNode( node ); } }
public static void UnregisterScreenColorNode( ScreenColorNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.ScreenColorNodes.RemoveNode( node ); } }
public static string[] ScreenColorNodeArr() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.ScreenColorNodes.NodesArr; } return null; }
public static ScreenColorNode GetScreenColorNode( int idx ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.ScreenColorNodes.GetNode( idx ); } return null; }
public static int GetScreenColorNodeRegisterId( int uniqueId ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.ScreenColorNodes.GetNodeRegisterId( uniqueId ); } return -1; }
public static void UpdateScreenColorDataNode( int nodeIdx, string data ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.ScreenColorNodes.UpdateDataOnNode( nodeIdx, data ); } }
public static int GetScreenColorNodeAmount() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.ScreenColorNodes.NodesList.Count; } return -1; }
// Local Var Node
public static int RegisterLocalVarNode( RegisterLocalVarNode node ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.LocalVarNodes.AddNode( node ); } return -1; }
public static void UnregisterLocalVarNode( RegisterLocalVarNode node ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.LocalVarNodes.RemoveNode( node ); } }
public static string[] LocalVarNodeArr() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.LocalVarNodes.NodesArr; } return null; }
public static int LocalVarNodeAmount() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.LocalVarNodes.NodesList.Count; } return 0; }
public static int GetLocalVarNodeRegisterId( int uniqueId ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.LocalVarNodes.GetNodeRegisterId( uniqueId ); } return -1; }
public static RegisterLocalVarNode GetLocalVarNode( int idx ) { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.LocalVarNodes.GetNode( idx ); } return null; }
public static void UpdateLocalVarDataNode( int nodeIdx, string data ) { if( CurrentWindow != null ) { CurrentWindow.CurrentGraph.LocalVarNodes.UpdateDataOnNode( nodeIdx, data ); } }
public static void FocusOnNode( ParentNode node, float zoom, bool selectNode ) { if( CurrentWindow != null ) { CurrentWindow.FocusOnNode( node, zoom, selectNode ); } }
public static PrecisionType CurrentPrecision() { if( CurrentWindow != null ) { return CurrentWindow.CurrentGraph.CurrentPrecision; } return PrecisionType.Float; }
public static string CurrentPrecisionCg() { if( CurrentWindow != null ) { return m_precisionTypeToCg[ CurrentWindow.CurrentGraph.CurrentPrecision ]; } return m_precisionTypeToCg[ PrecisionType.Float ]; }
public static PrecisionType GetFinalPrecision( PrecisionType precision )
{
if( CurrentWindow != null && CurrentWindow.CurrentGraph != null )
{
PrecisionType mainPrecision = CurrentWindow.CurrentGraph.CurrentPrecision;
if( (int)mainPrecision > (int)precision )
return mainPrecision;
}
return precision;
}
public static bool GetNodeAvailabilityInBitArray( int bitArray, NodeAvailability availability ) { return ( bitArray & (int)availability ) != 0; }
public static bool GetCategoryInBitArray( int bitArray, MasterNodePortCategory category ) { return ( bitArray & (int)category ) != 0; }
public static void SetCategoryInBitArray( ref int bitArray, MasterNodePortCategory category ) { bitArray = bitArray | (int)category; }
public static int GetPriority( WirePortDataType type ) { return m_portPriority[ type ]; }
public static void ShowIncompatiblePortMessage( bool fromInput, ParentNode inNode, WirePort inPort, ParentNode outNode, WirePort outPort )
{
string inPortName = inPort.Name.Equals( Constants.EmptyPortValue ) ? inPort.PortId.ToString() : inPort.Name;
string outPortName = outPort.Name.Equals( Constants.EmptyPortValue ) ? outPort.PortId.ToString() : outPort.Name;
ShowMessage( string.Format( ( fromInput ? IncorrectInputConnectionErrorMsg : IncorrectOutputConnectionErrorMsg ), inPortName, inNode.Attributes.Name, inPort.DataType, outPort.DataType, outPortName, outNode.Attributes.Name ) );
}
public static void ShowNoVertexModeNodeMessage( ParentNode node )
{
ShowMessage( string.Format( NoVertexModeNodeWarning, node.Attributes.Name ), MessageSeverity.Warning );
}
public static int TotalExampleMaterials { get { return m_exampleMaterialIDs.Count; } }
public static int ShaderIndentLevel
{
get { return m_shaderIndentLevel; }
set
{
m_shaderIndentLevel = Mathf.Max( value, 0 );
m_shaderIndentTabs = string.Empty;
for( int i = 0; i < m_shaderIndentLevel; i++ ) { m_shaderIndentTabs += "\t"; }
}
}
public static string ShaderIndentTabs { get { return m_shaderIndentTabs; } }
public static void AddLineToShaderBody( ref string ShaderBody, string line ) { ShaderBody += m_shaderIndentTabs + line; }
public static void AddMultiLineToShaderBody( ref string ShaderBody, string[] lines )
{
for( int i = 0; i < lines.Length; i++ )
{
ShaderBody += m_shaderIndentTabs + lines[ i ];
}
}
public static void ClearUndoHelper()
{
m_undoHelper.Clear();
}
public static bool CheckUndoNode( ParentNode node )
{
if( node == null )
return false;
if( m_undoHelper.ContainsKey( node.UniqueId ) )
{
return false;
}
m_undoHelper.Add( node.UniqueId, node );
EditorUtility.SetDirty( node );
return true;
}
public static void MarkUndoAction()
{
SerializeHelperCounter = 2;
}
public static bool SerializeFromUndo()
{
if( SerializeHelperCounter > 0 )
{
SerializeHelperCounter--;
return true;
}
return false;
}
public static int GetKeywordId( string keyword )
{
if( AvailableKeywordsDict.Count != AvailableKeywords.Length )
{
AvailableKeywordsDict.Clear();
for( int i = 1; i < AvailableKeywords.Length; i++ )
{
AvailableKeywordsDict.Add( AvailableKeywords[ i ], i );
}
}
if( AvailableKeywordsDict.ContainsKey( keyword ) )
{
return AvailableKeywordsDict[ keyword ];
}
return 0;
}
}
}
| 40.496154 | 277 | 0.692321 | [
"Unlicense"
] | hosoji/Grafight | Grafight/Assets/AmplifyShaderEditor/Plugins/Editor/Utils/UIUtils.cs | 94,761 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FilterPipelineExample.Filters;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace FilterPipelineExample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(new GlobalLogAsyncActionFilter());
options.Filters.Add(new GlobalLogAsyncAuthorizationFilter());
options.Filters.Add(new GlobalLogAsyncExceptionFilter());
options.Filters.Add(new GlobalLogAsyncResourceFilter());
options.Filters.Add(new GlobalLogAsyncResultFilter());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
} | 32.105263 | 106 | 0.604918 | [
"MIT"
] | AnzhelikaKravchuk/asp-dot-net-core-in-action | chapter13/2.0/FilterPipelineExample/FilterPipelineExample/Startup.cs | 1,832 | C# |
using Chii.OneBot.SDK.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Chii.OneBot.SDK.Model.Params
{
/// <summary>
/// 群組單人禁言
/// </summary>
internal class SetGroupBanParams : IParams
{
/// <summary>
/// 群號
/// </summary>
[JsonPropertyName("group_id")]
public long GroupId { get; set; }
/// <summary>
/// 要禁言的 QQ 號
/// </summary>
[JsonPropertyName("user_id")]
public long UserId { get; set; }
/// <summary>
/// 禁言時長,單位秒,0 表示取消禁言
/// </summary>
[JsonPropertyName("duration")]
public int Duration { get; set; }
}
}
| 22.514286 | 46 | 0.568528 | [
"Apache-2.0"
] | MiharaIchiro/Chii.OneBot.SDK | src/Model/Param/SetGroupBanParams.cs | 846 | C# |
using Microsoft.Xna.Framework;
using System;
using System.IO;
namespace FSO.Content.Model
{
public class CityMap
{
private static Color TERRAIN_GRASS = new Color(0, 255, 0);
private static Color TERRAIN_WATER = new Color(12, 0, 255);
private static Color TERRAIN_SNOW = new Color(255, 255, 255);
private static Color TERRAIN_ROCK = new Color(255, 0, 0);
private static Color TERRAIN_SAND = new Color(255, 255, 0);
private string _Directory;
public ITextureRef Elevation { get; internal set; }
public ITextureRef ForestDensity { get; internal set; }
public ITextureRef ForestType { get; internal set; }
public ITextureRef RoadMap { get; internal set; }
public ITextureRef TerrainTypeTex { get; internal set; }
public ITextureRef VertexColour { get; internal set; }
public ITextureRef Thumbnail { get; internal set; }
private TextureValueMap<TerrainType> _TerrainType;
private TextureValueMap<byte> _ElevationMap;
private TextureValueMap<byte> _RoadMap;
public CityMap(string directory)
{
_Directory = directory;
string ext = "bmp";
if (!File.Exists(Path.Combine(directory, "elevation.bmp")))
{
ext = "png"; //fso maps use png
}
Elevation = new FileTextureRef(Path.Combine(directory, "elevation."+ext));
ForestDensity = new FileTextureRef(Path.Combine(directory, "forestdensity." + ext));
ForestType = new FileTextureRef(Path.Combine(directory, "foresttype." + ext));
RoadMap = new FileTextureRef(Path.Combine(directory, "roadmap." + ext));
TerrainTypeTex = new FileTextureRef(Path.Combine(directory, "terraintype." + ext));
VertexColour = new FileTextureRef(Path.Combine(directory, "vertexcolor." + ext));
Thumbnail = new FileTextureRef(Path.Combine(directory, "thumbnail." + ext));
_TerrainType = new TextureValueMap<Model.TerrainType>(TerrainTypeTex, x =>
{
if(x == TERRAIN_GRASS){
return Model.TerrainType.GRASS;
}else if(x == TERRAIN_WATER)
{
return Model.TerrainType.WATER;
}else if(x == TERRAIN_SNOW)
{
return Model.TerrainType.SNOW;
}else if(x == TERRAIN_ROCK)
{
return Model.TerrainType.ROCK;
}else if(x == TERRAIN_SAND)
{
return Model.TerrainType.SAND;
}
return default(TerrainType);
});
_ElevationMap = new TextureValueMap<byte>(Elevation, x => x.R);
_RoadMap = new TextureValueMap<byte>(RoadMap, x => x.R);
}
public TerrainType GetTerrain(int x, int y)
{
return _TerrainType.Get(x, y);
}
public byte GetRoad(int x, int y)
{
return _RoadMap.Get(x, y);
}
public byte GetElevation(int x, int y)
{
return _ElevationMap.Get(x, y);
}
public TerrainBlend GetBlend(int x, int y)
{
TerrainType sample;
TerrainType t;
var edges = new TerrainType[] { TerrainType.NULL, TerrainType.NULL, TerrainType.NULL, TerrainType.NULL,
TerrainType.NULL, TerrainType.NULL, TerrainType.NULL, TerrainType.NULL};
sample = GetTerrain(x, y);
t = GetTerrain(x, y-1);
if ((y - 1 >= 0) && (t > sample)) edges[0] = t;
t = GetTerrain(x + 1, y-1);
if ((y - 1 >= 0) && (x + 1 < 512) && (t > sample)) edges[1] = t;
t = GetTerrain(x+1, y);
if ((x + 1 < 512) && (t > sample)) edges[2] = t;
t = GetTerrain(x + 1, y + 1);
if ((x + 1 < 512) && (y + 1 < 512) && (t > sample)) edges[3] = t;
t = GetTerrain(x, y + 1);
if ((y + 1 < 512) && (t > sample)) edges[4] = t;
t = GetTerrain(x-1, y + 1);
if ((y + 1 < 512) && (x - 1 >= 0) && (t > sample)) edges[5] = t;
t = t = GetTerrain(x-1, y);
if ((x - 1 >= 0) && (t > sample)) edges[6] = t;
t = t = GetTerrain(x - 1, y - 1);
if ((y - 1 >= 0) && (x - 1 >= 0) && (t > sample)) edges[7] = t;
int binary = 0;
for (int i=0; i<8; i++)
binary |= ((edges[i] > TerrainType.NULL) ? (1 << i) : 0);
int waterbinary = 0;
for (int i = 0; i < 8; i++)
waterbinary |= ((edges[i] == TerrainType.WATER) ? (1 << i) : 0);
TerrainType maxEdge = TerrainType.WATER;
for (int i = 0; i < 8; i++)
if (edges[i] < maxEdge && edges[i] != TerrainType.NULL) maxEdge = edges[i];
TerrainBlend ReturnBlend = new TerrainBlend();
ReturnBlend.Base = sample;
ReturnBlend.Blend = maxEdge;
ReturnBlend.AdjFlags = (byte)binary;
ReturnBlend.WaterFlags = (byte)waterbinary;
return ReturnBlend;
}
}
public struct TerrainBlend
{
public TerrainType Base;
public TerrainType Blend;
public byte AdjFlags;
public byte WaterFlags;
}
public enum TerrainType
{
WATER = 4,
ROCK = 2,
GRASS = 0,
SNOW = 3,
SAND = 1,
NULL = -1,
TS1DarkGrass = 5,
TS1AutumnGrass = 6,
TS1Cloud = 7
}
public class TextureValueMap <T>
{
private T[,] Values;
public TextureValueMap(ITextureRef texture, Func<Color, T> converter)
{
Values = new T[512, 512];
var image = texture.GetImage();
var bytes = image.Data;
var pixelSize = image.PixelSize;
// copy the bytes from bitmap to array
var index = 0;
for(var y=0; y < 512; y++){
for(var x=0; x < 512; x++){
var a = pixelSize == 3 ? 255 : bytes[index + 3];
var r = bytes[index + 2];
var g = bytes[index + 1];
var b = bytes[index];
index += pixelSize;
//The game actually uses the pixel coordinates as the lot coordinates
var color = new Color(r, g, b, a);
var value = converter(color);
Values[y, x] = value;
}
}
//image.UnlockBits(data);
}
public T Get(int x, int y)
{
if(x < 0 || y < 0 || x >= 512 || y >= 512){
return default(T);
}
return Values[y, x];
}
}
}
| 33.597087 | 115 | 0.498772 | [
"MPL-2.0"
] | HarryFreeMyLand/newso | Src/tso.content/model/CityMap.cs | 6,923 | C# |
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
namespace Microsoft.Azure.EventGridEdge.Samples.Common.Auth
{
public static class CertificateHelper
{
public static void ImportCertificate(params X509Certificate2[] certificates)
{
if (certificates != null)
{
StoreName storeName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? StoreName.CertificateAuthority : StoreName.Root;
StoreLocation storeLocation = StoreLocation.CurrentUser;
using (var store = new X509Store(storeName, storeLocation))
{
store.Open(OpenFlags.ReadWrite);
foreach (X509Certificate2 cert in certificates)
{
store.Add(cert);
}
}
}
}
public static bool IsCACertificate(X509Certificate2 certificate)
{
// https://tools.ietf.org/html/rfc3280#section-4.2.1.3
// The keyCertSign bit is asserted when the subject public key is
// used for verifying a signature on public key certificates. If the
// keyCertSign bit is asserted, then the cA bit in the basic
// constraints extension (section 4.2.1.10) MUST also be asserted.
// https://tools.ietf.org/html/rfc3280#section-4.2.1.10
// The cA boolean indicates whether the certified public key belongs to
// a CA. If the cA boolean is not asserted, then the keyCertSign bit in
// the key usage extension MUST NOT be asserted.
X509ExtensionCollection extensionCollection = certificate.Extensions;
foreach (X509Extension extension in extensionCollection)
{
if (extension is X509BasicConstraintsExtension basicConstraintExtension)
{
if (basicConstraintExtension.CertificateAuthority)
{
return true;
}
}
}
return false;
}
}
}
| 40.924528 | 140 | 0.585062 | [
"MIT"
] | Azure/event-grid-iot-edge | Common/auth/CertificateHelper.cs | 2,171 | C# |
// 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using static Microsoft.CodeAnalysis.Test.Extensions.SymbolExtensions;
using Xunit;
using Roslyn.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class SyntaxBinderTests : CompilingTestBase
{
[Fact, WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
public void EnumBinaryOps()
{
string source = @"
[Flags]
internal enum TestEnum
{
None,
Tags,
FilePath,
Capabilities,
Visibility,
AllProperties = FilePath | Visibility
}
class C {
public void Goo(){
var x = TestEnum.FilePath | TestEnum.Visibility;
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var orNodes = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().ToArray();
Assert.Equal(2, orNodes.Length);
var insideEnumDefinition = semanticModel.GetSymbolInfo(orNodes[0]);
var insideMethodBody = semanticModel.GetSymbolInfo(orNodes[1]);
Assert.False(insideEnumDefinition.IsEmpty);
Assert.False(insideMethodBody.IsEmpty);
Assert.NotEqual(insideEnumDefinition, insideMethodBody);
Assert.Equal("System.Int32 System.Int32.op_BitwiseOr(System.Int32 left, System.Int32 right)", insideEnumDefinition.Symbol.ToTestDisplayString());
Assert.Equal("TestEnum TestEnum.op_BitwiseOr(TestEnum left, TestEnum right)", insideMethodBody.Symbol.ToTestDisplayString());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void EnumBinaryOps_IOperation()
{
string source = @"
using System;
[Flags]
internal enum TestEnum
{
None,
Tags,
FilePath,
Capabilities,
Visibility,
AllProperties = FilePath | Visibility
}
class C
{
public void Goo()
{
var x = /*<bind>*/TestEnum.FilePath | TestEnum.Visibility/*</bind>*/;
Console.Write(x);
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: TestEnum, Constant: 6) (Syntax: 'TestEnum.Fi ... .Visibility')
Left:
IFieldReferenceOperation: TestEnum.FilePath (Static) (OperationKind.FieldReference, Type: TestEnum, Constant: 2) (Syntax: 'TestEnum.FilePath')
Instance Receiver:
null
Right:
IFieldReferenceOperation: TestEnum.Visibility (Static) (OperationKind.FieldReference, Type: TestEnum, Constant: 4) (Syntax: 'TestEnum.Visibility')
Instance Receiver:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(543895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543895")]
public void TestBug11947()
{
// Due to a long-standing bug, the native compiler allows underlying-enum with the same
// semantics as enum-underlying. (That is, the math is done in the underlying type and
// then cast back to the enum type.)
string source = @"
using System;
public enum E { Zero, One, Two };
class Test
{
static void Main()
{
E e = E.One;
int x = 3;
E r = x - e;
Console.Write(r);
E? en = E.Two;
int? xn = 2;
E? rn = xn - en;
Console.Write(rn);
}
}";
CompileAndVerify(source: source, expectedOutput: "TwoZero");
}
private const string StructWithUserDefinedBooleanOperators = @"
struct S
{
private int num;
private string str;
public S(int num, char chr)
{
this.num = num;
this.str = chr.ToString();
}
public S(int num, string str)
{
this.num = num;
this.str = str;
}
public static S operator & (S x, S y)
{
return new S(x.num & y.num, '(' + x.str + '&' + y.str + ')');
}
public static S operator | (S x, S y)
{
return new S(x.num | y.num, '(' + x.str + '|' + y.str + ')');
}
public static bool operator true(S s)
{
return s.num != 0;
}
public static bool operator false(S s)
{
return s.num == 0;
}
public override string ToString()
{
return this.num.ToString() + ':' + this.str;
}
}
";
[Fact]
public void TestUserDefinedLogicalOperators()
{
string source = @"
using System;
class C
{
static void Main()
{
S f = new S(0, 'f');
S t = new S(1, 't');
Console.WriteLine((f && f) && f);
Console.WriteLine((f && f) && t);
Console.WriteLine((f && t) && f);
Console.WriteLine((f && t) && t);
Console.WriteLine((t && f) && f);
Console.WriteLine((t && f) && t);
Console.WriteLine((t && t) && f);
Console.WriteLine((t && t) && t);
Console.WriteLine('-');
Console.WriteLine((f && f) || f);
Console.WriteLine((f && f) || t);
Console.WriteLine((f && t) || f);
Console.WriteLine((f && t) || t);
Console.WriteLine((t && f) || f);
Console.WriteLine((t && f) || t);
Console.WriteLine((t && t) || f);
Console.WriteLine((t && t) || t);
Console.WriteLine('-');
Console.WriteLine((f || f) && f);
Console.WriteLine((f || f) && t);
Console.WriteLine((f || t) && f);
Console.WriteLine((f || t) && t);
Console.WriteLine((t || f) && f);
Console.WriteLine((t || f) && t);
Console.WriteLine((t || t) && f);
Console.WriteLine((t || t) && t);
Console.WriteLine('-');
Console.WriteLine((f || f) || f);
Console.WriteLine((f || f) || t);
Console.WriteLine((f || t) || f);
Console.WriteLine((f || t) || t);
Console.WriteLine((t || f) || f);
Console.WriteLine((t || f) || t);
Console.WriteLine((t || t) || f);
Console.WriteLine((t || t) || t);
Console.WriteLine('-');
Console.WriteLine(f && (f && f));
Console.WriteLine(f && (f && t));
Console.WriteLine(f && (t && f));
Console.WriteLine(f && (t && t));
Console.WriteLine(t && (f && f));
Console.WriteLine(t && (f && t));
Console.WriteLine(t && (t && f));
Console.WriteLine(t && (t && t));
Console.WriteLine('-');
Console.WriteLine(f && (f || f));
Console.WriteLine(f && (f || t));
Console.WriteLine(f && (t || f));
Console.WriteLine(f && (t || t));
Console.WriteLine(t && (f || f));
Console.WriteLine(t && (f || t));
Console.WriteLine(t && (t || f));
Console.WriteLine(t && (t || t));
Console.WriteLine('-');
Console.WriteLine(f || (f && f));
Console.WriteLine(f || (f && t));
Console.WriteLine(f || (t && f));
Console.WriteLine(f || (t && t));
Console.WriteLine(t || (f && f));
Console.WriteLine(t || (f && t));
Console.WriteLine(t || (t && f));
Console.WriteLine(t || (t && t));
Console.WriteLine('-');
Console.WriteLine(f || (f || f));
Console.WriteLine(f || (f || t));
Console.WriteLine(f || (t || f));
Console.WriteLine(f || (t || t));
Console.WriteLine(t || (f || f));
Console.WriteLine(t || (f || t));
Console.WriteLine(t || (t || f));
Console.WriteLine(t || (t || t));
}
}
" + StructWithUserDefinedBooleanOperators;
string output = @"0:f
0:f
0:f
0:f
0:(t&f)
0:(t&f)
0:((t&t)&f)
1:((t&t)&t)
-
0:(f|f)
1:(f|t)
0:(f|f)
1:(f|t)
0:((t&f)|f)
1:((t&f)|t)
1:(t&t)
1:(t&t)
-
0:(f|f)
0:(f|f)
0:((f|t)&f)
1:((f|t)&t)
0:(t&f)
1:(t&t)
0:(t&f)
1:(t&t)
-
0:((f|f)|f)
1:((f|f)|t)
1:(f|t)
1:(f|t)
1:t
1:t
1:t
1:t
-
0:f
0:f
0:f
0:f
0:(t&f)
0:(t&f)
0:(t&(t&f))
1:(t&(t&t))
-
0:f
0:f
0:f
0:f
0:(t&(f|f))
1:(t&(f|t))
1:(t&t)
1:(t&t)
-
0:(f|f)
0:(f|f)
0:(f|(t&f))
1:(f|(t&t))
1:t
1:t
1:t
1:t
-
0:(f|(f|f))
1:(f|(f|t))
1:(f|t)
1:(f|t)
1:t
1:t
1:t
1:t";
CompileAndVerify(source: source, expectedOutput: output);
}
[Fact]
public void TestUserDefinedLogicalOperators2()
{
string source = @"
using System;
class C
{
static void Main()
{
S f = new S(0, 'f');
S t = new S(1, 't');
Console.Write((f && f) && f ? 1 : 0);
Console.Write((f && f) && t ? 1 : 0);
Console.Write((f && t) && f ? 1 : 0);
Console.Write((f && t) && t ? 1 : 0);
Console.Write((t && f) && f ? 1 : 0);
Console.Write((t && f) && t ? 1 : 0);
Console.Write((t && t) && f ? 1 : 0);
Console.Write((t && t) && t ? 1 : 0);
Console.WriteLine('-');
Console.Write((f && f) || f ? 1 : 0);
Console.Write((f && f) || t ? 1 : 0);
Console.Write((f && t) || f ? 1 : 0);
Console.Write((f && t) || t ? 1 : 0);
Console.Write((t && f) || f ? 1 : 0);
Console.Write((t && f) || t ? 1 : 0);
Console.Write((t && t) || f ? 1 : 0);
Console.Write((t && t) || t ? 1 : 0);
Console.WriteLine('-');
Console.Write((f || f) && f ? 1 : 0);
Console.Write((f || f) && t ? 1 : 0);
Console.Write((f || t) && f ? 1 : 0);
Console.Write((f || t) && t ? 1 : 0);
Console.Write((t || f) && f ? 1 : 0);
Console.Write((t || f) && t ? 1 : 0);
Console.Write((t || t) && f ? 1 : 0);
Console.Write((t || t) && t ? 1 : 0);
Console.WriteLine('-');
Console.Write((f || f) || f ? 1 : 0);
Console.Write((f || f) || t ? 1 : 0);
Console.Write((f || t) || f ? 1 : 0);
Console.Write((f || t) || t ? 1 : 0);
Console.Write((t || f) || f ? 1 : 0);
Console.Write((t || f) || t ? 1 : 0);
Console.Write((t || t) || f ? 1 : 0);
Console.Write((t || t) || t ? 1 : 0);
Console.WriteLine('-');
Console.Write(f && (f && f) ? 1 : 0);
Console.Write(f && (f && t) ? 1 : 0);
Console.Write(f && (t && f) ? 1 : 0);
Console.Write(f && (t && t) ? 1 : 0);
Console.Write(t && (f && f) ? 1 : 0);
Console.Write(t && (f && t) ? 1 : 0);
Console.Write(t && (t && f) ? 1 : 0);
Console.Write(t && (t && t) ? 1 : 0);
Console.WriteLine('-');
Console.Write(f && (f || f) ? 1 : 0);
Console.Write(f && (f || t) ? 1 : 0);
Console.Write(f && (t || f) ? 1 : 0);
Console.Write(f && (t || t) ? 1 : 0);
Console.Write(t && (f || f) ? 1 : 0);
Console.Write(t && (f || t) ? 1 : 0);
Console.Write(t && (t || f) ? 1 : 0);
Console.Write(t && (t || t) ? 1 : 0);
Console.WriteLine('-');
Console.Write(f || (f && f) ? 1 : 0);
Console.Write(f || (f && t) ? 1 : 0);
Console.Write(f || (t && f) ? 1 : 0);
Console.Write(f || (t && t) ? 1 : 0);
Console.Write(t || (f && f) ? 1 : 0);
Console.Write(t || (f && t) ? 1 : 0);
Console.Write(t || (t && f) ? 1 : 0);
Console.Write(t || (t && t) ? 1 : 0);
Console.WriteLine('-');
Console.Write(f || (f || f) ? 1 : 0);
Console.Write(f || (f || t) ? 1 : 0);
Console.Write(f || (t || f) ? 1 : 0);
Console.Write(f || (t || t) ? 1 : 0);
Console.Write(t || (f || f) ? 1 : 0);
Console.Write(t || (f || t) ? 1 : 0);
Console.Write(t || (t || f) ? 1 : 0);
Console.Write(t || (t || t) ? 1 : 0);
}
}
" + StructWithUserDefinedBooleanOperators;
string output = @"
00000001-
01010111-
00010101-
01111111-
00000001-
00000111-
00011111-
01111111";
CompileAndVerify(source: source, expectedOutput: output);
}
[Fact]
public void TestOperatorTrue()
{
string source = @"
using System;
struct S
{
private int x;
public S(int x) { this.x = x; }
public static bool operator true(S s) { return s.x != 0; }
public static bool operator false(S s) { return s.x == 0; }
}
class C
{
static void Main()
{
S zero = new S(0);
S one = new S(1);
if (zero)
Console.Write('a');
else
Console.Write('b');
if (one)
Console.Write('c');
else
Console.Write('d');
Console.Write( zero ? 'e' : 'f' );
Console.Write( one ? 'g' : 'h' );
while(zero)
{
Console.Write('i');
}
while(one)
{
Console.Write('j');
break;
}
do
{
Console.Write('k');
}
while(zero);
bool first = true;
do
{
Console.Write('l');
if (!first) break;
first = false;
}
while(one);
for( ; zero ; )
{
Console.Write('m');
}
for( ; one ; )
{
Console.Write('n');
break;
}
}
}";
string output = @"bcfgjklln";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestOperatorTrue_IOperation()
{
string source = @"
using System;
struct S
{
private int x;
public S(int x) { this.x = x; }
public static bool operator true(S s) { return s.x != 0; }
public static bool operator false(S s) { return s.x == 0; }
}
class C
{
static void Main(S zero, S one)
/*<bind>*/{
if (zero)
Console.Write('a');
else
Console.Write('b');
Console.Write(one ? 'g' : 'h');
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (zero) ... Write('b');')
Condition:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S s)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'zero')
Operand:
IParameterReferenceOperation: zero (OperationKind.ParameterReference, Type: S) (Syntax: 'zero')
WhenTrue:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write('a');')
Expression:
IInvocationOperation (void System.Console.Write(System.Char value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write('a')')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: ''a'')
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
WhenFalse:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write('b');')
Expression:
IInvocationOperation (void System.Console.Write(System.Char value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write('b')')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: ''b'')
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: b) (Syntax: ''b'')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... 'g' : 'h');')
Expression:
IInvocationOperation (void System.Console.Write(System.Char value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... 'g' : 'h')')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'one ? 'g' : 'h'')
IConditionalOperation (OperationKind.Conditional, Type: System.Char) (Syntax: 'one ? 'g' : 'h'')
Condition:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S s)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'one')
Operand:
IParameterReferenceOperation: one (OperationKind.ParameterReference, Type: S) (Syntax: 'one')
WhenTrue:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: g) (Syntax: ''g'')
WhenFalse:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: h) (Syntax: ''h'')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUnaryOperatorOverloading()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator + (S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator - (S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~ (S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator ! (S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
Console.Write( + ~ ! - a );
Console.Write( a );
Console.Write( a++ );
Console.Write( a );
Console.Write( b );
Console.Write( ++b );
Console.Write( b );
Console.Write( c );
Console.Write( c-- );
Console.Write( c );
Console.Write( d );
Console.Write( --d );
Console.Write( d );
}
}";
string output = "(+(~(!(-a))))aa(a+1)b(b+1)(b+1)cc(c-1)d(d-1)(d-1)";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUnaryOperatorOverloading_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator -(S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~(S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator !(S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Method(S a)
/*<bind>*/{
Console.Write(+a);
Console.Write(-a);
Console.Write(~a);
Console.Write(!a);
Console.Write(+~!-a);
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (5 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(+a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(+a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '+a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '+a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: S S.op_UnaryPlus(S x)) (OperationKind.Unary, Type: S) (Syntax: '+a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(-a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(-a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '-a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '-a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: S S.op_UnaryNegation(S x)) (OperationKind.Unary, Type: S) (Syntax: '-a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(~a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(~a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '~a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '~a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: S S.op_OnesComplement(S x)) (OperationKind.Unary, Type: S) (Syntax: '~a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(!a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(!a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '!a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '!a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: S S.op_LogicalNot(S x)) (OperationKind.Unary, Type: S) (Syntax: '!a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(+~!-a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(+~!-a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '+~!-a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '+~!-a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: S S.op_UnaryPlus(S x)) (OperationKind.Unary, Type: S) (Syntax: '+~!-a')
Operand:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: S S.op_OnesComplement(S x)) (OperationKind.Unary, Type: S) (Syntax: '~!-a')
Operand:
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: S S.op_LogicalNot(S x)) (OperationKind.Unary, Type: S) (Syntax: '!-a')
Operand:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: S S.op_UnaryNegation(S x)) (OperationKind.Unary, Type: S) (Syntax: '-a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperatorOverloading_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator -(S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~(S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator !(S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Method(S a)
/*<bind>*/{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '++a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a++')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '--a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a--')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperatorOverloading_Checked_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator -(S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~(S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator !(S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Method(S a)
/*<bind>*/{
checked
{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '++a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a++')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '--a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a--')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperator_IOperation()
{
string source = @"
using System;
class C
{
static void Method(int a)
/*<bind>*/{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IIncrementOrDecrementOperation (Postfix) (OperationKind.Decrement, Type: System.Int32) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperator_Checked_IOperation()
{
string source = @"
using System;
class C
{
static void Method(int a)
/*<bind>*/{
checked
{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IIncrementOrDecrementOperation (Prefix, Checked) (OperationKind.Increment, Type: System.Int32) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IIncrementOrDecrementOperation (Postfix, Checked) (OperationKind.Increment, Type: System.Int32) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IIncrementOrDecrementOperation (Prefix, Checked) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IIncrementOrDecrementOperation (Postfix, Checked) (OperationKind.Decrement, Type: System.Int32) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestBinaryOperatorOverloading()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public static S operator == (S x, S y) { return new S('(' + x.str + '=' + '=' + y.str + ')'); }
public static S operator != (S x, S y) { return new S('(' + x.str + '!' + '=' + y.str + ')'); }
public static S operator >= (S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); }
public static S operator <= (S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); }
public static S operator > (S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); }
public static S operator < (S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
S e = new S('e');
S f = new S('f');
S g = new S('g');
S h = new S('h');
S i = new S('i');
S j = new S('j');
S k = new S('k');
S l = new S('l');
S m = new S('m');
S n = new S('n');
S o = new S('o');
S p = new S('p');
Console.WriteLine(
(a >> 10) + (b << 20) - c * d / e % f & g |
h ^ i == j != k < l > m <= o >= p);
}
}";
string output = @"(((((a>>10)+(b<<20))-(((c*d)/e)%f))&g)|(h^((i==j)!=((((k<l)>m)<=o)>=p))))";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestBinaryOperatorOverloading_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator -(S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator %(S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator /(S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator *(S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator &(S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator |(S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^(S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator <<(S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >>(S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public static S operator ==(S x, S y) { return new S('(' + x.str + '=' + '=' + y.str + ')'); }
public static S operator !=(S x, S y) { return new S('(' + x.str + '!' + '=' + y.str + ')'); }
public static S operator >=(S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); }
public static S operator <=(S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); }
public static S operator >(S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); }
public static S operator <(S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
S e = new S('e');
S f = new S('f');
S g = new S('g');
S h = new S('h');
S i = new S('i');
S j = new S('j');
S k = new S('k');
S l = new S('l');
S m = new S('m');
S n = new S('n');
S o = new S('o');
S p = new S('p');
Console.WriteLine(
/*<bind>*/(a >> 10) + (b << 20) - c * d / e % f & g |
h ^ i == j != k < l > m <= o >= p/*</bind>*/);
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Or) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + ... m <= o >= p')
Left:
IBinaryOperation (BinaryOperatorKind.And) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + ... / e % f & g')
Left:
IBinaryOperation (BinaryOperatorKind.Subtract) (OperatorMethod: S S.op_Subtraction(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + ... * d / e % f')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: S S.op_Addition(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + (b << 20)')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperatorMethod: S S.op_RightShift(S x, System.Int32 y)) (OperationKind.Binary, Type: S) (Syntax: 'a >> 10')
Left:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IBinaryOperation (BinaryOperatorKind.LeftShift) (OperatorMethod: S S.op_LeftShift(S x, System.Int32 y)) (OperationKind.Binary, Type: S) (Syntax: 'b << 20')
Left:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: S) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
Right:
IBinaryOperation (BinaryOperatorKind.Remainder) (OperatorMethod: S S.op_Modulus(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'c * d / e % f')
Left:
IBinaryOperation (BinaryOperatorKind.Divide) (OperatorMethod: S S.op_Division(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'c * d / e')
Left:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperatorMethod: S S.op_Multiply(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'c * d')
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: S) (Syntax: 'c')
Right:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: S) (Syntax: 'd')
Right:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: S) (Syntax: 'e')
Right:
ILocalReferenceOperation: f (OperationKind.LocalReference, Type: S) (Syntax: 'f')
Right:
ILocalReferenceOperation: g (OperationKind.LocalReference, Type: S) (Syntax: 'g')
Right:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperatorMethod: S S.op_ExclusiveOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'h ^ i == j ... m <= o >= p')
Left:
ILocalReferenceOperation: h (OperationKind.LocalReference, Type: S) (Syntax: 'h')
Right:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperatorMethod: S S.op_Inequality(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'i == j != k ... m <= o >= p')
Left:
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: S S.op_Equality(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'i == j')
Left:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: S) (Syntax: 'i')
Right:
ILocalReferenceOperation: j (OperationKind.LocalReference, Type: S) (Syntax: 'j')
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperatorMethod: S S.op_GreaterThanOrEqual(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l > m <= o >= p')
Left:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperatorMethod: S S.op_LessThanOrEqual(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l > m <= o')
Left:
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperatorMethod: S S.op_GreaterThan(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l > m')
Left:
IBinaryOperation (BinaryOperatorKind.LessThan) (OperatorMethod: S S.op_LessThan(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l')
Left:
ILocalReferenceOperation: k (OperationKind.LocalReference, Type: S) (Syntax: 'k')
Right:
ILocalReferenceOperation: l (OperationKind.LocalReference, Type: S) (Syntax: 'l')
Right:
ILocalReferenceOperation: m (OperationKind.LocalReference, Type: S) (Syntax: 'm')
Right:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: S) (Syntax: 'o')
Right:
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: S) (Syntax: 'p')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0660: 'S' defines operator == or operator != but does not override Object.Equals(object o)
// struct S
Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "S").WithArguments("S").WithLocation(3, 8),
// CS0661: 'S' defines operator == or operator != but does not override Object.GetHashCode()
// struct S
Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "S").WithArguments("S").WithLocation(3, 8)
};
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(657084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657084")]
[CompilerTrait(CompilerFeature.IOperation)]
public void DuplicateOperatorInSubclass()
{
string source = @"
class B
{
public static B operator +(C c, B b) { return null; }
}
class C : B
{
public static B operator +(C c, B b) { return null; }
}
class Test
{
public static void Main()
{
B b = /*<bind>*/new C() + new B()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'new C() + new B()')
Left:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Right:
IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0034: Operator '+' is ambiguous on operands of type 'C' and 'B'
// B b = /*<bind>*/new C() + new B()/*</bind>*/;
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "new C() + new B()").WithArguments("+", "C", "B").WithLocation(16, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Enums_Dynamic_Unambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
using System.Collections.Generic;
class C<T>
{
enum E { A }
public void M()
{
var eq1 = C<dynamic>.E.A == C<object>.E.A;
var eq2 = C<object>.E.A == C<dynamic>.E.A;
var eq3 = C<Dictionary<object, dynamic>>.E.A == C<Dictionary<dynamic, object>>.E.A;
var neq1 = C<dynamic>.E.A != C<object>.E.A;
var neq2 = C<object>.E.A != C<dynamic>.E.A;
var neq3 = C<Dictionary<object, dynamic>>.E.A != C<Dictionary<dynamic, object>>.E.A;
var lt1 = C<dynamic>.E.A < C<object>.E.A;
var lt2 = C<object>.E.A < C<dynamic>.E.A;
var lt3 = C<Dictionary<object, dynamic>>.E.A < C<Dictionary<dynamic, object>>.E.A;
var lte1 = C<dynamic>.E.A <= C<object>.E.A;
var lte2 = C<object>.E.A <= C<dynamic>.E.A;
var lte3 = C<Dictionary<object, dynamic>>.E.A <= C<Dictionary<dynamic, object>>.E.A;
var gt1 = C<dynamic>.E.A > C<object>.E.A;
var gt2 = C<object>.E.A > C<dynamic>.E.A;
var gt3 = C<Dictionary<object, dynamic>>.E.A > C<Dictionary<dynamic, object>>.E.A;
var gte1 = C<dynamic>.E.A >= C<object>.E.A;
var gte2 = C<object>.E.A >= C<dynamic>.E.A;
var gte3 = C<Dictionary<object, dynamic>>.E.A >= C<Dictionary<dynamic, object>>.E.A;
var sub1 = C<dynamic>.E.A - C<object>.E.A;
var sub2 = C<object>.E.A - C<dynamic>.E.A;
var sub3 = C<Dictionary<object, dynamic>>.E.A - C<Dictionary<dynamic, object>>.E.A;
var subu1 = C<dynamic>.E.A - 1;
var subu3 = C<Dictionary<object, dynamic>>.E.A - 1;
var usub1 = 1 - C<dynamic>.E.A;
var usub3 = 1 - C<Dictionary<object, dynamic>>.E.A;
var addu1 = C<dynamic>.E.A + 1;
var addu3 = C<Dictionary<object, dynamic>>.E.A + 1;
var uadd1 = 1 + C<dynamic>.E.A;
var uadd3 = 1 + C<Dictionary<object, dynamic>>.E.A;
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics();
}
[Fact, WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
[CompilerTrait(CompilerFeature.IOperation)]
public void TestBinaryOperatorOverloading_Enums_Dynamic_Ambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
class C<T>
{
enum E { A }
public void M()
{
var and = C<dynamic>.E.A & C<object>.E.A;
var or = C<dynamic>.E.A | C<object>.E.A;
var xor = C<dynamic>.E.A ^ C<object>.E.A;
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (10,19): error CS0034: Operator '&' is ambiguous on operands of type 'C<dynamic>.E' and 'C<object>.E'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "C<dynamic>.E.A & C<object>.E.A").WithArguments("&", "C<dynamic>.E", "C<object>.E"),
// (11,18): error CS0034: Operator '|' is ambiguous on operands of type 'C<dynamic>.E' and 'C<object>.E'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "C<dynamic>.E.A | C<object>.E.A").WithArguments("|", "C<dynamic>.E", "C<object>.E"),
// (12,19): error CS0034: Operator '^' is ambiguous on operands of type 'C<dynamic>.E' and 'C<object>.E'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "C<dynamic>.E.A ^ C<object>.E.A").WithArguments("^", "C<dynamic>.E", "C<object>.E"));
}
[Fact]
[WorkItem(624270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624270"), WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Delegates_Dynamic_Unambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
class C<T>
{
delegate void A<U, V>(U u, V v);
C<dynamic>.A<object, object> d1 = null;
C<object>.A<object, object> d2 = null;
C<dynamic>.A<object, dynamic> d3 = null;
C<object>.A<dynamic, object> d4 = null;
public void M()
{
var eq1 = d1 == d2;
var eq2 = d1 == d3;
var eq3 = d1 == d4;
var eq4 = d2 == d3;
var neq1 = d1 != d2;
var neq2 = d1 != d3;
var neq3 = d1 != d4;
var neq4 = d2 != d3;
}
}
";
// Dev11 reports error CS0034: Operator '...' is ambiguous on operands ... and ... for all combinations
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics();
}
[Fact]
public void TestBinaryOperatorOverloading_UserDefined_Dynamic_Unambiguous()
{
string source = @"
class D<T>
{
public class C
{
public static int operator +(C x, C y) { return 1; }
}
}
class X
{
static void Main()
{
var x = new D<object>.C();
var y = new D<dynamic>.C();
var z = /*<bind>*/x + y/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 D<System.Object>.C.op_Addition(D<System.Object>.C x, D<System.Object>.C y)) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: D<System.Object>.C) (Syntax: 'x')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: D<System.Object>.C, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: D<dynamic>.C) (Syntax: 'y')
";
// Dev11 reports error CS0121: The call is ambiguous between the following methods or properties:
// 'D<object>.C.operator+(D<object>.C, D<object>.C)' and 'D<dynamic>.C.operator +(D<dynamic>.C, D<dynamic>.C)'
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
public void TestBinaryOperatorOverloading_UserDefined_Dynamic_Ambiguous()
{
string source = @"
class D<T>
{
public class C
{
public static C operator +(C x, C y) { return null; }
}
}
class X
{
static void Main()
{
var x = new D<object>.C();
var y = new D<dynamic>.C();
var z = /*<bind>*/x + y/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: D<System.Object>.C, IsInvalid) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: D<dynamic>.C, IsInvalid) (Syntax: 'y')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0034: Operator '+' is ambiguous on operands of type 'D<object>.C' and 'D<dynamic>.C'
// var z = /*<bind>*/x + y/*</bind>*/;
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + y").WithArguments("+", "D<object>.C", "D<dynamic>.C").WithLocation(16, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[WorkItem(624270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624270"), WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Delegates_Dynamic_Ambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
class C<T>
{
delegate void A<U, V>(U u, V v);
C<dynamic>.A<object, object> d1 = null;
C<object>.A<object, object> d2 = null;
C<dynamic>.A<object, dynamic> d3 = null;
C<object>.A<dynamic, object> d4 = null;
public void M()
{
var add1 = d1 + d2;
var add2 = d1 + d3;
var add3 = d1 + d4;
var add4 = d2 + d3;
var sub1 = d1 - d2;
var sub2 = d1 - d3;
var sub3 = d1 - d4;
var sub4 = d2 - d3;
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (17,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<object, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 + d2").WithArguments("+", "C<dynamic>.A<object, object>", "C<object>.A<object, object>"),
// (18,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 + d3").WithArguments("+", "C<dynamic>.A<object, object>", "C<dynamic>.A<object, dynamic>"),
// (19,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<dynamic, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 + d4").WithArguments("+", "C<dynamic>.A<object, object>", "C<object>.A<dynamic, object>"),
// (20,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<object>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d2 + d3").WithArguments("+", "C<object>.A<object, object>", "C<dynamic>.A<object, dynamic>"),
// (22,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<object, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 - d2").WithArguments("-", "C<dynamic>.A<object, object>", "C<object>.A<object, object>"),
// (23,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 - d3").WithArguments("-", "C<dynamic>.A<object, object>", "C<dynamic>.A<object, dynamic>"),
// (24,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<dynamic, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 - d4").WithArguments("-", "C<dynamic>.A<object, object>", "C<object>.A<dynamic, object>"),
// (25,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<object>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d2 - d3").WithArguments("-", "C<object>.A<object, object>", "C<dynamic>.A<object, dynamic>"));
}
[Fact]
[WorkItem(624270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624270"), WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Delegates_Dynamic_Ambiguous_Inference()
{
string source = @"
using System;
class Program
{
static void Main()
{
Action<object> a = null;
Goo(c => c == a);
}
static void Goo(Func<Action<object>, IComparable> x) { }
static void Goo(Func<Action<dynamic>, IConvertible> x) { }
}
";
// Dev11 considers Action<object> == Action<dynamic> ambiguous and thus chooses Goo(Func<Action<object>, IComparable>) overload.
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Goo(System.Func<System.Action<object>, System.IComparable>)' and 'Program.Goo(System.Func<System.Action<dynamic>, System.IConvertible>)'
Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("Program.Goo(System.Func<System.Action<object>, System.IComparable>)", "Program.Goo(System.Func<System.Action<dynamic>, System.IConvertible>)"));
}
[Fact]
public void TestBinaryOperatorOverloading_Pointers_Dynamic()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
using System.Collections.Generic;
unsafe class C<T>
{
enum E { A }
public void M()
{
var o = C<object>.E.A;
var d = C<dynamic>.E.A;
var dict1 = C<Dictionary<object, dynamic>>.E.A;
var dict2 = C<Dictionary<dynamic, object>>.E.A;
var eq1 = &o == &d;
var eq2 = &d == &o;
var eq3 = &dict1 == &dict2;
var eq4 = &dict2 == &dict1;
var neq1 = &o != &d;
var neq2 = &d != &o;
var neq3 = &dict1 != &dict2;
var neq4 = &dict2 != &dict1;
var sub1 = &o - &d;
var sub2 = &d - &o;
var sub3 = &dict1 - &dict2;
var sub4 = &dict2 - &dict1;
var subi1 = &o - 1;
var subi2 = &d - 1;
var subi3 = &dict1 - 1;
var subi4 = &dict2 - 1;
var addi1 = &o + 1;
var addi2 = &d + 1;
var addi3 = &dict1 + 1;
var addi4 = &dict2 + 1;
var iadd1 = 1 + &o;
var iadd2 = 1 + &d;
var iadd3 = 1 + &dict1;
var iadd4 = 1 + &dict2;
}
}
";
// Dev11 reports "error CS0034: Operator '-' is ambiguous on operands ... and ..." for all ptr - ptr
CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void TestOverloadResolutionTiebreakers()
{
string source = @"
using System;
struct S
{
public static bool operator == (S x, S y) { return true; }
public static bool operator != (S x, S y) { return false; }
public static bool operator == (S? x, S? y) { return true; }
public static bool operator != (S? x, S? y) { return false; }
public override bool Equals(object s) { return true; }
public override int GetHashCode() { return 0; }
public override string ToString() { return this.str; }
}
class X<T>
{
public static int operator +(X<T> x, int y) { return 0; }
public static int operator +(X<T> x, T y) { return 0; }
}
struct Q<U> where U : struct
{
public static int operator +(Q<U> x, int y) { return 0; }
public static int? operator +(Q<U>? x, U? y) { return 1; }
}
class C
{
static void M()
{
S s1 = new S();
S s2 = new S();
S? s3 = new S();
S? s4 = null;
X<int> xint = null;
int x = xint + 123; //-UserDefinedAddition
// In this case the native compiler and the spec disagree. Roslyn implements the spec.
// The tiebreaker is supposed to check for *specificity* first, and then *liftedness*.
// The native compiler eliminates the lifted operator even if it is more specific:
int? q = new Q<int>?() + new int?(); //-LiftedUserDefinedAddition
// All of these go to a user-defined equality operator;
// the lifted form is always worse than the unlifted form,
// and the user-defined form is always better than turning
// '== null' into a call to HasValue().
bool[] b =
{
s1 == s2, //-UserDefinedEqual
s1 == s3, //-UserDefinedEqual
s1 == null, //-UserDefinedEqual
s3 == s1, //-UserDefinedEqual
s3 == s4, //-UserDefinedEqual
s3 == null, //-UserDefinedEqual
null == s1, //-UserDefinedEqual
null == s3 //-UserDefinedEqual
};
}
}";
TestOperatorKinds(source);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestOverloadResolutionTiebreakers_IOperation()
{
string source = @"
using System;
struct S
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return false; }
public static bool operator ==(S? x, S? y) { return true; }
public static bool operator !=(S? x, S? y) { return false; }
public override bool Equals(object s) { return true; }
public override int GetHashCode() { return 0; }
public override string ToString() { return this.str; }
}
class X<T>
{
public static int operator +(X<T> x, int y) { return 0; }
public static int operator +(X<T> x, T y) { return 0; }
}
struct Q<U> where U : struct
{
public static int operator +(Q<U> x, int y) { return 0; }
public static int? operator +(Q<U>? x, U? y) { return 1; }
}
class C
{
static void M(S s1, S s2, S? s3, S? s4, X<int> xint)
/*<bind>*/{
int x = xint + 123; //-UserDefinedAddition
// In this case the native compiler and the spec disagree. Roslyn implements the spec.
// The tiebreaker is supposed to check for *specificity* first, and then *liftedness*.
// The native compiler eliminates the lifted operator even if it is more specific:
int? q = new Q<int>?() + new int?(); //-LiftedUserDefinedAddition
// All of these go to a user-defined equality operator;
// the lifted form is always worse than the unlifted form,
// and the user-defined form is always better than turning
// '== null' into a call to HasValue().
bool[] b =
{
s1 == s2, //-UserDefinedEqual
s1 == s3, //-UserDefinedEqual
s1 == null, //-UserDefinedEqual
s3 == s1, //-UserDefinedEqual
s3 == s4, //-UserDefinedEqual
s3 == null, //-UserDefinedEqual
null == s1, //-UserDefinedEqual
null == s3 //-UserDefinedEqual
};
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 x
Local_2: System.Int32? q
Local_3: System.Boolean[] b
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int x = xint + 123;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int x = xint + 123')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = xint + 123')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= xint + 123')
IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 X<System.Int32>.op_Addition(X<System.Int32> x, System.Int32 y)) (OperationKind.Binary, Type: System.Int32) (Syntax: 'xint + 123')
Left:
IParameterReferenceOperation: xint (OperationKind.ParameterReference, Type: X<System.Int32>) (Syntax: 'xint')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 123) (Syntax: '123')
Initializer:
null
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int? q = ne ... new int?();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int? q = ne ... new int?()')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32? q) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'q = new Q<i ... new int?()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Q<int ... new int?()')
IBinaryOperation (BinaryOperatorKind.Add, IsLifted) (OperatorMethod: System.Int32 Q<System.Int32>.op_Addition(Q<System.Int32> x, System.Int32 y)) (OperationKind.Binary, Type: System.Int32?) (Syntax: 'new Q<int>? ... new int?()')
Left:
IObjectCreationOperation (Constructor: Q<System.Int32>?..ctor()) (OperationKind.ObjectCreation, Type: Q<System.Int32>?) (Syntax: 'new Q<int>?()')
Arguments(0)
Initializer:
null
Right:
IObjectCreationOperation (Constructor: System.Int32?..ctor()) (OperationKind.ObjectCreation, Type: System.Int32?) (Syntax: 'new int?()')
Arguments(0)
Initializer:
null
Initializer:
null
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'bool[] b = ... };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'bool[] b = ... }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Boolean[] b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b = ... }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Boolean[], IsImplicit) (Syntax: '{ ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 8, IsImplicit) (Syntax: '{ ... }')
Initializer:
IArrayInitializerOperation (8 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ ... }')
Element Values(8):
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S x, S y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's1 == s2')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
Right:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S) (Syntax: 's2')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's1 == s3')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
Right:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's1 == null')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's3 == s1')
Left:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's3 == s4')
Left:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Right:
IParameterReferenceOperation: s4 (OperationKind.ParameterReference, Type: S?) (Syntax: 's4')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's3 == null')
Left:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'null == s1')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'null == s3')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Right:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0458: The result of the expression is always 'null' of type 'int?'
// int? q = new Q<int>?() + new int?(); //-LiftedUserDefinedAddition
Diagnostic(ErrorCode.WRN_AlwaysNull, "new Q<int>?() + new int?()").WithArguments("int?").WithLocation(37, 18),
// CS1061: 'S' does not contain a definition for 'str' and no extension method 'str' accepting a first argument of type 'S' could be found (are you missing a using directive or an assembly reference?)
// public override string ToString() { return this.str; }
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "str").WithArguments("S", "str").WithLocation(11, 53)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUserDefinedCompoundAssignment()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
S e = new S('e');
S f = new S('f');
S g = new S('g');
S h = new S('h');
S i = new S('i');
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
Console.WriteLine(a);
}
}";
string output = @"((((((((((a+b)-c)*d)/e)%f)<<10)>>20)&g)|h)^i)";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUserDefinedCompoundAssignment_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator -(S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator %(S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator /(S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator *(S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator &(S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator |(S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^(S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator <<(S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >>(S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main(S a, S b, S c, S d, S e, S f, S g, S h, S i)
/*<bind>*/{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: S S.op_Addition(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: S) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperatorMethod: S S.op_Subtraction(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: S) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperatorMethod: S S.op_Multiply(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: S) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperatorMethod: S S.op_Division(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: S) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperatorMethod: S S.op_Modulus(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: S) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperatorMethod: S S.op_LeftShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperatorMethod: S S.op_RightShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: S) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: S) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperatorMethod: S S.op_ExclusiveOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: S) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUserDefinedCompoundAssignment_Checked_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator -(S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator %(S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator /(S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator *(S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator &(S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator |(S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^(S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator <<(S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >>(S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main(S a, S b, S c, S d, S e, S f, S g, S h, S i)
/*<bind>*/{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: S S.op_Addition(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: S) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperatorMethod: S S.op_Subtraction(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: S) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperatorMethod: S S.op_Multiply(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: S) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperatorMethod: S S.op_Division(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: S) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperatorMethod: S S.op_Modulus(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: S) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperatorMethod: S S.op_LeftShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperatorMethod: S S.op_RightShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: S) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: S) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperatorMethod: S S.op_ExclusiveOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: S) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestCompoundAssignment_IOperation()
{
string source = @"
class C
{
static void M(int a, int b, int c, int d, int e, int f, int g, int h, int i)
/*<bind>*/{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(21723, "https://github.com/dotnet/roslyn/issues/21723")]
public void TestCompoundLiftedAssignment_IOperation()
{
string source = @"
class C
{
static void M(int a, int? b)
{
/*<bind>*/a += b/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add, IsLifted) (OperationKind.CompoundAssignment, Type: System.Int32, IsInvalid) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'b')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
// /*<bind>*/a += b/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a += b").WithArguments("int?", "int").WithLocation(6, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestCompoundAssignment_Checked_IOperation()
{
string source = @"
class C
{
static void M(int a, int b, int c, int d, int e, int f, int g, int h, int i)
/*<bind>*/{
checked
{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUserDefinedBinaryOperatorOverloadResolution()
{
TestOperatorKinds(@"
using System;
struct S
{
public static int operator + (S x1, S x2) { return 1; }
public static int? operator - (S x1, S? x2) { return 1; }
public static S operator & (S x1, S x2) { return x1; }
public static bool operator true(S? x1) { return true; }
public static bool operator false(S? x1) { return false; }
}
class B
{
public static bool operator ==(B b1, B b2) { return true; }
public static bool operator !=(B b1, B b2) { return true; }
}
class D : B {}
class C
{
static void M()
{
bool f;
B b = null;
D d = null;
S s1 = new S();
S? s2 = s1;
int i1;
int? i2;
i1 = s1 + s1; //-UserDefinedAddition
i2 = s1 + s2; //-LiftedUserDefinedAddition
i2 = s2 + s1; //-LiftedUserDefinedAddition
i2 = s2 + s2; //-LiftedUserDefinedAddition
// No lifted form.
i2 = s1 - s1; //-UserDefinedSubtraction
i2 = s1 - s2; //-UserDefinedSubtraction
f = b == b; //-UserDefinedEqual
f = b == d; //-UserDefinedEqual
f = d == b; //-UserDefinedEqual
f = d == d; //-UserDefinedEqual
s1 = s1 & s1; //-UserDefinedAnd
s2 = s2 & s1; //-LiftedUserDefinedAnd
s2 = s1 & s2; //-LiftedUserDefinedAnd
s2 = s2 & s2; //-LiftedUserDefinedAnd
// No lifted form.
s1 = s1 && s1; //-LogicalUserDefinedAnd
// UNDONE: More tests
}
}");
}
[Fact]
public void TestUserDefinedUnaryOperatorOverloadResolution()
{
TestOperatorKinds(@"
using System;
struct S
{
public static int operator +(S s) { return 1; }
public static int operator -(S? s) { return 2; }
public static int operator !(S s) { return 3; }
public static int operator ~(S s) { return 4; }
public static S operator ++(S s) { return s; }
public static S operator --(S? s) { return (S)s; }
}
class C
{
static void M()
{
S s1 = new S();
S? s2 = s1;
int i1;
int? i2;
i1 = +s1; //-UserDefinedUnaryPlus
i2 = +s2; //-LiftedUserDefinedUnaryPlus
// No lifted form.
i1 = -s1; //-UserDefinedUnaryMinus
i1 = -s2; //-UserDefinedUnaryMinus
i1 = !s1; //-UserDefinedLogicalNegation
i2 = !s2; //-LiftedUserDefinedLogicalNegation
i1 = ~s1; //-UserDefinedBitwiseComplement
i2 = ~s2; //-LiftedUserDefinedBitwiseComplement
s1++; //-UserDefinedPostfixIncrement
s2++; //-LiftedUserDefinedPostfixIncrement
++s1; //-UserDefinedPrefixIncrement
++s2; //-LiftedUserDefinedPrefixIncrement
// No lifted form
s1--; //-UserDefinedPostfixDecrement
s2--; //-UserDefinedPostfixDecrement
}
}");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUserDefinedUnaryOperatorOverloadResolution_IOperation()
{
string source = @"
using System;
struct S
{
public static int operator +(S s) { return 1; }
public static int operator -(S? s) { return 2; }
public static int operator !(S s) { return 3; }
public static int operator ~(S s) { return 4; }
public static S operator ++(S s) { return s; }
public static S operator --(S? s) { return (S)s; }
}
class C
{
static void M(S s1, S? s2, int i1, int? i2)
/*<bind>*/{
i1 = +s1; //-UserDefinedUnaryPlus
i2 = +s2; //-LiftedUserDefinedUnaryPlus
// No lifted form.
i1 = -s1; //-UserDefinedUnaryMinus
i1 = -s2; //-UserDefinedUnaryMinus
i1 = !s1; //-UserDefinedLogicalNegation
i2 = !s2; //-LiftedUserDefinedLogicalNegation
i1 = ~s1; //-UserDefinedBitwiseComplement
i2 = ~s2; //-LiftedUserDefinedBitwiseComplement
s1++; //-UserDefinedPostfixIncrement
s2++; //-LiftedUserDefinedPostfixIncrement
++s1; //-UserDefinedPrefixIncrement
++s2; //-LiftedUserDefinedPrefixIncrement
// No lifted form
s1--; //-UserDefinedPostfixDecrement
s2--; //-UserDefinedPostfixDecrement
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (14 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = +s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = +s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: System.Int32 S.op_UnaryPlus(S s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '+s1')
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i2 = +s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'i2 = +s2')
Left:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i2')
Right:
IUnaryOperation (UnaryOperatorKind.Plus, IsLifted) (OperatorMethod: System.Int32 S.op_UnaryPlus(S s)) (OperationKind.Unary, Type: System.Int32?) (Syntax: '+s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = -s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = -s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: System.Int32 S.op_UnaryNegation(S? s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '-s1')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = -s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = -s2')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: System.Int32 S.op_UnaryNegation(S? s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '-s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = !s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = !s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: System.Int32 S.op_LogicalNot(S s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '!s1')
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i2 = !s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'i2 = !s2')
Left:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i2')
Right:
IUnaryOperation (UnaryOperatorKind.Not, IsLifted) (OperatorMethod: System.Int32 S.op_LogicalNot(S s)) (OperationKind.Unary, Type: System.Int32?) (Syntax: '!s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = ~s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = ~s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: System.Int32 S.op_OnesComplement(S s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '~s1')
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i2 = ~s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'i2 = ~s2')
Left:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i2')
Right:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation, IsLifted) (OperatorMethod: System.Int32 S.op_OnesComplement(S s)) (OperationKind.Unary, Type: System.Int32?) (Syntax: '~s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's1++;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S) (Syntax: 's1++')
Target:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's2++;')
Expression:
IIncrementOrDecrementOperation (Postfix, IsLifted) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S?) (Syntax: 's2++')
Target:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '++s1;')
Expression:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S) (Syntax: '++s1')
Target:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '++s2;')
Expression:
IIncrementOrDecrementOperation (Prefix, IsLifted) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S?) (Syntax: '++s2')
Target:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's1--;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S? s)) (OperationKind.Decrement, Type: S) (Syntax: 's1--')
Target:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's2--;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S? s)) (OperationKind.Decrement, Type: S?) (Syntax: 's2--')
Target:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type
// public static S operator --(S? s) { return (S)s; }
Diagnostic(ErrorCode.ERR_BadIncDecRetType, "--").WithLocation(10, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUnaryOperatorOverloadingErrors()
{
var source = @"
class C
{
// UNDONE: Write tests for the rest of them
void M(bool b)
{
if(!1) {}
b++;
error++;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,12): error CS0023: Operator '!' cannot be applied to operand of type 'int'
// if(!1) {}
Diagnostic(ErrorCode.ERR_BadUnaryOp, "!1").WithArguments("!", "int").WithLocation(7, 12),
// (8,9): error CS0023: Operator '++' cannot be applied to operand of type 'bool'
// b++;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "b++").WithArguments("++", "bool").WithLocation(8, 9),
// (9,9): error CS0103: The name 'error' does not exist in the current context
// error++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var negOne = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("!1", negOne.ToString());
var type1 = model.GetTypeInfo(negOne).Type;
Assert.Equal("?", type1.ToTestDisplayString());
Assert.True(type1.IsErrorType());
var boolPlusPlus = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().ElementAt(0);
Assert.Equal("b++", boolPlusPlus.ToString());
var type2 = model.GetTypeInfo(boolPlusPlus).Type;
Assert.Equal("?", type2.ToTestDisplayString());
Assert.True(type2.IsErrorType());
var errorPlusPlus = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().ElementAt(1);
Assert.Equal("error++", errorPlusPlus.ToString());
var type3 = model.GetTypeInfo(errorPlusPlus).Type;
Assert.Equal("?", type3.ToTestDisplayString());
Assert.True(type3.IsErrorType());
}
[Fact]
public void TestBinaryOperatorOverloadingErrors()
{
// The native compiler and Roslyn report slightly different errors here.
// The native compiler reports CS0019 when attempting to add or compare long and ulong:
// that is "operator cannot be applied to operands of type long and ulong". This is
// correct but not as specific as it could be; the error is actually because overload
// resolution is ambiguous. The double + double --> double, float + float --> float
// and decimal + decimal --> decimal operators are all applicable but overload resolution
// finds that this set of applicable operators is ambiguous; float is better than double,
// but neither float nor decimal is better than the other.
//
// Roslyn produces the more accurate error; this is an ambiguity.
//
// Comparing string and exception is not ambiguous; the only applicable operator
// is the reference equality operator, and it requires that its operand types be
// convertible to each other.
string source = @"
class C
{
bool N() { return false; }
void M()
{
long i64 = 1;
ulong ui64 = 1;
System.String s1 = null;
System.Exception ex1 = null;
object o1 = i64 + ui64; // CS0034
bool b1 = i64 == ui64; // CS0034
bool b2 = s1 == ex1; // CS0019
bool b3 = (object)s1 == ex1; // legal!
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,21): error CS0034: Operator '+' is ambiguous on operands of type 'long' and 'ulong'
// object o1 = i64 + ui64; // CS0034
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "i64 + ui64").WithArguments("+", "long", "ulong"),
// (12,19): error CS0034: Operator '==' is ambiguous on operands of type 'long' and 'ulong'
// bool b1 = i64 == ui64; // CS0034
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "i64 == ui64").WithArguments("==", "long", "ulong"),
// (13,19): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'System.Exception'
// bool b2 = s1 == ex1; // CS0019
Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 == ex1").WithArguments("==", "string", "System.Exception"));
}
[Fact]
public void TestCompoundOperatorErrors()
{
var source = @"
class C
{
// UNDONE: Add more error cases
class D : C {}
public static C operator + (C c1, C c2) { return c1; }
public int ReadOnly { get { return 0; } }
public int WriteOnly { set { } }
void M()
{
C c = new C();
D d = new D();
c.ReadOnly += 1;
c.WriteOnly += 1;
int i32 = 1;
long i64 = 1;
// If we have x += y and the + is a built-in operator then
// the result must be *explicitly* convertible to x, and y
// must be *implicitly* convertible to x.
//
// If the + is a user-defined operator then the result must
// be *implicitly* convertible to x, and y need not have
// any relationship with x.
// Overload resolution resolves this as long + long --> long.
// The result is explicitly convertible to int, but the right-hand
// side is not, so this is an error.
i32 += i64;
// In the user-defined conversion, the result of the addition must
// be *implicitly* convertible to the left hand side:
d += c;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (17,9): error CS0200: Property or indexer 'C.ReadOnly' cannot be assigned to -- it is read only
// c.ReadOnly += 1;
Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.ReadOnly").WithArguments("C.ReadOnly").WithLocation(17, 9),
// (18,9): error CS0154: The property or indexer 'C.WriteOnly' cannot be used in this context because it lacks the get accessor
// c.WriteOnly += 1;
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c.WriteOnly").WithArguments("C.WriteOnly").WithLocation(18, 9),
// (34,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
// i32 += i64;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "i32 += i64").WithArguments("long", "int").WithLocation(34, 9),
// (39,9): error CS0266: Cannot implicitly convert type 'C' to 'C.D'. An explicit conversion exists (are you missing a cast?)
// d += c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "d += c").WithArguments("C", "C.D").WithLocation(39, 9));
}
[Fact]
public void TestOperatorOverloadResolution()
{
// UNDONE: User-defined operators
// UNDONE: TestOverloadResolution(GenerateTest(PostfixIncrementTemplate, "++", "PostfixIncrement"));
// UNDONE: TestOverloadResolution(GenerateTest(PostfixIncrementTemplate, "--", "PostfixDecrement"));
TestOperatorKinds(GenerateTest(PrefixIncrementTemplate, "++", "PrefixIncrement"));
TestOperatorKinds(GenerateTest(PrefixIncrementTemplate, "--", "PrefixDecrement"));
// UNDONE: Pointer ++ --
TestOperatorKinds(UnaryPlus);
TestOperatorKinds(UnaryMinus);
TestOperatorKinds(LogicalNegation);
TestOperatorKinds(BitwiseComplement);
TestOperatorKinds(EnumAddition);
TestOperatorKinds(StringAddition);
TestOperatorKinds(DelegateAddition);
// UNDONE: Pointer addition
TestOperatorKinds(EnumSubtraction);
TestOperatorKinds(DelegateSubtraction);
// UNDONE: Pointer subtraction
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "+", "Addition"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "-", "Subtraction"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "*", "Multiplication"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "/", "Division"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "%", "Remainder"));
TestOperatorKinds(GenerateTest(ShiftTemplate, "<<", "LeftShift"));
TestOperatorKinds(GenerateTest(ShiftTemplate, ">>", "RightShift"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "==", "Equal"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "!=", "NotEqual"));
TestOperatorKinds(GenerateTest(EqualityTemplate, "!=", "NotEqual"));
TestOperatorKinds(GenerateTest(EqualityTemplate, "!=", "NotEqual"));
// UNDONE: Pointer equality
TestOperatorKinds(GenerateTest(ComparisonTemplate, ">", "GreaterThan"));
TestOperatorKinds(GenerateTest(ComparisonTemplate, ">=", "GreaterThanOrEqual"));
TestOperatorKinds(GenerateTest(ComparisonTemplate, "<", "LessThan"));
TestOperatorKinds(GenerateTest(ComparisonTemplate, "<=", "LessThanOrEqual"));
TestOperatorKinds(GenerateTest(LogicTemplate, "^", "Xor"));
TestOperatorKinds(GenerateTest(LogicTemplate, "&", "And"));
TestOperatorKinds(GenerateTest(LogicTemplate, "|", "Or"));
TestOperatorKinds(GenerateTest(ShortCircuitTemplate, "&&", "And"));
TestOperatorKinds(GenerateTest(ShortCircuitTemplate, "||", "Or"));
}
[Fact]
public void TestEnumOperatorOverloadResolution()
{
TestOperatorKinds(GenerateTest(EnumLogicTemplate, "^", "Xor"));
TestOperatorKinds(GenerateTest(EnumLogicTemplate, "&", "And"));
TestOperatorKinds(GenerateTest(EnumLogicTemplate, "|", "Or"));
}
[Fact]
public void TestConstantOperatorOverloadResolution()
{
string code =
@"class C
{
static void F(object o) { }
static void M()
{
const short ci16 = 1;
uint u32 = 1;
F(u32 + 1); //-UIntAddition
F(2 + u32); //-UIntAddition
F(u32 + ci16); //-LongAddition
F(u32 + int.MaxValue); //-UIntAddition
F(u32 + (-1)); //-LongAddition
//-IntUnaryMinus
F(u32 + long.MaxValue); //-LongAddition
int i32 = 2;
F(i32 + 1); //-IntAddition
F(2 + i32); //-IntAddition
F(i32 + ci16); //-IntAddition
F(i32 + int.MaxValue); //-IntAddition
F(i32 + (-1)); //-IntAddition
//-IntUnaryMinus
}
}
";
TestOperatorKinds(code);
}
private void TestBoundTree(string source, System.Func<IEnumerable<KeyValuePair<TreeDumperNode, TreeDumperNode>>, IEnumerable<string>> query)
{
// The mechanism of this test is: we build the bound tree for the code passed in and then extract
// from it the nodes that describe the operators. We then compare the description of
// the operators given to the comment that follows the use of the operator.
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
var diagnostics = new DiagnosticBag();
var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), diagnostics);
var tree = BoundTreeDumperNodeProducer.MakeTree(block);
var results = string.Join("\n",
query(tree.PreorderTraversal())
.ToArray());
var expected = string.Join("\n", source
.Split(new[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries)
.Where(x => x.Contains("//-"))
.Select(x => x.Substring(x.IndexOf("//-", StringComparison.Ordinal) + 3).Trim())
.ToArray());
Assert.Equal(expected, results);
}
private void TestOperatorKinds(string source)
{
// The mechanism of this test is: we build the bound tree for the code passed in and then extract
// from it the nodes that describe the operators. We then compare the description of
// the operators given to the comment that follows the use of the operator.
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node.Text == "operatorKind"
where node.Value != null
select node.Value.ToString());
}
private void TestCompoundAssignment(string source)
{
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node != null && (node.Text == "eventAssignmentOperator" || node.Text == "compoundAssignmentOperator")
select string.Join(" ", from child in node.Children
where child.Text == "@operator" ||
child.Text == "isAddition" ||
child.Text == "isDynamic" ||
child.Text == "leftConversion" ||
child.Text == "finalConversion"
select child.Text + ": " + (child.Text == "@operator" ? ((BinaryOperatorSignature)child.Value).Kind.ToString() : child.Value.ToString())));
}
private void TestTypes(string source)
{
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node.Text == "type"
select edge.Key.Text + ": " + (node.Value != null ? node.Value.ToString() : "<null>"));
}
private static string FormatTypeArgumentList(ImmutableArray<TypeWithAnnotations>? arguments)
{
if (arguments == null || arguments.Value.IsEmpty)
{
return "";
}
string s = "<";
for (int i = 0; i < arguments.Value.Length; ++i)
{
if (i != 0)
{
s += ", ";
}
s += arguments.Value[i].Type.ToString();
}
return s + ">";
}
private void TestDynamicMemberAccessCore(string source)
{
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node.Text == "dynamicMemberAccess"
let name = node["name"]
let typeArguments = node["typeArgumentsOpt"].Value as ImmutableArray<TypeWithAnnotations>?
select name.Value.ToString() + FormatTypeArgumentList(typeArguments));
}
private static string GenerateTest(string template, string op, string opkind)
{
string result = template.Replace("OPERATOR", op);
result = result.Replace("KIND", opkind);
return result;
}
#region "Constant String"
private const string Prefix = @"
class C
{
enum E { }
void N(params object[] p) {}
delegate void D();
void M()
{
E e1;
E e2;
string s1 = null;
string s2 = null;
object o1 = null;
object o2 = null;
bool bln;
bool? nbln;
D d1 = null;
D d2 = null;
int i = 1;
E e = 0;
int? ni = 1;
E? ne = 0;
int i1 = 0;
char chr;
sbyte i08 = 1;
short i16 = 1;
int i32 = 1;
long i64 = 1;
byte u08 = 1;
ushort u16 = 1;
uint u32 = 1;
ulong u64 = 1;
float r32 = 1;
double r64 = 1;
decimal dec; // UNDONE: Decimal constants not supported yet.
char? nchr = null;
sbyte? ni08 = 1;
short? ni16 = 1;
int? ni32 = 1;
long? ni64 = 1;
byte? nu08 = 1;
ushort? nu16 = 1;
uint? nu32 = 1;
ulong? nu64 = 1;
float? nr32 = 1;
double? nr64 = 1;
decimal? ndec; // UNDONE: Decimal constants not supported yet.
N(
";
private const string Postfix = @"
);
}
}
";
private const string EnumAddition = Prefix + @"
i + e, //-UnderlyingAndEnumAddition
i + ne, //-LiftedUnderlyingAndEnumAddition
e + i, //-EnumAndUnderlyingAddition
e + ni, //-LiftedEnumAndUnderlyingAddition
ni + e, //-LiftedUnderlyingAndEnumAddition
ni + ne, //-LiftedUnderlyingAndEnumAddition
ne + i, //-LiftedEnumAndUnderlyingAddition
ne + ni //-LiftedEnumAndUnderlyingAddition" + Postfix;
private const string DelegateAddition = Prefix + @"
d1 + d2 //-DelegateCombination" + Postfix;
private const string StringAddition = Prefix + @"
s1 + s1, //-StringConcatenation
s1 + o1, //-StringAndObjectConcatenation
i1 + s1 //-ObjectAndStringConcatenation" + Postfix;
private const string ArithmeticTemplate = Prefix + @"
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR i64, //-LongKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR u32, //-UIntKIND
chr OPERATOR u64, //-ULongKIND
chr OPERATOR r32, //-FloatKIND
chr OPERATOR r64, //-DoubleKIND
chr OPERATOR dec, //-DecimalKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR ni64, //-LiftedLongKIND
chr OPERATOR nu16, //-LiftedIntKIND
chr OPERATOR nu32, //-LiftedUIntKIND
chr OPERATOR nu64, //-LiftedULongKIND
chr OPERATOR nr32, //-LiftedFloatKIND
chr OPERATOR nr64, //-LiftedDoubleKIND
chr OPERATOR ndec, //-LiftedDecimalKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR i64, //-LongKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR u32, //-LongKIND
// i16 OPERATOR u64, (ambiguous)
i16 OPERATOR r32, //-FloatKIND
i16 OPERATOR r64, //-DoubleKIND
i16 OPERATOR dec, //-DecimalKIND
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR ni64, //-LiftedLongKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR nu32, //-LiftedLongKIND
// i16 OPERATOR nu64, (ambiguous)
i16 OPERATOR nr32, //-LiftedFloatKIND
i16 OPERATOR nr64, //-LiftedDoubleKIND
i16 OPERATOR ndec, //-LiftedDecimalKIND
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR i64, //-LongKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR u32, //-LongKIND
// i32 OPERATOR u64, (ambiguous)
i32 OPERATOR r32, //-FloatKIND
i32 OPERATOR r64, //-DoubleKIND
i32 OPERATOR dec, //-DecimalKIND
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR ni64, //-LiftedLongKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR nu32, //-LiftedLongKIND
// i32 OPERATOR nu64, (ambiguous)
i32 OPERATOR nr32, //-LiftedFloatKIND
i32 OPERATOR nr64, //-LiftedDoubleKIND
i32 OPERATOR ndec, //-LiftedDecimalKIND
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR i64, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR u32, //-LongKIND
// i64 OPERATOR u64, (ambiguous)
i64 OPERATOR r32, //-FloatKIND
i64 OPERATOR r64, //-DoubleKIND
i64 OPERATOR dec, //-DecimalKIND
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR ni64, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
i64 OPERATOR nu32, //-LiftedLongKIND
// i64 OPERATOR nu64, (ambiguous)
i64 OPERATOR nr32, //-LiftedFloatKIND
i64 OPERATOR nr64, //-LiftedDoubleKIND
i64 OPERATOR ndec, //-LiftedDecimalKIND
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR i64, //-LongKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR u32, //-UIntKIND
u16 OPERATOR u64, //-ULongKIND
u16 OPERATOR r32, //-FloatKIND
u16 OPERATOR r64, //-DoubleKIND
u16 OPERATOR dec, //-DecimalKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR ni64, //-LiftedLongKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u16 OPERATOR nu32, //-LiftedUIntKIND
u16 OPERATOR nu64, //-LiftedULongKIND
u16 OPERATOR nr32, //-LiftedFloatKIND
u16 OPERATOR nr64, //-LiftedDoubleKIND
u16 OPERATOR ndec, //-LiftedDecimalKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-LongKIND
u32 OPERATOR i32, //-LongKIND
u32 OPERATOR i64, //-LongKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR u32, //-UIntKIND
u32 OPERATOR u64, //-ULongKIND
u32 OPERATOR r32, //-FloatKIND
u32 OPERATOR r64, //-DoubleKIND
u32 OPERATOR dec, //-DecimalKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedLongKIND
u32 OPERATOR ni32, //-LiftedLongKIND
u32 OPERATOR ni64, //-LiftedLongKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u32 OPERATOR nu32, //-LiftedUIntKIND
u32 OPERATOR nu64, //-LiftedULongKIND
u32 OPERATOR nr32, //-LiftedFloatKIND
u32 OPERATOR nr64, //-LiftedDoubleKIND
u32 OPERATOR ndec, //-LiftedDecimalKIND
u64 OPERATOR chr, //-ULongKIND
// u64 OPERATOR i16, (ambiguous)
// u64 OPERATOR i32, (ambiguous)
// u64 OPERATOR i64, (ambiguous)
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR u32, //-ULongKIND
u64 OPERATOR u64, //-ULongKIND
u64 OPERATOR r32, //-FloatKIND
u64 OPERATOR r64, //-DoubleKIND
u64 OPERATOR dec, //-DecimalKIND
u64 OPERATOR nchr, //-LiftedULongKIND
// u64 OPERATOR ni16, (ambiguous)
// u64 OPERATOR ni32, (ambiguous)
// u64 OPERATOR ni64, (ambiguous)
u64 OPERATOR nu16, //-LiftedULongKIND
u64 OPERATOR nu32, //-LiftedULongKIND
u64 OPERATOR nu64, //-LiftedULongKIND
u64 OPERATOR nr32, //-LiftedFloatKIND
u64 OPERATOR nr64, //-LiftedDoubleKIND
u64 OPERATOR ndec, //-LiftedDecimalKIND
r32 OPERATOR chr, //-FloatKIND
r32 OPERATOR i16, //-FloatKIND
r32 OPERATOR i32, //-FloatKIND
r32 OPERATOR i64, //-FloatKIND
r32 OPERATOR u16, //-FloatKIND
r32 OPERATOR u32, //-FloatKIND
r32 OPERATOR u64, //-FloatKIND
r32 OPERATOR r32, //-FloatKIND
r32 OPERATOR r64, //-DoubleKIND
// r32 OPERATOR dec, (none applicable)
r32 OPERATOR nchr, //-LiftedFloatKIND
r32 OPERATOR ni16, //-LiftedFloatKIND
r32 OPERATOR ni32, //-LiftedFloatKIND
r32 OPERATOR ni64, //-LiftedFloatKIND
r32 OPERATOR nu16, //-LiftedFloatKIND
r32 OPERATOR nu32, //-LiftedFloatKIND
r32 OPERATOR nu64, //-LiftedFloatKIND
r32 OPERATOR nr32, //-LiftedFloatKIND
r32 OPERATOR nr64, //-LiftedDoubleKIND
// r32 OPERATOR ndec, (none applicable)
r64 OPERATOR chr, //-DoubleKIND
r64 OPERATOR i16, //-DoubleKIND
r64 OPERATOR i32, //-DoubleKIND
r64 OPERATOR i64, //-DoubleKIND
r64 OPERATOR u16, //-DoubleKIND
r64 OPERATOR u32, //-DoubleKIND
r64 OPERATOR u64, //-DoubleKIND
r64 OPERATOR r32, //-DoubleKIND
r64 OPERATOR r64, //-DoubleKIND
// r64 OPERATOR dec, (none applicable)
r64 OPERATOR nchr, //-LiftedDoubleKIND
r64 OPERATOR ni16, //-LiftedDoubleKIND
r64 OPERATOR ni32, //-LiftedDoubleKIND
r64 OPERATOR ni64, //-LiftedDoubleKIND
r64 OPERATOR nu16, //-LiftedDoubleKIND
r64 OPERATOR nu32, //-LiftedDoubleKIND
r64 OPERATOR nu64, //-LiftedDoubleKIND
r64 OPERATOR nr32, //-LiftedDoubleKIND
r64 OPERATOR nr64, //-LiftedDoubleKIND
// r64 OPERATOR ndec, (none applicable)
dec OPERATOR chr, //-DecimalKIND
dec OPERATOR i16, //-DecimalKIND
dec OPERATOR i32, //-DecimalKIND
dec OPERATOR i64, //-DecimalKIND
dec OPERATOR u16, //-DecimalKIND
dec OPERATOR u32, //-DecimalKIND
dec OPERATOR u64, //-DecimalKIND
// dec OPERATOR r32, (none applicable)
// dec OPERATOR r64, (none applicable)
dec OPERATOR dec, //-DecimalKIND
dec OPERATOR nchr, //-LiftedDecimalKIND
dec OPERATOR ni16, //-LiftedDecimalKIND
dec OPERATOR ni32, //-LiftedDecimalKIND
dec OPERATOR ni64, //-LiftedDecimalKIND
dec OPERATOR nu16, //-LiftedDecimalKIND
dec OPERATOR nu32, //-LiftedDecimalKIND
dec OPERATOR nu64, //-LiftedDecimalKIND
// dec OPERATOR nr32, (none applicable)
// dec OPERATOR nr64, (none applicable)
dec OPERATOR ndec, //-LiftedDecimalKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR i64, //-LiftedLongKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR u32, //-LiftedUIntKIND
nchr OPERATOR u64, //-LiftedULongKIND
nchr OPERATOR r32, //-LiftedFloatKIND
nchr OPERATOR r64, //-LiftedDoubleKIND
nchr OPERATOR dec, //-LiftedDecimalKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR ni64, //-LiftedLongKIND
nchr OPERATOR nu16, //-LiftedIntKIND
nchr OPERATOR nu32, //-LiftedUIntKIND
nchr OPERATOR nu64, //-LiftedULongKIND
nchr OPERATOR nr32, //-LiftedFloatKIND
nchr OPERATOR nr64, //-LiftedDoubleKIND
nchr OPERATOR ndec, //-LiftedDecimalKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR i64, //-LiftedLongKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR u32, //-LiftedLongKIND
// ni16 OPERATOR u64, (ambiguous)
ni16 OPERATOR r32, //-LiftedFloatKIND
ni16 OPERATOR r64, //-LiftedDoubleKIND
ni16 OPERATOR dec, //-LiftedDecimalKIND
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR ni64, //-LiftedLongKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR nu32, //-LiftedLongKIND
// ni16 OPERATOR nu64, (ambiguous)
ni16 OPERATOR nr32, //-LiftedFloatKIND
ni16 OPERATOR nr64, //-LiftedDoubleKIND
ni16 OPERATOR ndec, //-LiftedDecimalKIND
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR i64, //-LiftedLongKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR u32, //-LiftedLongKIND
// ni32 OPERATOR u64, (ambiguous)
ni32 OPERATOR r32, //-LiftedFloatKIND
ni32 OPERATOR r64, //-LiftedDoubleKIND
ni32 OPERATOR dec, //-LiftedDecimalKIND
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR ni64, //-LiftedLongKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR nu32, //-LiftedLongKIND
// ni32 OPERATOR nu64, (ambiguous)
ni32 OPERATOR nr32, //-LiftedFloatKIND
ni32 OPERATOR nr64, //-LiftedDoubleKIND
ni32 OPERATOR ndec, //-LiftedDecimalKIND
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR i64, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR u32, //-LiftedLongKIND
// ni64 OPERATOR u64, (ambiguous)
ni64 OPERATOR r32, //-LiftedFloatKIND
ni64 OPERATOR r64, //-LiftedDoubleKIND
ni64 OPERATOR dec, //-LiftedDecimalKIND
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR ni64, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
ni64 OPERATOR nu32, //-LiftedLongKIND
// ni64 OPERATOR nu64, (ambiguous)
ni64 OPERATOR nr32, //-LiftedFloatKIND
ni64 OPERATOR nr64, //-LiftedDoubleKIND
ni64 OPERATOR ndec, //-LiftedDecimalKIND
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR i64, //-LiftedLongKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR u32, //-LiftedUIntKIND
nu16 OPERATOR u64, //-LiftedULongKIND
nu16 OPERATOR r32, //-LiftedFloatKIND
nu16 OPERATOR r64, //-LiftedDoubleKIND
nu16 OPERATOR dec, //-LiftedDecimalKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR ni64, //-LiftedLongKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu16 OPERATOR nu32, //-LiftedUIntKIND
nu16 OPERATOR nu64, //-LiftedULongKIND
nu16 OPERATOR nr32, //-LiftedFloatKIND
nu16 OPERATOR nr64, //-LiftedDoubleKIND
nu16 OPERATOR ndec, //-LiftedDecimalKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedLongKIND
nu32 OPERATOR i32, //-LiftedLongKIND
nu32 OPERATOR i64, //-LiftedLongKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR u32, //-LiftedUIntKIND
nu32 OPERATOR u64, //-LiftedULongKIND
nu32 OPERATOR r32, //-LiftedFloatKIND
nu32 OPERATOR r64, //-LiftedDoubleKIND
nu32 OPERATOR dec, //-LiftedDecimalKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedLongKIND
nu32 OPERATOR ni32, //-LiftedLongKIND
nu32 OPERATOR ni64, //-LiftedLongKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu32 OPERATOR nu32, //-LiftedUIntKIND
nu32 OPERATOR nu64, //-LiftedULongKIND
nu32 OPERATOR nr32, //-LiftedFloatKIND
nu32 OPERATOR nr64, //-LiftedDoubleKIND
nu32 OPERATOR ndec, //-LiftedDecimalKIND
nu64 OPERATOR chr, //-LiftedULongKIND
// nu64 OPERATOR i16, (ambiguous)
// nu64 OPERATOR i32, (ambiguous)
// nu64 OPERATOR i64, (ambiguous)
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR u32, //-LiftedULongKIND
nu64 OPERATOR u64, //-LiftedULongKIND
nu64 OPERATOR r32, //-LiftedFloatKIND
nu64 OPERATOR r64, //-LiftedDoubleKIND
nu64 OPERATOR dec, //-LiftedDecimalKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
// nu64 OPERATOR ni16, (ambiguous)
// nu64 OPERATOR ni32, (ambiguous)
// nu64 OPERATOR ni64, (ambiguous)
nu64 OPERATOR nu16, //-LiftedULongKIND
nu64 OPERATOR nu32, //-LiftedULongKIND
nu64 OPERATOR nu64, //-LiftedULongKIND
nu64 OPERATOR nr32, //-LiftedFloatKIND
nu64 OPERATOR nr64, //-LiftedDoubleKIND
nu64 OPERATOR ndec, //-LiftedDecimalKIND
nr32 OPERATOR chr, //-LiftedFloatKIND
nr32 OPERATOR i16, //-LiftedFloatKIND
nr32 OPERATOR i32, //-LiftedFloatKIND
nr32 OPERATOR i64, //-LiftedFloatKIND
nr32 OPERATOR u16, //-LiftedFloatKIND
nr32 OPERATOR u32, //-LiftedFloatKIND
nr32 OPERATOR u64, //-LiftedFloatKIND
nr32 OPERATOR r32, //-LiftedFloatKIND
nr32 OPERATOR r64, //-LiftedDoubleKIND
// nr32 OPERATOR dec, (none applicable)
nr32 OPERATOR nchr, //-LiftedFloatKIND
nr32 OPERATOR ni16, //-LiftedFloatKIND
nr32 OPERATOR ni32, //-LiftedFloatKIND
nr32 OPERATOR ni64, //-LiftedFloatKIND
nr32 OPERATOR nu16, //-LiftedFloatKIND
nr32 OPERATOR nu32, //-LiftedFloatKIND
nr32 OPERATOR nu64, //-LiftedFloatKIND
nr32 OPERATOR nr32, //-LiftedFloatKIND
nr32 OPERATOR nr64, //-LiftedDoubleKIND
// nr32 OPERATOR ndec, (none applicable)
nr64 OPERATOR chr, //-LiftedDoubleKIND
nr64 OPERATOR i16, //-LiftedDoubleKIND
nr64 OPERATOR i32, //-LiftedDoubleKIND
nr64 OPERATOR i64, //-LiftedDoubleKIND
nr64 OPERATOR u16, //-LiftedDoubleKIND
nr64 OPERATOR u32, //-LiftedDoubleKIND
nr64 OPERATOR u64, //-LiftedDoubleKIND
nr64 OPERATOR r32, //-LiftedDoubleKIND
nr64 OPERATOR r64, //-LiftedDoubleKIND
// nr64 OPERATOR dec, (none applicable)
nr64 OPERATOR nchr, //-LiftedDoubleKIND
nr64 OPERATOR ni16, //-LiftedDoubleKIND
nr64 OPERATOR ni32, //-LiftedDoubleKIND
nr64 OPERATOR ni64, //-LiftedDoubleKIND
nr64 OPERATOR nu16, //-LiftedDoubleKIND
nr64 OPERATOR nu32, //-LiftedDoubleKIND
nr64 OPERATOR nu64, //-LiftedDoubleKIND
nr64 OPERATOR nr32, //-LiftedDoubleKIND
nr64 OPERATOR nr64, //-LiftedDoubleKIND
// nr64 OPERATOR ndec, (none applicable)
ndec OPERATOR chr, //-LiftedDecimalKIND
ndec OPERATOR i16, //-LiftedDecimalKIND
ndec OPERATOR i32, //-LiftedDecimalKIND
ndec OPERATOR i64, //-LiftedDecimalKIND
ndec OPERATOR u16, //-LiftedDecimalKIND
ndec OPERATOR u32, //-LiftedDecimalKIND
ndec OPERATOR u64, //-LiftedDecimalKIND
// ndec OPERATOR r32, (none applicable)
// ndec OPERATOR r64, (none applicable)
ndec OPERATOR dec, //-LiftedDecimalKIND
ndec OPERATOR nchr, //-LiftedDecimalKIND
ndec OPERATOR ni16, //-LiftedDecimalKIND
ndec OPERATOR ni32, //-LiftedDecimalKIND
ndec OPERATOR ni64, //-LiftedDecimalKIND
ndec OPERATOR nu16, //-LiftedDecimalKIND
ndec OPERATOR nu32, //-LiftedDecimalKIND
ndec OPERATOR nu64, //-LiftedDecimalKIND
// ndec OPERATOR nr32, (none applicable)
// ndec OPERATOR nr64, (none applicable)
ndec OPERATOR ndec //-LiftedDecimalKIND" + Postfix;
private const string EnumSubtraction = Prefix + @"
e - e, //-EnumSubtraction
e - ne, //-LiftedEnumSubtraction
e - i, //-EnumAndUnderlyingSubtraction
e - ni, //-LiftedEnumAndUnderlyingSubtraction
ne - e, //-LiftedEnumSubtraction
ne - ne, //-LiftedEnumSubtraction
ne - i, //-LiftedEnumAndUnderlyingSubtraction
ne - ni //-LiftedEnumAndUnderlyingSubtraction" + Postfix;
private const string DelegateSubtraction = Prefix + "d1 - d2 //-DelegateRemoval" + Postfix;
private const string ShiftTemplate = Prefix + @"
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-UIntKIND
u32 OPERATOR i32, //-UIntKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedUIntKIND
u32 OPERATOR ni32, //-LiftedUIntKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u64 OPERATOR chr, //-ULongKIND
u64 OPERATOR i16, //-ULongKIND
u64 OPERATOR i32, //-ULongKIND
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR nchr, //-LiftedULongKIND
u64 OPERATOR ni16, //-LiftedULongKIND
u64 OPERATOR ni32, //-LiftedULongKIND
u64 OPERATOR nu16, //-LiftedULongKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedUIntKIND
nu32 OPERATOR i32, //-LiftedUIntKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedUIntKIND
nu32 OPERATOR ni32, //-LiftedUIntKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu64 OPERATOR chr, //-LiftedULongKIND
nu64 OPERATOR i16, //-LiftedULongKIND
nu64 OPERATOR i32, //-LiftedULongKIND
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
nu64 OPERATOR ni16, //-LiftedULongKIND
nu64 OPERATOR ni32, //-LiftedULongKIND
nu64 OPERATOR nu16 //-LiftedULongKIND
" + Postfix;
private const string LogicTemplate = Prefix + @"
bln OPERATOR bln, //-BoolKIND
bln OPERATOR nbln, //-LiftedBoolKIND
nbln OPERATOR bln, //-LiftedBoolKIND
nbln OPERATOR nbln, //-LiftedBoolKIND
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR i64, //-LongKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR u32, //-UIntKIND
chr OPERATOR u64, //-ULongKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR ni64, //-LiftedLongKIND
chr OPERATOR nu16, //-LiftedIntKIND
chr OPERATOR nu32, //-LiftedUIntKIND
chr OPERATOR nu64, //-LiftedULongKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR i64, //-LongKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR u32, //-LongKIND
// i16 OPERATOR u64,
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR ni64, //-LiftedLongKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR nu32, //-LiftedLongKIND
//i16 OPERATOR nu64,
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR i64, //-LongKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR u32, //-LongKIND
//i32 OPERATOR u64,
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR ni64, //-LiftedLongKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR nu32, //-LiftedLongKIND
//i32 OPERATOR nu64,
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR i64, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR u32, //-LongKIND
//i64 OPERATOR u64,
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR ni64, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
i64 OPERATOR nu32, //-LiftedLongKIND
//i64 OPERATOR nu64,
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR i64, //-LongKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR u32, //-UIntKIND
u16 OPERATOR u64, //-ULongKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR ni64, //-LiftedLongKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u16 OPERATOR nu32, //-LiftedUIntKIND
u16 OPERATOR nu64, //-LiftedULongKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-LongKIND
u32 OPERATOR i32, //-LongKIND
u32 OPERATOR i64, //-LongKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR u32, //-UIntKIND
u32 OPERATOR u64, //-ULongKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedLongKIND
u32 OPERATOR ni32, //-LiftedLongKIND
u32 OPERATOR ni64, //-LiftedLongKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u32 OPERATOR nu32, //-LiftedUIntKIND
u32 OPERATOR nu64, //-LiftedULongKIND
u64 OPERATOR chr, //-ULongKIND
//u64 OPERATOR i16,
//u64 OPERATOR i32,
//u64 OPERATOR i64,
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR u32, //-ULongKIND
u64 OPERATOR u64, //-ULongKIND
u64 OPERATOR nchr, //-LiftedULongKIND
//u64 OPERATOR ni16,
//u64 OPERATOR ni32,
//u64 OPERATOR ni64,
u64 OPERATOR nu16, //-LiftedULongKIND
u64 OPERATOR nu32, //-LiftedULongKIND
u64 OPERATOR nu64, //-LiftedULongKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR i64, //-LiftedLongKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR u32, //-LiftedUIntKIND
nchr OPERATOR u64, //-LiftedULongKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR ni64, //-LiftedLongKIND
nchr OPERATOR nu16, //-LiftedIntKIND
nchr OPERATOR nu32, //-LiftedUIntKIND
nchr OPERATOR nu64, //-LiftedULongKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR i64, //-LiftedLongKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR u32, //-LiftedLongKIND
//ni16 OPERATOR u64,
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR ni64, //-LiftedLongKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR nu32, //-LiftedLongKIND
//ni16 OPERATOR nu64,
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR i64, //-LiftedLongKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR u32, //-LiftedLongKIND
//ni32 OPERATOR u64,
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR ni64, //-LiftedLongKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR nu32, //-LiftedLongKIND
//ni32 OPERATOR nu64,
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR i64, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR u32, //-LiftedLongKIND
//ni64 OPERATOR u64,
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR ni64, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
ni64 OPERATOR nu32, //-LiftedLongKIND
//ni64 OPERATOR nu64,
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR i64, //-LiftedLongKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR u32, //-LiftedUIntKIND
nu16 OPERATOR u64, //-LiftedULongKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR ni64, //-LiftedLongKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu16 OPERATOR nu32, //-LiftedUIntKIND
nu16 OPERATOR nu64, //-LiftedULongKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedLongKIND
nu32 OPERATOR i32, //-LiftedLongKIND
nu32 OPERATOR i64, //-LiftedLongKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR u32, //-LiftedUIntKIND
nu32 OPERATOR u64, //-LiftedULongKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedLongKIND
nu32 OPERATOR ni32, //-LiftedLongKIND
nu32 OPERATOR ni64, //-LiftedLongKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu32 OPERATOR nu32, //-LiftedUIntKIND
nu32 OPERATOR nu64, //-LiftedULongKIND
nu64 OPERATOR chr, //-LiftedULongKIND
//nu64 OPERATOR i16,
//nu64 OPERATOR i32,
//nu64 OPERATOR i64,
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR u32, //-LiftedULongKIND
nu64 OPERATOR u64, //-LiftedULongKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
//nu64 OPERATOR ni16,
//nu64 OPERATOR ni32,
//nu64 OPERATOR ni64,
nu64 OPERATOR nu16, //-LiftedULongKIND
nu64 OPERATOR nu32, //-LiftedULongKIND
nu64 OPERATOR nu64 //-LiftedULongKIND
" + Postfix;
//built-in operator only works for bools (not even lifted bools)
private const string ShortCircuitTemplate = Prefix + @"
bln OPERATOR bln, //-LogicalBoolKIND
" + Postfix;
private const string EnumLogicTemplate = Prefix + @"
e OPERATOR e, //-EnumKIND
e OPERATOR ne, //-LiftedEnumKIND
ne OPERATOR e, //-LiftedEnumKIND
ne OPERATOR ne //-LiftedEnumKIND" + Postfix;
private const string ComparisonTemplate = Prefix + @"
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR i64, //-LongKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR u32, //-UIntKIND
chr OPERATOR u64, //-ULongKIND
chr OPERATOR r32, //-FloatKIND
chr OPERATOR r64, //-DoubleKIND
chr OPERATOR dec, //-DecimalKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR ni64, //-LiftedLongKIND
chr OPERATOR nu16, //-LiftedIntKIND
chr OPERATOR nu32, //-LiftedUIntKIND
chr OPERATOR nu64, //-LiftedULongKIND
chr OPERATOR nr32, //-LiftedFloatKIND
chr OPERATOR nr64, //-LiftedDoubleKIND
chr OPERATOR ndec, //-LiftedDecimalKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR i64, //-LongKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR u32, //-LongKIND
// i16 OPERATOR u64, (ambiguous)
i16 OPERATOR r32, //-FloatKIND
i16 OPERATOR r64, //-DoubleKIND
i16 OPERATOR dec, //-DecimalKIND
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR ni64, //-LiftedLongKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR nu32, //-LiftedLongKIND
// i16 OPERATOR nu64, (ambiguous)
i16 OPERATOR nr32, //-LiftedFloatKIND
i16 OPERATOR nr64, //-LiftedDoubleKIND
i16 OPERATOR ndec, //-LiftedDecimalKIND
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR i64, //-LongKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR u32, //-LongKIND
// i32 OPERATOR u64, (ambiguous)
i32 OPERATOR r32, //-FloatKIND
i32 OPERATOR r64, //-DoubleKIND
i32 OPERATOR dec, //-DecimalKIND
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR ni64, //-LiftedLongKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR nu32, //-LiftedLongKIND
// i32 OPERATOR nu64, (ambiguous)
i32 OPERATOR nr32, //-LiftedFloatKIND
i32 OPERATOR nr64, //-LiftedDoubleKIND
i32 OPERATOR ndec, //-LiftedDecimalKIND
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR i64, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR u32, //-LongKIND
// i64 OPERATOR u64, (ambiguous)
i64 OPERATOR r32, //-FloatKIND
i64 OPERATOR r64, //-DoubleKIND
i64 OPERATOR dec, //-DecimalKIND
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR ni64, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
i64 OPERATOR nu32, //-LiftedLongKIND
// i64 OPERATOR nu64, (ambiguous)
i64 OPERATOR nr32, //-LiftedFloatKIND
i64 OPERATOR nr64, //-LiftedDoubleKIND
i64 OPERATOR ndec, //-LiftedDecimalKIND
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR i64, //-LongKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR u32, //-UIntKIND
//u16 OPERATOR u64, (ambiguous)
u16 OPERATOR r32, //-FloatKIND
u16 OPERATOR r64, //-DoubleKIND
u16 OPERATOR dec, //-DecimalKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR ni64, //-LiftedLongKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u16 OPERATOR nu32, //-LiftedUIntKIND
//u16 OPERATOR nu64, (ambiguous)
u16 OPERATOR nr32, //-LiftedFloatKIND
u16 OPERATOR nr64, //-LiftedDoubleKIND
u16 OPERATOR ndec, //-LiftedDecimalKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-LongKIND
u32 OPERATOR i32, //-LongKIND
u32 OPERATOR i64, //-LongKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR u32, //-UIntKIND
u32 OPERATOR u64, //-ULongKIND
u32 OPERATOR r32, //-FloatKIND
u32 OPERATOR r64, //-DoubleKIND
u32 OPERATOR dec, //-DecimalKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedLongKIND
u32 OPERATOR ni32, //-LiftedLongKIND
u32 OPERATOR ni64, //-LiftedLongKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u32 OPERATOR nu32, //-LiftedUIntKIND
u32 OPERATOR nu64, //-LiftedULongKIND
u32 OPERATOR nr32, //-LiftedFloatKIND
u32 OPERATOR nr64, //-LiftedDoubleKIND
u32 OPERATOR ndec, //-LiftedDecimalKIND
u64 OPERATOR chr, //-ULongKIND
// u64 OPERATOR i16, (ambiguous)
// u64 OPERATOR i32, (ambiguous)
// u64 OPERATOR i64, (ambiguous)
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR u32, //-ULongKIND
u64 OPERATOR u64, //-ULongKIND
u64 OPERATOR r32, //-FloatKIND
u64 OPERATOR r64, //-DoubleKIND
u64 OPERATOR dec, //-DecimalKIND
u64 OPERATOR nchr, //-LiftedULongKIND
// u64 OPERATOR ni16, (ambiguous)
// u64 OPERATOR ni32, (ambiguous)
// u64 OPERATOR ni64, (ambiguous)
u64 OPERATOR nu16, //-LiftedULongKIND
u64 OPERATOR nu32, //-LiftedULongKIND
u64 OPERATOR nu64, //-LiftedULongKIND
u64 OPERATOR nr32, //-LiftedFloatKIND
u64 OPERATOR nr64, //-LiftedDoubleKIND
u64 OPERATOR ndec, //-LiftedDecimalKIND
r32 OPERATOR chr, //-FloatKIND
r32 OPERATOR i16, //-FloatKIND
r32 OPERATOR i32, //-FloatKIND
r32 OPERATOR i64, //-FloatKIND
r32 OPERATOR u16, //-FloatKIND
r32 OPERATOR u32, //-FloatKIND
r32 OPERATOR u64, //-FloatKIND
r32 OPERATOR r32, //-FloatKIND
r32 OPERATOR r64, //-DoubleKIND
// r32 OPERATOR dec, (none applicable)
r32 OPERATOR nchr, //-LiftedFloatKIND
r32 OPERATOR ni16, //-LiftedFloatKIND
r32 OPERATOR ni32, //-LiftedFloatKIND
r32 OPERATOR ni64, //-LiftedFloatKIND
r32 OPERATOR nu16, //-LiftedFloatKIND
r32 OPERATOR nu32, //-LiftedFloatKIND
r32 OPERATOR nu64, //-LiftedFloatKIND
r32 OPERATOR nr32, //-LiftedFloatKIND
r32 OPERATOR nr64, //-LiftedDoubleKIND
// r32 OPERATOR ndec, (none applicable)
r64 OPERATOR chr, //-DoubleKIND
r64 OPERATOR i16, //-DoubleKIND
r64 OPERATOR i32, //-DoubleKIND
r64 OPERATOR i64, //-DoubleKIND
r64 OPERATOR u16, //-DoubleKIND
r64 OPERATOR u32, //-DoubleKIND
r64 OPERATOR u64, //-DoubleKIND
r64 OPERATOR r32, //-DoubleKIND
r64 OPERATOR r64, //-DoubleKIND
// r64 OPERATOR dec, (none applicable)
r64 OPERATOR nchr, //-LiftedDoubleKIND
r64 OPERATOR ni16, //-LiftedDoubleKIND
r64 OPERATOR ni32, //-LiftedDoubleKIND
r64 OPERATOR ni64, //-LiftedDoubleKIND
r64 OPERATOR nu16, //-LiftedDoubleKIND
r64 OPERATOR nu32, //-LiftedDoubleKIND
r64 OPERATOR nu64, //-LiftedDoubleKIND
r64 OPERATOR nr32, //-LiftedDoubleKIND
r64 OPERATOR nr64, //-LiftedDoubleKIND
// r64 OPERATOR ndec, (none applicable)
dec OPERATOR chr, //-DecimalKIND
dec OPERATOR i16, //-DecimalKIND
dec OPERATOR i32, //-DecimalKIND
dec OPERATOR i64, //-DecimalKIND
dec OPERATOR u16, //-DecimalKIND
dec OPERATOR u32, //-DecimalKIND
dec OPERATOR u64, //-DecimalKIND
// dec OPERATOR r32, (none applicable)
// dec OPERATOR r64, (none applicable)
dec OPERATOR dec, //-DecimalKIND
dec OPERATOR nchr, //-LiftedDecimalKIND
dec OPERATOR ni16, //-LiftedDecimalKIND
dec OPERATOR ni32, //-LiftedDecimalKIND
dec OPERATOR ni64, //-LiftedDecimalKIND
dec OPERATOR nu16, //-LiftedDecimalKIND
dec OPERATOR nu32, //-LiftedDecimalKIND
dec OPERATOR nu64, //-LiftedDecimalKIND
// dec OPERATOR nr32, (none applicable)
// dec OPERATOR nr64, (none applicable)
dec OPERATOR ndec, //-LiftedDecimalKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR i64, //-LiftedLongKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR u32, //-LiftedUIntKIND
nchr OPERATOR u64, //-LiftedULongKIND
nchr OPERATOR r32, //-LiftedFloatKIND
nchr OPERATOR r64, //-LiftedDoubleKIND
nchr OPERATOR dec, //-LiftedDecimalKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR ni64, //-LiftedLongKIND
nchr OPERATOR nu16, //-LiftedIntKIND
nchr OPERATOR nu32, //-LiftedUIntKIND
nchr OPERATOR nu64, //-LiftedULongKIND
nchr OPERATOR nr32, //-LiftedFloatKIND
nchr OPERATOR nr64, //-LiftedDoubleKIND
nchr OPERATOR ndec, //-LiftedDecimalKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR i64, //-LiftedLongKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR u32, //-LiftedLongKIND
// ni16 OPERATOR u64, (ambiguous)
ni16 OPERATOR r32, //-LiftedFloatKIND
ni16 OPERATOR r64, //-LiftedDoubleKIND
ni16 OPERATOR dec, //-LiftedDecimalKIND
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR ni64, //-LiftedLongKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR nu32, //-LiftedLongKIND
// ni16 OPERATOR nu64, (ambiguous)
ni16 OPERATOR nr32, //-LiftedFloatKIND
ni16 OPERATOR nr64, //-LiftedDoubleKIND
ni16 OPERATOR ndec, //-LiftedDecimalKIND
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR i64, //-LiftedLongKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR u32, //-LiftedLongKIND
// ni32 OPERATOR u64, (ambiguous)
ni32 OPERATOR r32, //-LiftedFloatKIND
ni32 OPERATOR r64, //-LiftedDoubleKIND
ni32 OPERATOR dec, //-LiftedDecimalKIND
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR ni64, //-LiftedLongKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR nu32, //-LiftedLongKIND
// ni32 OPERATOR nu64, (ambiguous)
ni32 OPERATOR nr32, //-LiftedFloatKIND
ni32 OPERATOR nr64, //-LiftedDoubleKIND
ni32 OPERATOR ndec, //-LiftedDecimalKIND
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR i64, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR u32, //-LiftedLongKIND
// ni64 OPERATOR u64, (ambiguous)
ni64 OPERATOR r32, //-LiftedFloatKIND
ni64 OPERATOR r64, //-LiftedDoubleKIND
ni64 OPERATOR dec, //-LiftedDecimalKIND
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR ni64, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
ni64 OPERATOR nu32, //-LiftedLongKIND
// ni64 OPERATOR nu64, (ambiguous)
ni64 OPERATOR nr32, //-LiftedFloatKIND
ni64 OPERATOR nr64, //-LiftedDoubleKIND
ni64 OPERATOR ndec, //-LiftedDecimalKIND
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR i64, //-LiftedLongKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR u32, //-LiftedUIntKIND
//nu16 OPERATOR u64, (ambiguous)
nu16 OPERATOR r32, //-LiftedFloatKIND
nu16 OPERATOR r64, //-LiftedDoubleKIND
nu16 OPERATOR dec, //-LiftedDecimalKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR ni64, //-LiftedLongKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu16 OPERATOR nu32, //-LiftedUIntKIND
//nu16 OPERATOR nu64, (ambiguous)
nu16 OPERATOR nr32, //-LiftedFloatKIND
nu16 OPERATOR nr64, //-LiftedDoubleKIND
nu16 OPERATOR ndec, //-LiftedDecimalKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedLongKIND
nu32 OPERATOR i32, //-LiftedLongKIND
nu32 OPERATOR i64, //-LiftedLongKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR u32, //-LiftedUIntKIND
nu32 OPERATOR u64, //-LiftedULongKIND
nu32 OPERATOR r32, //-LiftedFloatKIND
nu32 OPERATOR r64, //-LiftedDoubleKIND
nu32 OPERATOR dec, //-LiftedDecimalKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedLongKIND
nu32 OPERATOR ni32, //-LiftedLongKIND
nu32 OPERATOR ni64, //-LiftedLongKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu32 OPERATOR nu32, //-LiftedUIntKIND
nu32 OPERATOR nu64, //-LiftedULongKIND
nu32 OPERATOR nr32, //-LiftedFloatKIND
nu32 OPERATOR nr64, //-LiftedDoubleKIND
nu32 OPERATOR ndec, //-LiftedDecimalKIND
nu64 OPERATOR chr, //-LiftedULongKIND
// nu64 OPERATOR i16, (ambiguous)
// nu64 OPERATOR i32, (ambiguous)
// nu64 OPERATOR i64, (ambiguous)
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR u32, //-LiftedULongKIND
nu64 OPERATOR u64, //-LiftedULongKIND
nu64 OPERATOR r32, //-LiftedFloatKIND
nu64 OPERATOR r64, //-LiftedDoubleKIND
nu64 OPERATOR dec, //-LiftedDecimalKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
// nu64 OPERATOR ni16, (ambiguous)
// nu64 OPERATOR ni32, (ambiguous)
// nu64 OPERATOR ni64, (ambiguous)
nu64 OPERATOR nu16, //-LiftedULongKIND
nu64 OPERATOR nu32, //-LiftedULongKIND
nu64 OPERATOR nu64, //-LiftedULongKIND
nu64 OPERATOR nr32, //-LiftedFloatKIND
nu64 OPERATOR nr64, //-LiftedDoubleKIND
nu64 OPERATOR ndec, //-LiftedDecimalKIND
nr32 OPERATOR chr, //-LiftedFloatKIND
nr32 OPERATOR i16, //-LiftedFloatKIND
nr32 OPERATOR i32, //-LiftedFloatKIND
nr32 OPERATOR i64, //-LiftedFloatKIND
nr32 OPERATOR u16, //-LiftedFloatKIND
nr32 OPERATOR u32, //-LiftedFloatKIND
nr32 OPERATOR u64, //-LiftedFloatKIND
nr32 OPERATOR r32, //-LiftedFloatKIND
nr32 OPERATOR r64, //-LiftedDoubleKIND
// nr32 OPERATOR dec, (none applicable)
nr32 OPERATOR nchr, //-LiftedFloatKIND
nr32 OPERATOR ni16, //-LiftedFloatKIND
nr32 OPERATOR ni32, //-LiftedFloatKIND
nr32 OPERATOR ni64, //-LiftedFloatKIND
nr32 OPERATOR nu16, //-LiftedFloatKIND
nr32 OPERATOR nu32, //-LiftedFloatKIND
nr32 OPERATOR nu64, //-LiftedFloatKIND
nr32 OPERATOR nr32, //-LiftedFloatKIND
nr32 OPERATOR nr64, //-LiftedDoubleKIND
// nr32 OPERATOR ndec, (none applicable)
nr64 OPERATOR chr, //-LiftedDoubleKIND
nr64 OPERATOR i16, //-LiftedDoubleKIND
nr64 OPERATOR i32, //-LiftedDoubleKIND
nr64 OPERATOR i64, //-LiftedDoubleKIND
nr64 OPERATOR u16, //-LiftedDoubleKIND
nr64 OPERATOR u32, //-LiftedDoubleKIND
nr64 OPERATOR u64, //-LiftedDoubleKIND
nr64 OPERATOR r32, //-LiftedDoubleKIND
nr64 OPERATOR r64, //-LiftedDoubleKIND
// nr64 OPERATOR dec, (none applicable)
nr64 OPERATOR nchr, //-LiftedDoubleKIND
nr64 OPERATOR ni16, //-LiftedDoubleKIND
nr64 OPERATOR ni32, //-LiftedDoubleKIND
nr64 OPERATOR ni64, //-LiftedDoubleKIND
nr64 OPERATOR nu16, //-LiftedDoubleKIND
nr64 OPERATOR nu32, //-LiftedDoubleKIND
nr64 OPERATOR nu64, //-LiftedDoubleKIND
nr64 OPERATOR nr32, //-LiftedDoubleKIND
nr64 OPERATOR nr64, //-LiftedDoubleKIND
// nr64 OPERATOR ndec, (none applicable)
ndec OPERATOR chr, //-LiftedDecimalKIND
ndec OPERATOR i16, //-LiftedDecimalKIND
ndec OPERATOR i32, //-LiftedDecimalKIND
ndec OPERATOR i64, //-LiftedDecimalKIND
ndec OPERATOR u16, //-LiftedDecimalKIND
ndec OPERATOR u32, //-LiftedDecimalKIND
ndec OPERATOR u64, //-LiftedDecimalKIND
// ndec OPERATOR r32, (none applicable)
// ndec OPERATOR r64, (none applicable)
ndec OPERATOR dec, //-LiftedDecimalKIND
ndec OPERATOR nchr, //-LiftedDecimalKIND
ndec OPERATOR ni16, //-LiftedDecimalKIND
ndec OPERATOR ni32, //-LiftedDecimalKIND
ndec OPERATOR ni64, //-LiftedDecimalKIND
ndec OPERATOR nu16, //-LiftedDecimalKIND
ndec OPERATOR nu32, //-LiftedDecimalKIND
ndec OPERATOR nu64, //-LiftedDecimalKIND
// ndec OPERATOR nr32, (none applicable)
// ndec OPERATOR nr64, (none applicable)
ndec OPERATOR ndec //-LiftedDecimalKIND
" + Postfix;
private const string EqualityTemplate = Prefix + @"
e1 OPERATOR e2, //-EnumKIND
e1 OPERATOR o2, //-KIND
d1 OPERATOR d2, //-DelegateKIND
d1 OPERATOR o2, //-ObjectKIND
s1 OPERATOR s2, //-StringKIND
s1 OPERATOR o2, //-ObjectKIND
o1 OPERATOR e2, //-KIND
o1 OPERATOR d2, //-ObjectKIND
o1 OPERATOR s2, //-ObjectKIND
o1 OPERATOR o2 //-ObjectKIND" + Postfix;
private const string PostfixIncrementTemplate = Prefix + @"
e OPERATOR, //-EnumKIND
chr OPERATOR, //-CharKIND
i08 OPERATOR, //-SByteKIND
i16 OPERATOR, //-ShortKIND
i32 OPERATOR, //-IntKIND
i64 OPERATOR, //-LongKIND
u08 OPERATOR, //-ByteKIND
u16 OPERATOR, //-UShortKIND
u32 OPERATOR, //-UIntKIND
u64 OPERATOR, //-ULongKIND
r32 OPERATOR, //-FloatKIND
r64 OPERATOR, //-DoubleKIND
dec OPERATOR, //-DecimalKIND
ne OPERATOR, //-LiftedEnumKIND
nchr OPERATOR, //-LiftedCharKIND
ni08 OPERATOR, //-LiftedSByteKIND
ni16 OPERATOR, //-LiftedShortKIND
ni32 OPERATOR, //-LiftedIntKIND
ni64 OPERATOR, //-LiftedLongKIND
nu08 OPERATOR, //-LiftedByteKIND
nu16 OPERATOR, //-LiftedUShortKIND
nu32 OPERATOR, //-LiftedUIntKIND
nu64 OPERATOR, //-LiftedULongKIND
nr32 OPERATOR, //-LiftedFloatKIND
nr64 OPERATOR, //-LiftedDoubleKIND
ndec OPERATOR //-LiftedDecimalKIND
" + Postfix;
private const string PrefixIncrementTemplate = Prefix + @"
OPERATOR e , //-EnumKIND
OPERATOR chr , //-CharKIND
OPERATOR i08 , //-SByteKIND
OPERATOR i16 , //-ShortKIND
OPERATOR i32 , //-IntKIND
OPERATOR i64 , //-LongKIND
OPERATOR u08 , //-ByteKIND
OPERATOR u16 , //-UShortKIND
OPERATOR u32 , //-UIntKIND
OPERATOR u64 , //-ULongKIND
OPERATOR r32 , //-FloatKIND
OPERATOR r64 , //-DoubleKIND
OPERATOR dec , //-DecimalKIND
OPERATOR ne , //-LiftedEnumKIND
OPERATOR nchr , //-LiftedCharKIND
OPERATOR ni08 , //-LiftedSByteKIND
OPERATOR ni16 , //-LiftedShortKIND
OPERATOR ni32 , //-LiftedIntKIND
OPERATOR ni64 , //-LiftedLongKIND
OPERATOR nu08 , //-LiftedByteKIND
OPERATOR nu16 , //-LiftedUShortKIND
OPERATOR nu32 , //-LiftedUIntKIND
OPERATOR nu64 , //-LiftedULongKIND
OPERATOR nr32 , //-LiftedFloatKIND
OPERATOR nr64 , //-LiftedDoubleKIND
OPERATOR ndec //-LiftedDecimalKIND" + Postfix;
private const string UnaryPlus = Prefix + @"
+ chr, //-IntUnaryPlus
+ i08, //-IntUnaryPlus
+ i16, //-IntUnaryPlus
+ i32, //-IntUnaryPlus
+ i64, //-LongUnaryPlus
+ u08, //-IntUnaryPlus
+ u16, //-IntUnaryPlus
+ u32, //-UIntUnaryPlus
+ u64, //-ULongUnaryPlus
+ r32, //-FloatUnaryPlus
+ r64, //-DoubleUnaryPlus
+ dec, //-DecimalUnaryPlus
+ nchr, //-LiftedIntUnaryPlus
+ ni08, //-LiftedIntUnaryPlus
+ ni16, //-LiftedIntUnaryPlus
+ ni32, //-LiftedIntUnaryPlus
+ ni64, //-LiftedLongUnaryPlus
+ nu08, //-LiftedIntUnaryPlus
+ nu16, //-LiftedIntUnaryPlus
+ nu32, //-LiftedUIntUnaryPlus
+ nu64, //-LiftedULongUnaryPlus
+ nr32, //-LiftedFloatUnaryPlus
+ nr64, //-LiftedDoubleUnaryPlus
+ ndec //-LiftedDecimalUnaryPlus" + Postfix;
private const string UnaryMinus = Prefix + @"
- chr, //-IntUnaryMinus
- i08, //-IntUnaryMinus
- i16, //-IntUnaryMinus
- i32, //-IntUnaryMinus
- i64, //-LongUnaryMinus
- u08, //-IntUnaryMinus
- u16, //-IntUnaryMinus
- u32, //-LongUnaryMinus
- r32, //-FloatUnaryMinus
- r64, //-DoubleUnaryMinus
- dec, //-DecimalUnaryMinus
- nchr, //-LiftedIntUnaryMinus
- ni08, //-LiftedIntUnaryMinus
- ni16, //-LiftedIntUnaryMinus
- ni32, //-LiftedIntUnaryMinus
- ni64, //-LiftedLongUnaryMinus
- nu08, //-LiftedIntUnaryMinus
- nu16, //-LiftedIntUnaryMinus
- nu32, //-LiftedLongUnaryMinus
- nr32, //-LiftedFloatUnaryMinus
- nr64, //-LiftedDoubleUnaryMinus
- ndec //-LiftedDecimalUnaryMinus" + Postfix;
private const string LogicalNegation = Prefix + @"
! bln, //-BoolLogicalNegation
! nbln //-LiftedBoolLogicalNegation" + Postfix;
private const string BitwiseComplement = Prefix + @"
~ e, //-EnumBitwiseComplement
~ chr, //-IntBitwiseComplement
~ i08, //-IntBitwiseComplement
~ i16, //-IntBitwiseComplement
~ i32, //-IntBitwiseComplement
~ i64, //-LongBitwiseComplement
~ u08, //-IntBitwiseComplement
~ u16, //-IntBitwiseComplement
~ u32, //-UIntBitwiseComplement
~ u64, //-ULongBitwiseComplement
~ ne, //-LiftedEnumBitwiseComplement
~ nchr, //-LiftedIntBitwiseComplement
~ ni08, //-LiftedIntBitwiseComplement
~ ni16, //-LiftedIntBitwiseComplement
~ ni32, //-LiftedIntBitwiseComplement
~ ni64, //-LiftedLongBitwiseComplement
~ nu08, //-LiftedIntBitwiseComplement
~ nu16, //-LiftedIntBitwiseComplement
~ nu32, //-LiftedUIntBitwiseComplement
~ nu64 //-LiftedULongBitwiseComplement
);
}
}" + Postfix;
#endregion
[Fact, WorkItem(527598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527598")]
public void UserDefinedOperatorOnPointerType()
{
CreateCompilation(@"
unsafe struct A
{
public static implicit operator int*(A x) { return null; }
static void M()
{
var x = new A();
int* y = null;
var z = x - y; // Dev11 generates CS0019...should compile
}
}
", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
// add better verification once this is implemented
}
[Fact]
public void TestNullCoalesce_Dynamic()
{
var source = @"
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
Dynamic_b_constant_null_a();
Dynamic_b_constant_null_a_nullable();
Dynamic_b_constant_not_null_a_nullable();
Dynamic_b_not_null_a();
Dynamic_b_not_null_a_nullable(10);
return 0;
}
public static D Dynamic_b_constant_null_a()
{
dynamic b = new D();
D a = null;
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_constant_null_a_nullable()
{
dynamic b = new D();
int? a = null;
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_constant_not_null_a_nullable()
{
dynamic b = new D();
int? a = 10;
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_not_null_a()
{
dynamic b = new D();
D a = new E();
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_not_null_a_nullable(int? c)
{
dynamic b = new D();
int? a = c;
dynamic z = a ?? b;
return z;
}
}
";
var compilation = CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(541147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541147")]
[Fact]
public void TestNullCoalesceWithMethodGroup()
{
var source = @"
using System;
static class Program
{
static void Main()
{
Action a = Main ?? Main;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main ?? Main").WithArguments("??", "method group", "method group"));
}
[WorkItem(541149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541149")]
[Fact]
public void TestNullCoalesceWithLambda()
{
var source = @"
using System;
static class Program
{
static void Main()
{
const Action<int> a = null;
var b = a ?? (() => { });
}
}
";
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? (() => { })").WithArguments("??", "System.Action<int>", "lambda expression"));
}
[WorkItem(541148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541148")]
[Fact]
public void TestNullCoalesceWithConstNonNullExpression()
{
var source = @"
using System;
static class Program
{
static void Main()
{
const string x = ""A"";
string y;
string z = x ?? y;
Console.WriteLine(z);
}
}
";
CompileAndVerify(source, expectedOutput: "A");
}
[WorkItem(545631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545631")]
[Fact]
public void TestNullCoalesceWithInvalidUserDefinedConversions_01()
{
var source = @"
class B
{
static void Main()
{
A a = null;
B b = null;
var c = a ?? b;
}
public static implicit operator A(B x)
{
return new A();
}
}
class A
{
public static implicit operator A(B x)
{
return new A();
}
public static implicit operator B(A x)
{
return new B();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,22): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A'
// var c = a ?? b;
Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A"));
}
[WorkItem(545631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545631")]
[Fact]
public void TestNullCoalesceWithInvalidUserDefinedConversions_02()
{
var source = @"
struct B
{
static void Main()
{
A? a = null;
B b;
var c = a ?? b;
}
public static implicit operator A(B x)
{
return new A();
}
}
struct A
{
public static implicit operator A(B x)
{
return new A();
}
public static implicit operator B(A x)
{
return new B();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,22): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A'
// var c = a ?? b;
Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A"));
}
[WorkItem(545631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545631")]
[Fact]
public void TestNullCoalesceWithInvalidUserDefinedConversions_03()
{
var source = @"
struct B
{
static void Main()
{
A a2;
B? b2 = null;
var c2 = b2 ?? a2;
}
public static implicit operator A(B x)
{
return new A();
}
}
struct A
{
public static implicit operator A(B x)
{
return new A();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,18): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A'
// var c2 = b2 ?? a2;
Diagnostic(ErrorCode.ERR_AmbigUDConv, "b2").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A"));
}
[WorkItem(541343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541343")]
[Fact]
public void TestAsOperator_Bug8014()
{
var source = @"
using System;
class Program
{
static void Main()
{
object y = null as object ?? null;
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty);
}
[WorkItem(542090, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542090")]
[Fact]
public void TestAsOperatorWithImplicitConversion()
{
var source = @"
using System;
class Program
{
static void Main()
{
object o = 5 as object;
string s = ""str"" as string;
s = null as string;
}
}
";
CompileAndVerify(source, expectedOutput: "");
}
[Fact]
public void TestDefaultOperator_ConstantDateTime()
{
var source = @"
using System;
namespace N2
{
class X
{
public static void Main()
{
}
public static DateTime Goo()
{
return default(DateTime);
}
}
}";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestDefaultOperator_Dynamic()
{
// "default(dynamic)" has constant value null.
var source = @"
using System;
public class X
{
public static void Main()
{
const object obj = default(dynamic);
Console.Write(obj == null);
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "True"); ;
source = @"
using System;
public class C<T> { }
public class X
{
public X(dynamic param = default(dynamic)) { Console.WriteLine(param == null); }
public static void Main()
{
Console.Write(default(dynamic));
Console.Write(default(C<dynamic>));
Console.WriteLine(default(dynamic) == null);
Console.WriteLine(default(C<dynamic>) == null);
object x = default(dynamic);
Console.WriteLine(x == null);
var unused = new X();
}
}";
comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics();
// "default(dynamic)" has type dynamic
source = @"
public class X
{
public X(object param = default(dynamic)) {}
}";
comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (4,21): error CS1750: A value of type 'dynamic' cannot be used as a default parameter because there are no standard conversions to type 'object'
// public X(object param = default(dynamic)) {}
Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "param").WithArguments("dynamic", "object"));
}
[WorkItem(537876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537876")]
[Fact]
public void TestEnumOrAssign()
{
var source = @"
enum F
{
A,
B,
C
}
class Program
{
static void Main(string[] args)
{
F x = F.A;
x |= F.B;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[WorkItem(542072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542072")]
[Fact]
public void TestEnumLogicalWithLiteralZero_9042()
{
var source = @"
enum F { A }
class Program
{
static void Main()
{
M(F.A | 0);
M(0 | F.A);
M(F.A & 0);
M(0 & F.A);
M(F.A ^ 0);
M(0 ^ F.A);
}
static void M(F f) {}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[WorkItem(542073, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542073")]
[Fact]
public void TestEnumCompoundAddition_9043()
{
var source = @"
enum F { A, B }
class Program
{
static void Main()
{
F f = F.A;
f += 1;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[WorkItem(542086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542086")]
[Fact]
public void TestStringCompoundAddition_9146()
{
var source = @"
class Test
{
public static void Main()
{
int i = 0;
string s = ""i="";
s += i;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestOpTrueInBooleanExpression()
{
var source = @"
class Program
{
struct C
{
public int x;
public static bool operator true(C c) { return c.x != 0; }
public static bool operator false(C c) { return c.x == 0; }
public static bool operator true(C? c) { return c.HasValue && c.Value.x != 0; }
public static bool operator false(C? c) { return c.HasValue && c.Value.x == 0; }
}
static void Main()
{
C c = new C();
c.x = 1;
if (c)
{
System.Console.WriteLine(1);
}
while(c)
{
System.Console.WriteLine(2);
c.x--;
}
for(c.x = 1; c; c.x--)
System.Console.WriteLine(3);
c.x = 1;
do
{
System.Console.WriteLine(4);
c.x--;
}
while(c);
System.Console.WriteLine(c ? 6 : 5);
C? c2 = c;
System.Console.WriteLine(c2 ? 7 : 8);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestOpTrueInBooleanExpressionError()
{
// operator true does not lift to nullable.
var source = @"
class Program
{
struct C
{
public int x;
public static bool operator true(C c) { return c.x != 0; }
public static bool operator false(C c) { return c.x == 0; }
}
static void Main()
{
C? c = new C();
if (c)
{
System.Console.WriteLine(1);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (14,13): error CS0029: Cannot implicitly convert type 'Program.C?' to 'bool'
// if (c)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c").WithArguments("Program.C?", "bool"),
// (6,20): warning CS0649: Field 'Program.C.x' is never assigned to, and will always have its default value 0
// public int x;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Program.C.x", "0")
);
}
[WorkItem(543294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543294")]
[Fact()]
public void TestAsOperatorWithTypeParameter()
{
// SPEC: Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs:
// SPEC: - An identity (�6.1.1), implicit nullable (�6.1.4), implicit reference (�6.1.6), boxing (�6.1.7),
// SPEC: explicit nullable (�6.2.3), explicit reference (�6.2.4), or unboxing (�6.2.5) conversion exists
// SPEC: from E to T.
// SPEC: - The type of E or T is an open type.
// SPEC: - E is the null literal.
// SPEC VIOLATION: The specification unintentionally allows the case where requirement 2 above:
// SPEC VIOLATION: "The type of E or T is an open type" is true, but type of E is void type, i.e. T is an open type.
// SPEC VIOLATION: Dev10 compiler correctly generates an error for this case and we will maintain compatibility.
var source = @"
using System;
class Program
{
static void Main()
{
Goo<Action>();
}
static void Goo<T>() where T : class
{
object o = Main() as T;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (13,20): error CS0039: Cannot convert type 'void' to 'T' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
// object o = Main() as T;
Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "Main() as T").WithArguments("void", "T"));
}
[WorkItem(543294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543294")]
[Fact()]
public void TestIsOperatorWithTypeParameter_01()
{
var source = @"
using System;
class Program
{
static void Main()
{
Goo<Action>();
}
static void Goo<T>() where T : class
{
bool b = Main() is T;
}
}
";
// NOTE: Dev10 violates the SPEC for this test case and generates
// NOTE: an error ERR_NoExplicitBuiltinConv if the target type
// NOTE: is an open type. According to the specification, the result
// NOTE: is always false, but no compile time error occurs.
// NOTE: We follow the specification and generate WRN_IsAlwaysFalse
// NOTE: instead of an error.
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (13,18): warning CS0184: The given expression is never of the provided ('T') type
// bool b = Main() is T;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "Main() is T").WithArguments("T"));
}
[Fact]
[WorkItem(34679, "https://github.com/dotnet/roslyn/issues/34679")]
public void TestIsOperatorWithTypeParameter_02()
{
var source = @"
class A<T>
{
public virtual void M1<S>(S x) where S : T { }
}
class C : A<int?>
{
static void Main()
{
var x = new C();
int? y = null;
x.M1(y);
x.Test(y);
y = 0;
x.M1(y);
x.Test(y);
}
void Test(int? x)
{
if (x is System.ValueType)
{
System.Console.WriteLine(""Test if"");
}
else
{
System.Console.WriteLine(""Test else"");
}
}
public override void M1<S>(S x)
{
if (x is System.ValueType)
{
System.Console.WriteLine(""M1 if"");
}
else
{
System.Console.WriteLine(""M1 else"");
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput:
@"M1 else
Test else
M1 if
Test if");
}
[WorkItem(844635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844635")]
[Fact()]
public void TestIsOperatorWithGenericContainingType()
{
var source = @"
class Program
{
static void Goo<T>(
Outer<T>.C c1, Outer<int>.C c2,
Outer<T>.S s1, Outer<int>.S s2,
Outer<T>.E e1, Outer<int>.E e2)
{
bool b;
b = c1 is Outer<T>.C; // Deferred to runtime - null check.
b = c1 is Outer<int>.C; // Deferred to runtime - null check.
b = c1 is Outer<long>.C; // Deferred to runtime - null check.
b = c2 is Outer<T>.C; // Deferred to runtime - null check.
b = c2 is Outer<int>.C; // Deferred to runtime - null check.
b = c2 is Outer<long>.C; // Always false.
b = s1 is Outer<T>.S; // Always true.
b = s1 is Outer<int>.S; // Deferred to runtime - type unification.
b = s1 is Outer<long>.S; // Deferred to runtime - type unification.
b = s2 is Outer<T>.S; // Deferred to runtime - type unification.
b = s2 is Outer<int>.S; // Always true.
b = s2 is Outer<long>.S; // Always false.
b = e1 is Outer<T>.E; // Always true.
b = e1 is Outer<int>.E; // Deferred to runtime - type unification.
b = e1 is Outer<long>.E; // Deferred to runtime - type unification.
b = e2 is Outer<T>.E; // Deferred to runtime - type unification.
b = e2 is Outer<int>.E; // Always true.
b = e2 is Outer<long>.E; // Always false.
}
}
class Outer<T>
{
public class C { }
public struct S { }
public enum E { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (16,13): warning CS0184: The given expression is never of the provided ('Outer<long>.C') type
// b = c2 is Outer<long>.C; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "c2 is Outer<long>.C").WithArguments("Outer<long>.C").WithLocation(16, 13),
// (18,13): warning CS0183: The given expression is always of the provided ('Outer<T>.S') type
// b = s1 is Outer<T>.S; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "s1 is Outer<T>.S").WithArguments("Outer<T>.S").WithLocation(18, 13),
// (23,13): warning CS0183: The given expression is always of the provided ('Outer<int>.S') type
// b = s2 is Outer<int>.S; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "s2 is Outer<int>.S").WithArguments("Outer<int>.S").WithLocation(23, 13),
// (24,13): warning CS0184: The given expression is never of the provided ('Outer<long>.S') type
// b = s2 is Outer<long>.S; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "s2 is Outer<long>.S").WithArguments("Outer<long>.S").WithLocation(24, 13),
// (26,13): warning CS0183: The given expression is always of the provided ('Outer<T>.E') type
// b = e1 is Outer<T>.E; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is Outer<T>.E").WithArguments("Outer<T>.E").WithLocation(26, 13),
// (31,13): warning CS0183: The given expression is always of the provided ('Outer<int>.E') type
// b = e2 is Outer<int>.E; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is Outer<int>.E").WithArguments("Outer<int>.E").WithLocation(31, 13),
// (32,13): warning CS0184: The given expression is never of the provided ('Outer<long>.E') type
// b = e2 is Outer<long>.E; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "e2 is Outer<long>.E").WithArguments("Outer<long>.E").WithLocation(32, 13));
}
[Fact]
public void TestIsOperatorWithGenericClassAndValueType()
{
var source = @"
class Program
{
static bool Goo<T>(C<T> c)
{
return c is int; // always false
}
}
class C<T> { }
";
CreateCompilation(source).VerifyDiagnostics(
// (6,16): warning CS0184: The given expression is never of the provided ('int') type
// return c is int; // always false
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "c is int").WithArguments("int").WithLocation(6, 16)
);
}
[WorkItem(844635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844635")]
[Fact()]
public void TestIsOperatorWithTypesThatCannotUnify()
{
var source = @"
class Program
{
static void Goo<T>(Outer<T>.S s1, Outer<T[]>.S s2)
{
bool b;
b = s1 is Outer<int[]>.S; // T -> int[]
b = s1 is Outer<T[]>.S; // Cannot unify - as in dev12, we do not warn.
b = s2 is Outer<int[]>.S; // T -> int
b = s2 is Outer<T[]>.S; // Always true.
b = s2 is Outer<T[,]>.S; // Cannot unify - as in dev12, we do not warn.
}
}
class Outer<T>
{
public struct S { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (11,13): warning CS0183: The given expression is always of the provided ('Outer<T[]>.S') type
// b = s2 is Outer<T[]>.S; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "s2 is Outer<T[]>.S").WithArguments("Outer<T[]>.S").WithLocation(11, 13));
}
[WorkItem(844635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844635")]
[Fact()]
public void TestIsOperatorWithSpecialTypes()
{
var source = @"
using System;
class Program
{
static void Goo<T, TClass, TStruct>(Outer<T>.E e1, Outer<int>.E e2, int i, T t, TClass tc, TStruct ts)
where TClass : class
where TStruct : struct
{
bool b;
b = e1 is Enum; // Always true.
b = e2 is Enum; // Always true.
b = 0 is Enum; // Always false.
b = i is Enum; // Always false.
b = t is Enum; // Deferred.
b = tc is Enum; // Deferred.
b = ts is Enum; // Deferred.
b = e1 is ValueType; // Always true.
b = e2 is ValueType; // Always true.
b = 0 is ValueType; // Always true.
b = i is ValueType; // Always true.
b = t is ValueType; // Deferred - null check.
b = tc is ValueType; // Deferred - null check.
b = ts is ValueType; // Always true.
b = e1 is Object; // Always true.
b = e2 is Object; // Always true.
b = 0 is Object; // Always true.
b = i is Object; // Always true.
b = t is Object; // Deferred - null check.
b = tc is Object; // Deferred - null check.
b = ts is Object; // Always true.
}
}
class Outer<T>
{
public enum E { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (11,13): warning CS0183: The given expression is always of the provided ('System.Enum') type
// b = e1 is Enum; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is Enum").WithArguments("System.Enum").WithLocation(11, 13),
// (12,13): warning CS0183: The given expression is always of the provided ('System.Enum') type
// b = e2 is Enum; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is Enum").WithArguments("System.Enum").WithLocation(12, 13),
// (13,13): warning CS0184: The given expression is never of the provided ('System.Enum') type
// b = 0 is Enum; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "0 is Enum").WithArguments("System.Enum").WithLocation(13, 13),
// (14,13): warning CS0184: The given expression is never of the provided ('System.Enum') type
// b = i is Enum; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "i is Enum").WithArguments("System.Enum").WithLocation(14, 13),
// (19,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = e1 is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is ValueType").WithArguments("System.ValueType").WithLocation(19, 13),
// (20,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = e2 is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is ValueType").WithArguments("System.ValueType").WithLocation(20, 13),
// (21,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = 0 is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "0 is ValueType").WithArguments("System.ValueType").WithLocation(21, 13),
// (22,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = i is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "i is ValueType").WithArguments("System.ValueType").WithLocation(22, 13),
// (25,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = ts is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "ts is ValueType").WithArguments("System.ValueType").WithLocation(25, 13),
// (27,13): warning CS0183: The given expression is always of the provided ('object') type
// b = e1 is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is Object").WithArguments("object").WithLocation(27, 13),
// (28,13): warning CS0183: The given expression is always of the provided ('object') type
// b = e2 is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is Object").WithArguments("object").WithLocation(28, 13),
// (29,13): warning CS0183: The given expression is always of the provided ('object') type
// b = 0 is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "0 is Object").WithArguments("object").WithLocation(29, 13),
// (30,13): warning CS0183: The given expression is always of the provided ('object') type
// b = i is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "i is Object").WithArguments("object").WithLocation(30, 13),
// (33,13): warning CS0183: The given expression is always of the provided ('object') type
// b = ts is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "ts is Object").WithArguments("object").WithLocation(33, 13));
}
[WorkItem(543294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543294"), WorkItem(546655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546655")]
[Fact()]
public void TestAsOperator_SpecErrorCase()
{
// SPEC: Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs:
// SPEC: - An identity (�6.1.1), implicit nullable (�6.1.4), implicit reference (�6.1.6), boxing (�6.1.7),
// SPEC: explicit nullable (�6.2.3), explicit reference (�6.2.4), or unboxing (�6.2.5) conversion exists
// SPEC: from E to T.
// SPEC: - The type of E or T is an open type.
// SPEC: - E is the null literal.
// SPEC VIOLATION: The specification contains an error in the list of legal conversions above.
// SPEC VIOLATION: If we have "class C<T, U> where T : U where U : class" then there is
// SPEC VIOLATION: an implicit conversion from T to U, but it is not an identity, reference or
// SPEC VIOLATION: boxing conversion. It will be one of those at runtime, but at compile time
// SPEC VIOLATION: we do not know which, and therefore cannot classify it as any of those.
var source = @"
using System;
class Program
{
static void Main()
{
Goo<Action, Action>(null);
}
static U Goo<T, U>(T t)
where T : U
where U : class
{
var s = t is U;
return t as U;
}
}
";
CompileAndVerify(source, expectedOutput: "").VerifyDiagnostics();
}
[WorkItem(546655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546655")]
[Fact()]
public void TestIsOperatorWithTypeParameter_Bug16461()
{
var source = @"
using System;
public class G<T>
{
public bool M(T t) { return t is object; }
}
public class GG<T, V> where T : V
{
public bool M(T t) { return t is V; }
}
class Test
{
static void Main()
{
var obj = new G<Test>();
Console.WriteLine(obj.M( (Test)null ));
var obj1 = new GG<Test, Test>();
Console.WriteLine(obj1.M( (Test)null ));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
False");
comp.VerifyDiagnostics();
}
[Fact()]
public void TestIsAsOperator_UserDefinedConversionsNotAllowed()
{
var source = @"
// conversion.cs
class Goo { public Goo(Bar b){} }
class Goo2 { public Goo2(Bar b){} }
struct Bar
{
// Declare an implicit conversion from a int to a Bar
static public implicit operator Bar(int value)
{
return new Bar();
}
// Declare an explicit conversion from a Bar to Goo
static public explicit operator Goo(Bar value)
{
return new Goo(value);
}
// Declare an implicit conversion from a Bar to Goo2
static public implicit operator Goo2(Bar value)
{
return new Goo2(value);
}
}
class Test
{
static public void Main()
{
Bar numeral;
numeral = 10;
object a1 = numeral as Goo;
object a2 = 1 as Bar;
object a3 = numeral as Goo2;
bool b1 = numeral is Goo;
bool b2 = 1 is Bar;
bool b3 = numeral is Goo2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (37,21): error CS0039: Cannot convert type 'Bar' to 'Goo' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
// object a1 = numeral as Goo;
Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "numeral as Goo").WithArguments("Bar", "Goo"),
// (38,21): error CS0077: The as operator must be used with a reference type or nullable type ('Bar' is a non-nullable value type)
// object a2 = 1 as Bar;
Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, "1 as Bar").WithArguments("Bar"),
// (39,21): error CS0039: Cannot convert type 'Bar' to 'Goo2' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
// object a3 = numeral as Goo2;
Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "numeral as Goo2").WithArguments("Bar", "Goo2"),
// (41,19): warning CS0184: The given expression is never of the provided ('Goo') type
// bool b1 = numeral is Goo;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "numeral is Goo").WithArguments("Goo"),
// (42,19): warning CS0184: The given expression is never of the provided ('Bar') type
// bool b2 = 1 is Bar;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is Bar").WithArguments("Bar"),
// (43,19): warning CS0184: The given expression is never of the provided ('Goo2') type
// bool b3 = numeral is Goo2;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "numeral is Goo2").WithArguments("Goo2"));
}
[WorkItem(543455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543455")]
[Fact()]
public void CS0184WRN_IsAlwaysFalse_Generic()
{
var text = @"
public class GenC<T> : GenI<T> where T : struct
{
public bool Test(T t)
{
return (t is C);
}
}
public interface GenI<T>
{
bool Test(T t);
}
public class C
{
public void Method() { }
public static int Main()
{
return 0;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "t is C").WithArguments("C"));
}
[WorkItem(547011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547011")]
[Fact()]
public void CS0184WRN_IsAlwaysFalse_IntPtr()
{
var text = @"using System;
public enum E
{
First
}
public class Base
{
public static void Main()
{
E e = E.First;
Console.WriteLine(e is IntPtr);
Console.WriteLine(e as IntPtr);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (12,27): warning CS0184: The given expression is never of the provided ('System.IntPtr') type
// Console.WriteLine(e is IntPtr);
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "e is IntPtr").WithArguments("System.IntPtr"),
// (13,27): error CS0077: The as operator must be used with a reference type or nullable type ('System.IntPtr' is a non-nullable value type)
// Console.WriteLine(e as IntPtr);
Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, "e as IntPtr").WithArguments("System.IntPtr"));
}
[WorkItem(543443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543443")]
[Fact]
public void ParamsOperators()
{
var text =
@"class X
{
public static bool operator >(X a, params int[] b)
{
return true;
}
public static bool operator <(X a, params int[] b)
{
return false;
}
}";
CreateCompilation(text).VerifyDiagnostics(
// (3,39): error CS1670: params is not valid in this context public static bool operator >(X a, params int[] b)
Diagnostic(ErrorCode.ERR_IllegalParams, "params"),
// (8,40): error CS1670: params is not valid in this context
// public static bool operator <(X a, params int[] b)
Diagnostic(ErrorCode.ERR_IllegalParams, "params")
);
}
[WorkItem(543438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543438")]
[Fact()]
public void TestNullCoalesce_UserDefinedConversions()
{
var text =
@"class B
{
static void Main()
{
A a = null;
B b = null;
var c = a ?? b;
}
}
class A
{
public static implicit operator B(A x)
{
return new B();
}
}";
CompileAndVerify(text);
}
[WorkItem(543503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543503")]
[Fact()]
public void TestAsOperator_UserDefinedConversions()
{
var text =
@"using System;
class C<T>
{
public static implicit operator string (C<T> x)
{
return """";
}
string s = new C<T>() as string;
}";
CompileAndVerify(text);
}
[WorkItem(543503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543503")]
[Fact()]
public void TestIsOperator_UserDefinedConversions()
{
var text =
@"using System;
class C<T>
{
public static implicit operator string (C<T> x)
{
return """";
}
bool b = new C<T>() is string;
}";
CompileAndVerify(text);
}
[WorkItem(543483, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543483")]
[Fact]
public void TestEqualityOperator_NullableStructs()
{
string source1 =
@"
public struct NonGenericStruct { }
public struct GenericStruct<T> { }
public class Goo
{
public NonGenericStruct? ngsq;
public GenericStruct<int>? gsiq;
}
public class GenGoo<T>
{
public GenericStruct<T>? gstq;
}
public class Test
{
public static bool Run()
{
Goo f = new Goo();
f.ngsq = new NonGenericStruct();
f.gsiq = new GenericStruct<int>();
GenGoo<int> gf = new GenGoo<int>();
gf.gstq = new GenericStruct<int>();
return (f.ngsq != null) && (f.gsiq != null) && (gf.gstq != null);
}
public static void Main()
{
System.Console.WriteLine(Run() ? 1 : 0);
}
}";
string source2 = @"
struct S
{
public static bool operator ==(S? x, decimal? y) { return false; }
public static bool operator !=(S? x, decimal? y) { return false; }
public static bool operator ==(S? x, double? y) { return false; }
public static bool operator !=(S? x, double? y) { return false; }
public override int GetHashCode() { return 0; }
public override bool Equals(object x) { return false; }
static void Main()
{
S? s = default(S?);
// This is *not* equivalent to !s.HasValue because
// there is an applicable user-defined conversion.
// Even though the conversion is ambiguous!
if (s == null) s = default(S);
}
}
";
CompileAndVerify(source1, expectedOutput: "1");
CreateCompilation(source2).VerifyDiagnostics(
// (16,9): error CS0034: Operator '==' is ambiguous on operands of type 'S?' and '<null>'
// if (s == null) s = default(S);
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "s == null").WithArguments("==", "S?", "<null>"));
}
[WorkItem(543432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543432")]
[Fact]
public void NoNewForOperators()
{
var text =
@"class A
{
public static implicit operator A(D x)
{
return null;
}
}
class B : A
{
public static implicit operator B(D x)
{
return null;
}
}
class D {}";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact(), WorkItem(543433, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543433")]
public void ERR_NoImplicitConvCast_UserDefinedConversions()
{
var text =
@"class A
{
public static A operator ++(A x)
{
return new A();
}
}
class B : A
{
static void Main()
{
B b = new B();
b++;
}
}
";
CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b++").WithArguments("A", "B"));
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleOperatorIncrement()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static (T1 fst, T2 snd) operator ++((T1 one, T2 two) tuple)
{
return tuple;
}
}
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleOperatorConvert()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static explicit operator (T1 fst, T2 snd)((T1 one, T2 two) s)
{
return s;
}
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,41): error CS0555: User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type
// public static explicit operator (T1 fst, T2 snd)((T1 one, T2 two) s)
Diagnostic(ErrorCode.ERR_IdentityConversion, "(T1 fst, T2 snd)").WithLocation(6, 41));
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleOperatorConvertToBaseType()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static explicit operator ValueType(ValueTuple<T1, T2> s)
{
return s;
}
}
}
";
CreateCompilation(text).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify(
// (6,41): error CS0553: 'ValueTuple<T1, T2>.explicit operator ValueType((T1, T2))': user-defined conversions to or from a base class are not allowed
// public static explicit operator ValueType(ValueTuple<T1, T2> s)
Diagnostic(ErrorCode.ERR_ConversionWithBase, "ValueType").WithArguments("System.ValueTuple<T1, T2>.explicit operator System.ValueType((T1, T2))").WithLocation(6, 41));
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleBinaryOperator()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static ValueTuple<T1, T2> operator +((T1 fst, T2 snd) s1, (T1 one, T2 two) s2)
{
return s1;
}
}
}
";
CreateCompilation(text).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_01()
{
string source =
@"
using System;
class C
{
public static implicit operator Func<int>(C x)
{
return null;
}
}
class D
{
public static implicit operator Action(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((C)null == (D)null);
Console.WriteLine((C)null != (D)null);
}
}
";
string expectedOutput = @"True
False";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_02()
{
string source =
@"
using System;
class C
{
public static implicit operator Func<int>(C x)
{
return null;
}
}
class D
{
public static implicit operator Action(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((Func<int>)(C)null == (D)null);
Console.WriteLine((Func<int>)(C)null == (Action)(D)null);
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (21,27): error CS0019: Operator '==' cannot be applied to operands of type 'System.Func<int>' and 'D'
// Console.WriteLine((Func<int>)(C)null == (D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(Func<int>)(C)null == (D)null").WithArguments("==", "System.Func<int>", "D"),
// (22,27): error CS0019: Operator '==' cannot be applied to operands of type 'System.Func<int>' and 'System.Action'
// Console.WriteLine((Func<int>)(C)null == (Action)(D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(Func<int>)(C)null == (Action)(D)null").WithArguments("==", "System.Func<int>", "System.Action"));
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_03_Ambiguous()
{
string source =
@"
using System;
class C
{
public static implicit operator Func<int>(C x)
{
return null;
}
}
class D
{
public static implicit operator Action(D x)
{
return null;
}
public static implicit operator Func<int>(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((C)null == (D)null);
Console.WriteLine((C)null != (D)null);
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (26,27): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'D'
// Console.WriteLine((C)null == (D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(C)null == (D)null").WithArguments("==", "C", "D"),
// (27,27): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'D'
// Console.WriteLine((C)null != (D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(C)null != (D)null").WithArguments("!=", "C", "D"));
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_04_BaseTypes()
{
string source =
@"
using System;
class A
{
public static implicit operator Func<int>(A x)
{
return null;
}
}
class C : A
{
}
class D
{
public static implicit operator Func<int>(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((C)null == (D)null);
Console.WriteLine((C)null != (D)null);
}
}
";
string expectedOutput = @"True
False";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[WorkItem(543754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543754")]
[Fact]
public void TestEqualityOperator_NullableDecimal()
{
string source =
@"
public class Test
{
public static bool Goo(decimal? deq)
{
return deq == null;
}
public static void Main()
{
Goo(null);
}
}
";
CompileAndVerify(source, expectedOutput: "");
}
[WorkItem(543910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543910")]
[Fact]
public void TypeParameterConstraintToGenericType()
{
string source =
@"
public class Gen<T>
{
public T t;
public Gen(T t)
{
this.t = t;
}
public static Gen<T> operator + (Gen<T> x, T y)
{
return new Gen<T>(y);
}
}
public class ConstrainedTestContext<T,U> where T : Gen<U>
{
public static Gen<U> ExecuteOpAddition(T x, U y)
{
return x + y;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(544490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544490")]
[Fact]
public void LiftedUserDefinedUnaryOperator()
{
string source =
@"
struct S
{
public static int operator +(S s) { return 1; }
public static void Main()
{
S s = new S();
S? sq = s;
var j = +sq;
System.Console.WriteLine(j);
}
}
";
CompileAndVerify(source, expectedOutput: "1");
}
[WorkItem(544490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544490")]
[Fact]
public void TestDefaultOperatorEnumConstantValue()
{
string source =
@"
enum X { F = 0 };
class C
{
public static int Main()
{
const X x = default(X);
return (int)x;
}
}
";
CompileAndVerify(source, expectedOutput: "");
}
[Fact]
public void OperatorHiding1()
{
string source = @"
class Base1
{
public static Base1 operator +(Base1 b, Derived1 d) { return b; }
}
class Derived1 : Base1
{
public static Base1 operator +(Base1 b, Derived1 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void OperatorHiding2()
{
string source = @"
class Base2
{
public static Base2 op_Addition(Base2 b, Derived2 d) { return b; }
}
class Derived2 : Base2
{
public static Base2 operator +(Base2 b, Derived2 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void OperatorHiding3()
{
string source = @"
class Base3
{
public static Base3 operator +(Base3 b, Derived3 d) { return b; }
}
class Derived3 : Base3
{
public static Base3 op_Addition(Base3 b, Derived3 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void OperatorHiding4()
{
string source = @"
class Base4
{
public static Base4 op_Addition(Base4 b, Derived4 d) { return b; }
}
class Derived4 : Base4
{
public static Base4 op_Addition(Base4 b, Derived4 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,25): warning CS0108: 'Derived4.op_Addition(Base4, Derived4)' hides inherited member 'Base4.op_Addition(Base4, Derived4)'. Use the new keyword if hiding was intended.
// public static Base4 op_Addition(Base4 b, Derived4 d) { return b; }
Diagnostic(ErrorCode.WRN_NewRequired, "op_Addition").WithArguments("Derived4.op_Addition(Base4, Derived4)", "Base4.op_Addition(Base4, Derived4)"));
}
[Fact]
public void ConversionHiding1()
{
string source = @"
class Base1
{
public static implicit operator string(Base1 b) { return null; }
}
class Derived1 : Base1
{
public static implicit operator string(Base1 b) { return null; } // CS0556, but not CS0108
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,37): error CS0556: User-defined conversion must convert to or from the enclosing type
// public static implicit operator string(Base1 b) { return null; }
Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "string"));
}
[Fact]
public void ConversionHiding2()
{
string source = @"
class Base2
{
public static string op_Explicit(Derived2 d) { return null; }
}
class Derived2 : Base2
{
public static implicit operator string(Derived2 d) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void ConversionHiding3()
{
string source = @"
class Base3
{
public static implicit operator string(Base3 b) { return null; }
}
class Derived3 : Base3
{
public static string op_Explicit(Base3 b) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void ConversionHiding4()
{
string source = @"
class Base4
{
public static string op_Explicit(Base4 b) { return null; }
}
class Derived4 : Base4
{
public static string op_Explicit(Base4 b) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,26): warning CS0108: 'Derived4.op_Explicit(Base4)' hides inherited member 'Base4.op_Explicit(Base4)'. Use the new keyword if hiding was intended.
// public static string op_Explicit(Base4 b) { return null; }
Diagnostic(ErrorCode.WRN_NewRequired, "op_Explicit").WithArguments("Derived4.op_Explicit(Base4)", "Base4.op_Explicit(Base4)"));
}
[Fact]
public void ClassesWithOperatorNames()
{
string source = @"
class op_Increment
{
public static op_Increment operator ++ (op_Increment c) { return null; }
}
class op_Decrement
{
public static op_Decrement operator -- (op_Decrement c) { return null; }
}
class op_UnaryPlus
{
public static int operator + (op_UnaryPlus c) { return 0; }
}
class op_UnaryNegation
{
public static int operator - (op_UnaryNegation c) { return 0; }
}
class op_OnesComplement
{
public static int operator ~ (op_OnesComplement c) { return 0; }
}
class op_Addition
{
public static int operator + (op_Addition c, int i) { return 0; }
}
class op_Subtraction
{
public static int operator - (op_Subtraction c, int i) { return 0; }
}
class op_Multiply
{
public static int operator * (op_Multiply c, int i) { return 0; }
}
class op_Division
{
public static int operator / (op_Division c, int i) { return 0; }
}
class op_Modulus
{
public static int operator % (op_Modulus c, int i) { return 0; }
}
class op_ExclusiveOr
{
public static int operator ^ (op_ExclusiveOr c, int i) { return 0; }
}
class op_BitwiseAnd
{
public static int operator & (op_BitwiseAnd c, int i) { return 0; }
}
class op_BitwiseOr
{
public static int operator | (op_BitwiseOr c, int i) { return 0; }
}
class op_LeftShift
{
public static long operator << (op_LeftShift c, int i) { return 0; }
}
class op_RightShift
{
public static long operator >> (op_RightShift c, int i) { return 0; }
}
class op_UnsignedRightShift
{
}
";
CreateCompilation(source).VerifyDiagnostics(
// (4,38): error CS0542: 'op_Increment': member names cannot be the same as their enclosing type
// public static op_Increment operator ++ (op_Increment c) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "++").WithArguments("op_Increment"),
// (8,38): error CS0542: 'op_Decrement': member names cannot be the same as their enclosing type
// public static op_Decrement operator -- (op_Decrement c) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "--").WithArguments("op_Decrement"),
// (12,29): error CS0542: 'op_UnaryPlus': member names cannot be the same as their enclosing type
// public static int operator + (op_UnaryPlus c) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "+").WithArguments("op_UnaryPlus"),
// (16,39): error CS0542: 'op_UnaryNegation': member names cannot be the same as their enclosing type
// public static int operator - (op_UnaryNegation c) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "-").WithArguments("op_UnaryNegation"),
// (20,29): error CS0542: 'op_OnesComplement': member names cannot be the same as their enclosing type
// public static int operator ~ (op_OnesComplement c) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "~").WithArguments("op_OnesComplement"),
// (24,29): error CS0542: 'op_Addition': member names cannot be the same as their enclosing type
// public static int operator + (op_Addition c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "+").WithArguments("op_Addition"),
// (28,29): error CS0542: 'op_Subtraction': member names cannot be the same as their enclosing type
// public static int operator - (op_Subtraction c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "-").WithArguments("op_Subtraction"),
// (32,29): error CS0542: 'op_Multiply': member names cannot be the same as their enclosing type
// public static int operator * (op_Multiply c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "*").WithArguments("op_Multiply"),
// (36,29): error CS0542: 'op_Division': member names cannot be the same as their enclosing type
// public static int operator / (op_Division c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "/").WithArguments("op_Division"),
// (40,29): error CS0542: 'op_Modulus': member names cannot be the same as their enclosing type
// public static int operator % (op_Modulus c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "%").WithArguments("op_Modulus"),
// (44,29): error CS0542: 'op_ExclusiveOr': member names cannot be the same as their enclosing type
// public static int operator ^ (op_ExclusiveOr c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "^").WithArguments("op_ExclusiveOr"),
// (48,29): error CS0542: 'op_BitwiseAnd': member names cannot be the same as their enclosing type
// public static int operator & (op_BitwiseAnd c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "&").WithArguments("op_BitwiseAnd"),
// (52,29): error CS0542: 'op_BitwiseOr': member names cannot be the same as their enclosing type
// public static int operator | (op_BitwiseOr c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "|").WithArguments("op_BitwiseOr"),
// (56,30): error CS0542: 'op_LeftShift': member names cannot be the same as their enclosing type
// public static long operator << (op_LeftShift c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "<<").WithArguments("op_LeftShift"),
// (60,30): error CS0542: 'op_RightShift': member names cannot be the same as their enclosing type
// public static long operator >> (op_RightShift c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, ">>").WithArguments("op_RightShift"));
}
[Fact]
public void ClassesWithConversionNames()
{
string source = @"
class op_Explicit
{
public static explicit operator op_Explicit(int x) { return null; }
}
class op_Implicit
{
public static implicit operator op_Implicit(int x) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (4,37): error CS0542: 'op_Explicit': member names cannot be the same as their enclosing type
// public static explicit operator op_Explicit(int x) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "op_Explicit").WithArguments("op_Explicit"),
// (9,37): error CS0542: 'op_Implicit': member names cannot be the same as their enclosing type
// public static implicit operator op_Implicit(int x) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "op_Implicit").WithArguments("op_Implicit"));
}
[Fact, WorkItem(546771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546771")]
public void TestIsNullable_Bug16777()
{
string source = @"
class Program
{
enum E { }
static void Main()
{
M(null);
M(0);
}
static void M(E? e)
{
System.Console.Write(e is E ? 't' : 'f');
}
}
";
CompileAndVerify(source: source, expectedOutput: "ft");
}
[Fact]
public void CompoundOperatorWithThisOnLeft()
{
string source =
@"using System;
public struct Value
{
int value;
public Value(int value)
{
this.value = value;
}
public static Value operator +(Value a, int b)
{
return new Value(a.value + b);
}
public void Test()
{
this += 2;
}
public void Print()
{
Console.WriteLine(this.value);
}
public static void Main(string[] args)
{
Value v = new Value(1);
v.Test();
v.Print();
}
}";
string output = @"3";
CompileAndVerify(source: source, expectedOutput: output);
}
[WorkItem(631414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631414")]
[Fact]
public void LiftedUserDefinedEquality1()
{
string source = @"
struct S1
{
// Interesting
public static bool operator ==(S1 x, S1 y) { throw null; }
public static bool operator ==(S1 x, S2 y) { throw null; }
// Filler
public static bool operator !=(S1 x, S1 y) { throw null; }
public static bool operator !=(S1 x, S2 y) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
}
struct S2
{
}
class Program
{
bool Test(S1? s1)
{
return s1 == null;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var expectedOperator = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("S1").GetMembers(WellKnownMemberNames.EqualityOperatorName).
OfType<MethodSymbol>().Single(m => m.ParameterTypesWithAnnotations[0].Equals(m.ParameterTypesWithAnnotations[1], TypeCompareKind.ConsiderEverything));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
var info = model.GetSymbolInfo(syntax);
Assert.Equal(expectedOperator.GetPublicSymbol(), info.Symbol);
}
[WorkItem(631414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631414")]
[Fact]
public void LiftedUserDefinedEquality2()
{
string source = @"
using System;
struct S1
{
// Interesting
[Obsolete(""A"")]
public static bool operator ==(S1 x, S1 y) { throw null; }
[Obsolete(""B"")]
public static bool operator ==(S1 x, S2 y) { throw null; }
// Filler
public static bool operator !=(S1 x, S1 y) { throw null; }
public static bool operator !=(S1 x, S2 y) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
}
struct S2
{
}
class Program
{
bool Test(S1? s1)
{
return s1 == null;
}
}
";
// CONSIDER: This is a little silly, since that method will never be called.
CreateCompilation(source).VerifyDiagnostics(
// (27,16): warning CS0618: 'S1.operator ==(S1, S1)' is obsolete: 'A'
// return s1 == null;
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "s1 == null").WithArguments("S1.operator ==(S1, S1)", "A"));
}
[WorkItem(631414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631414")]
[Fact]
public void LiftedUserDefinedEquality3()
{
string source = @"
struct S1
{
// Interesting
public static bool operator ==(S1 x, S2 y) { throw null; }
// Filler
public static bool operator !=(S1 x, S2 y) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
}
struct S2
{
}
class Program
{
bool Test(S1? s1, S2? s2)
{
return s1 == s2;
}
}
";
// CONSIDER: There is no reason not to allow this, but dev11 doesn't.
CreateCompilation(source).VerifyDiagnostics(
// (21,16): error CS0019: Operator '==' cannot be applied to operands of type 'S1?' and 'S2?'
// return s1 == s2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 == s2").WithArguments("==", "S1?", "S2?"));
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void AmbiguousLogicalOrConversion()
{
string source = @"
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
throw null;
}
public static implicit operator int(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
// SPEC VIOLATION: According to the spec, this is ambiguous. However, we will match the dev11 behavior.
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Last();
Assert.Equal("i2", syntax.Identifier.ValueText);
var info = model.GetTypeInfo(syntax);
Assert.Equal(comp.GlobalNamespace.GetMember<NamedTypeSymbol>("InputParameter"), info.Type.GetSymbol());
Assert.Equal(comp.GetSpecialType(SpecialType.System_Boolean), info.ConvertedType.GetSymbol());
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void AmbiguousOrConversion()
{
string source = @"
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
throw null;
}
public static implicit operator int(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 | i2;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (21,18): error CS0034: Operator '|' is ambiguous on operands of type 'InputParameter' and 'InputParameter'
// bool b = i1 | i2;
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "i1 | i2").WithArguments("|", "InputParameter", "InputParameter"));
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void DynamicAmbiguousLogicalOrConversion()
{
string source = @"
using System;
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
System.Console.WriteLine(""A"");
return true;
}
public static implicit operator int(InputParameter inputParameter)
{
System.Console.WriteLine(""B"");
return 1;
}
}
class Program
{
static void Main(string[] args)
{
dynamic i1 = new InputParameter();
dynamic i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: @"A
A");
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[ConditionalFact(typeof(DesktopOnly))]
public void DynamicAmbiguousOrConversion()
{
string source = @"
using System;
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
System.Console.WriteLine(""A"");
return true;
}
public static implicit operator int(InputParameter inputParameter)
{
System.Console.WriteLine(""B"");
return 1;
}
}
class Program
{
static void Main(string[] args)
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
dynamic i1 = new InputParameter();
dynamic i2 = new InputParameter();
bool b = i1 | i2;
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.ReleaseExe);
CompileAndVerifyException<Microsoft.CSharp.RuntimeBinder.RuntimeBinderException>(comp,
"Operator '|' is ambiguous on operands of type 'InputParameter' and 'InputParameter'");
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void UnambiguousLogicalOrConversion1()
{
string source = @"
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Last();
Assert.Equal("i2", syntax.Identifier.ValueText);
var info = model.GetTypeInfo(syntax);
Assert.Equal(comp.GlobalNamespace.GetMember<NamedTypeSymbol>("InputParameter").GetPublicSymbol(), info.Type);
Assert.Equal(comp.GetSpecialType(SpecialType.System_Boolean).GetPublicSymbol(), info.ConvertedType);
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void UnambiguousLogicalOrConversion2()
{
string source = @"
class InputParameter
{
public static implicit operator int(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (16,18): error CS0019: Operator '||' cannot be applied to operands of type 'InputParameter' and 'InputParameter'
// bool b = i1 || i2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i1 || i2").WithArguments("||", "InputParameter", "InputParameter"));
}
[WorkItem(665002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665002")]
[Fact]
public void DedupingLiftedUserDefinedOperators()
{
string source = @"
using System;
public class RubyTime
{
public static TimeSpan operator -(RubyTime x, DateTime y)
{
throw null;
}
public static TimeSpan operator -(RubyTime x, RubyTime y)
{
throw null;
}
public static implicit operator DateTime(RubyTime time)
{
throw null;
}
TimeSpan Test(RubyTime x, DateTime y)
{
return x - y;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact()]
public void UnaryIntrinsicSymbols1()
{
UnaryOperatorKind[] operators =
{
UnaryOperatorKind.PostfixIncrement,
UnaryOperatorKind.PostfixDecrement,
UnaryOperatorKind.PrefixIncrement,
UnaryOperatorKind.PrefixDecrement,
UnaryOperatorKind.UnaryPlus,
UnaryOperatorKind.UnaryMinus,
UnaryOperatorKind.LogicalNegation,
UnaryOperatorKind.BitwiseComplement
};
string[] opTokens = {"++","--","++","--",
"+","-","!","~"};
string[] typeNames =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid",
"dynamic",
"byte*"
};
var builder = new System.Text.StringBuilder();
int n = 0;
builder.Append(
"class Module1\n" +
"{\n");
foreach (var arg1 in typeNames)
{
n += 1;
builder.AppendFormat(
"void Test{1}({0} x1, System.Nullable<{0}> x2)\n", arg1, n);
builder.Append(
"{\n");
for (int k = 0; k < operators.Length; k++)
{
if (operators[k] == UnaryOperatorKind.PostfixDecrement || operators[k] == UnaryOperatorKind.PostfixIncrement)
{
builder.AppendFormat(
" var z{0}_1 = x1 {1};\n" +
" var z{0}_2 = x2 {1};\n" +
" if (x1 {1}) {{}}\n" +
" if (x2 {1}) {{}}\n",
k, opTokens[k]);
}
else
{
builder.AppendFormat(
" var z{0}_1 = {1} x1;\n" +
" var z{0}_2 = {1} x2;\n" +
" if ({1} x1) {{}}\n" +
" if ({1} x2) {{}}\n",
k, opTokens[k]);
}
}
builder.Append(
"}\n");
}
builder.Append(
"}\n");
var source = builder.ToString();
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(true));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select ((ExpressionSyntax)(node as PrefixUnaryExpressionSyntax)) ?? node as PostfixUnaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
n = 0;
for (int name = 0; name < typeNames.Length; name++)
{
TypeSymbol type;
if (name == typeNames.Length - 1)
{
type = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Byte));
}
else if (name == typeNames.Length - 2)
{
type = compilation.DynamicType;
}
else
{
type = compilation.GetTypeByMetadataName(typeNames[name]);
}
foreach (var op in operators)
{
TestUnaryIntrinsicSymbol(
op,
type,
compilation,
semanticModel,
nodes[n],
nodes[n + 1],
nodes[n + 2],
nodes[n + 3]);
n += 4;
}
}
Assert.Equal(n, nodes.Length);
}
private void TestUnaryIntrinsicSymbol(
UnaryOperatorKind op,
TypeSymbol type,
CSharpCompilation compilation,
SemanticModel semanticModel,
ExpressionSyntax node1,
ExpressionSyntax node2,
ExpressionSyntax node3,
ExpressionSyntax node4
)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(node1);
Assert.Equal(type.IsDynamic() ? CandidateReason.LateBound : CandidateReason.None, info1.CandidateReason);
Assert.Equal(0, info1.CandidateSymbols.Length);
var symbol1 = (IMethodSymbol)info1.Symbol;
var symbol2 = semanticModel.GetSymbolInfo(node2).Symbol;
var symbol3 = (IMethodSymbol)semanticModel.GetSymbolInfo(node3).Symbol;
var symbol4 = semanticModel.GetSymbolInfo(node4).Symbol;
Assert.Equal(symbol1, symbol3);
if ((object)symbol1 != null)
{
Assert.NotSame(symbol1, symbol3);
Assert.Equal(symbol1.GetHashCode(), symbol3.GetHashCode());
Assert.Equal(symbol1.Parameters[0], symbol3.Parameters[0]);
Assert.Equal(symbol1.Parameters[0].GetHashCode(), symbol3.Parameters[0].GetHashCode());
}
Assert.Equal(symbol2, symbol4);
TypeSymbol underlying = type;
if (op == UnaryOperatorKind.BitwiseComplement ||
op == UnaryOperatorKind.PrefixDecrement || op == UnaryOperatorKind.PrefixIncrement ||
op == UnaryOperatorKind.PostfixDecrement || op == UnaryOperatorKind.PostfixIncrement)
{
underlying = type.EnumUnderlyingTypeOrSelf();
}
UnaryOperatorKind result = OverloadResolution.UnopEasyOut.OpKind(op, underlying);
UnaryOperatorSignature signature;
if (result == UnaryOperatorKind.Error)
{
if (type.IsDynamic())
{
signature = new UnaryOperatorSignature(op | UnaryOperatorKind.Dynamic, type, type);
}
else if (type.IsPointerType() &&
(op == UnaryOperatorKind.PrefixDecrement || op == UnaryOperatorKind.PrefixIncrement ||
op == UnaryOperatorKind.PostfixDecrement || op == UnaryOperatorKind.PostfixIncrement))
{
signature = new UnaryOperatorSignature(op | UnaryOperatorKind.Pointer, type, type);
}
else
{
Assert.Null(symbol1);
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
}
else
{
signature = compilation.builtInOperators.GetSignature(result);
if ((object)underlying != (object)type)
{
Assert.Equal(underlying, signature.OperandType);
Assert.Equal(underlying, signature.ReturnType);
signature = new UnaryOperatorSignature(signature.Kind, type, type);
}
}
Assert.NotNull(symbol1);
string containerName = signature.OperandType.ToTestDisplayString();
string returnName = signature.ReturnType.ToTestDisplayString();
if (op == UnaryOperatorKind.LogicalNegation && type.IsEnumType())
{
containerName = type.ToTestDisplayString();
returnName = containerName;
}
Assert.Equal(String.Format("{2} {0}.{1}({0} value)",
containerName,
OperatorFacts.UnaryOperatorNameFromOperatorKind(op),
returnName),
symbol1.ToTestDisplayString());
Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind);
Assert.True(symbol1.IsImplicitlyDeclared);
bool expectChecked = false;
switch (op)
{
case UnaryOperatorKind.UnaryMinus:
expectChecked = (type.IsDynamic() || symbol1.ContainingType.EnumUnderlyingTypeOrSelf().SpecialType.IsIntegralType());
break;
case UnaryOperatorKind.PrefixDecrement:
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.PostfixIncrement:
expectChecked = (type.IsDynamic() || type.IsPointerType() ||
symbol1.ContainingType.EnumUnderlyingTypeOrSelf().SpecialType.IsIntegralType() ||
symbol1.ContainingType.SpecialType == SpecialType.System_Char);
break;
default:
expectChecked = type.IsDynamic();
break;
}
Assert.Equal(expectChecked, symbol1.IsCheckedBuiltin);
Assert.False(symbol1.IsGenericMethod);
Assert.False(symbol1.IsExtensionMethod);
Assert.False(symbol1.IsExtern);
Assert.False(symbol1.CanBeReferencedByName);
Assert.Null(symbol1.GetSymbol().DeclaringCompilation);
Assert.Equal(symbol1.Name, symbol1.MetadataName);
Assert.Same(symbol1.ContainingSymbol, symbol1.Parameters[0].Type);
Assert.Equal(0, symbol1.Locations.Length);
Assert.Null(symbol1.GetDocumentationCommentId());
Assert.Equal("", symbol1.GetDocumentationCommentXml());
Assert.True(symbol1.GetSymbol().HasSpecialName);
Assert.True(symbol1.IsStatic);
Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility);
Assert.False(symbol1.HidesBaseMethodsByName);
Assert.False(symbol1.IsOverride);
Assert.False(symbol1.IsVirtual);
Assert.False(symbol1.IsAbstract);
Assert.False(symbol1.IsSealed);
Assert.Equal(1, symbol1.GetSymbol().ParameterCount);
Assert.Equal(0, symbol1.Parameters[0].Ordinal);
var otherSymbol = (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol;
Assert.Equal(symbol1, otherSymbol);
if (type.IsValueType && !type.IsPointerType())
{
Assert.Equal(symbol1, symbol2);
return;
}
Assert.Null(symbol2);
}
[Fact()]
public void CheckedUnaryIntrinsicSymbols()
{
var source =
@"
class Module1
{
void Test(int x)
{
var z1 = -x;
var z2 = --x;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(false));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select ((ExpressionSyntax)(node as PrefixUnaryExpressionSyntax)) ?? node as PostfixUnaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(2, nodes.Length);
var symbols1 = (from node1 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol).ToArray();
foreach (var symbol1 in symbols1)
{
Assert.False(symbol1.IsCheckedBuiltin);
}
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(true));
semanticModel = compilation.GetSemanticModel(tree);
var symbols2 = (from node2 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node2).Symbol).ToArray();
foreach (var symbol2 in symbols2)
{
Assert.True(symbol2.IsCheckedBuiltin);
}
for (int i = 0; i < symbols1.Length; i++)
{
Assert.NotEqual(symbols1[i], symbols2[i]);
}
}
[ConditionalFact(typeof(ClrOnly), typeof(NoIOperationValidation), Reason = "https://github.com/mono/mono/issues/10917")]
public void BinaryIntrinsicSymbols1()
{
BinaryOperatorKind[] operators =
{
BinaryOperatorKind.Addition,
BinaryOperatorKind.Subtraction,
BinaryOperatorKind.Multiplication,
BinaryOperatorKind.Division,
BinaryOperatorKind.Remainder,
BinaryOperatorKind.Equal,
BinaryOperatorKind.NotEqual,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Xor,
BinaryOperatorKind.Or,
BinaryOperatorKind.And,
BinaryOperatorKind.LogicalOr,
BinaryOperatorKind.LogicalAnd
};
string[] opTokens = {
"+",
"-",
"*",
"/",
"%",
"==",
"!=",
"<=",
">=",
"<",
">",
"<<",
">>",
"^",
"|",
"&",
"||",
"&&"};
string[] typeNames =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid",
"System.Delegate",
"System.Action",
"System.AppDomainInitializer",
"System.ValueType",
"TestStructure",
"Module1",
"dynamic",
"byte*",
"sbyte*"
};
var builder = new System.Text.StringBuilder();
int n = 0;
builder.Append(
"struct TestStructure\n" +
"{}\n" +
"class Module1\n" +
"{\n");
foreach (var arg1 in typeNames)
{
foreach (var arg2 in typeNames)
{
n += 1;
builder.AppendFormat(
"void Test{2}({0} x1, {1} y1, System.Nullable<{0}> x2, System.Nullable<{1}> y2)\n" +
"{{\n", arg1, arg2, n);
for (int k = 0; k < opTokens.Length; k++)
{
builder.AppendFormat(
" var z{0}_1 = x1 {1} y1;\n" +
" var z{0}_2 = x2 {1} y2;\n" +
" var z{0}_3 = x2 {1} y1;\n" +
" var z{0}_4 = x1 {1} y2;\n" +
" if (x1 {1} y1) {{}}\n" +
" if (x2 {1} y2) {{}}\n" +
" if (x2 {1} y1) {{}}\n" +
" if (x1 {1} y2) {{}}\n",
k, opTokens[k]);
}
builder.Append(
"}\n");
}
}
builder.Append(
"}\n");
var source = builder.ToString();
var compilation = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45Extended, options: TestOptions.ReleaseDll.WithOverflowChecks(true));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
TypeSymbol[] types = new TypeSymbol[typeNames.Length];
for (int i = 0; i < typeNames.Length - 3; i++)
{
types[i] = compilation.GetTypeByMetadataName(typeNames[i]);
}
Assert.Null(types[types.Length - 3]);
types[types.Length - 3] = compilation.DynamicType;
Assert.Null(types[types.Length - 2]);
types[types.Length - 2] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Byte));
Assert.Null(types[types.Length - 1]);
types[types.Length - 1] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_SByte));
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as BinaryExpressionSyntax)).
Where(node => (object)node != null).ToArray();
n = 0;
foreach (var leftType in types)
{
foreach (var rightType in types)
{
foreach (var op in operators)
{
TestBinaryIntrinsicSymbol(
op,
leftType,
rightType,
compilation,
semanticModel,
nodes[n],
nodes[n + 1],
nodes[n + 2],
nodes[n + 3],
nodes[n + 4],
nodes[n + 5],
nodes[n + 6],
nodes[n + 7]);
n += 8;
}
}
}
Assert.Equal(n, nodes.Length);
}
[ConditionalFact(typeof(NoIOperationValidation))]
public void BinaryIntrinsicSymbols2()
{
BinaryOperatorKind[] operators =
{
BinaryOperatorKind.Addition,
BinaryOperatorKind.Subtraction,
BinaryOperatorKind.Multiplication,
BinaryOperatorKind.Division,
BinaryOperatorKind.Remainder,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Xor,
BinaryOperatorKind.Or,
BinaryOperatorKind.And
};
string[] opTokens = {
"+=",
"-=",
"*=",
"/=",
"%=",
"<<=",
">>=",
"^=",
"|=",
"&="};
string[] typeNames =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid",
"System.Delegate",
"System.Action",
"System.AppDomainInitializer",
"System.ValueType",
"TestStructure",
"Module1",
"dynamic",
"byte*",
"sbyte*"
};
var builder = new System.Text.StringBuilder();
int n = 0;
builder.Append(
"struct TestStructure\n" +
"{}\n" +
"class Module1\n" +
"{\n");
foreach (var arg1 in typeNames)
{
foreach (var arg2 in typeNames)
{
n += 1;
builder.AppendFormat(
"void Test{2}({0} x1, {1} y1, System.Nullable<{0}> x2, System.Nullable<{1}> y2)\n" +
"{{\n", arg1, arg2, n);
for (int k = 0; k < opTokens.Length; k++)
{
builder.AppendFormat(
" x1 {1} y1;\n" +
" x2 {1} y2;\n" +
" x2 {1} y1;\n" +
" x1 {1} y2;\n" +
" if (x1 {1} y1) {{}}\n" +
" if (x2 {1} y2) {{}}\n" +
" if (x2 {1} y1) {{}}\n" +
" if (x1 {1} y2) {{}}\n",
k, opTokens[k]);
}
builder.Append(
"}\n");
}
}
builder.Append(
"}\n");
var source = builder.ToString();
var compilation = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40Extended, options: TestOptions.ReleaseDll.WithOverflowChecks(true));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
TypeSymbol[] types = new TypeSymbol[typeNames.Length];
for (int i = 0; i < typeNames.Length - 3; i++)
{
types[i] = compilation.GetTypeByMetadataName(typeNames[i]);
}
Assert.Null(types[types.Length - 3]);
types[types.Length - 3] = compilation.DynamicType;
Assert.Null(types[types.Length - 2]);
types[types.Length - 2] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Byte));
Assert.Null(types[types.Length - 1]);
types[types.Length - 1] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_SByte));
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as AssignmentExpressionSyntax)).
Where(node => (object)node != null).ToArray();
n = 0;
foreach (var leftType in types)
{
foreach (var rightType in types)
{
foreach (var op in operators)
{
TestBinaryIntrinsicSymbol(
op,
leftType,
rightType,
compilation,
semanticModel,
nodes[n],
nodes[n + 1],
nodes[n + 2],
nodes[n + 3],
nodes[n + 4],
nodes[n + 5],
nodes[n + 6],
nodes[n + 7]);
n += 8;
}
}
}
Assert.Equal(n, nodes.Length);
}
private void TestBinaryIntrinsicSymbol(
BinaryOperatorKind op,
TypeSymbol leftType,
TypeSymbol rightType,
CSharpCompilation compilation,
SemanticModel semanticModel,
ExpressionSyntax node1,
ExpressionSyntax node2,
ExpressionSyntax node3,
ExpressionSyntax node4,
ExpressionSyntax node5,
ExpressionSyntax node6,
ExpressionSyntax node7,
ExpressionSyntax node8
)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(node1);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
if (info1.Symbol == null)
{
if (info1.CandidateSymbols.Length == 0)
{
if (leftType.IsDynamic() || rightType.IsDynamic())
{
Assert.True(CandidateReason.LateBound == info1.CandidateReason || CandidateReason.None == info1.CandidateReason);
}
else
{
Assert.Equal(CandidateReason.None, info1.CandidateReason);
}
}
else
{
Assert.Equal(CandidateReason.OverloadResolutionFailure, info1.CandidateReason);
foreach (MethodSymbol s in info1.CandidateSymbols)
{
Assert.Equal(MethodKind.UserDefinedOperator, s.MethodKind);
}
}
}
else
{
Assert.Equal(leftType.IsDynamic() || rightType.IsDynamic() ? CandidateReason.LateBound : CandidateReason.None, info1.CandidateReason);
Assert.Equal(0, info1.CandidateSymbols.Length);
}
var symbol1 = (IMethodSymbol)info1.Symbol;
var symbol2 = semanticModel.GetSymbolInfo(node2).Symbol;
var symbol3 = semanticModel.GetSymbolInfo(node3).Symbol;
var symbol4 = semanticModel.GetSymbolInfo(node4).Symbol;
var symbol5 = (IMethodSymbol)semanticModel.GetSymbolInfo(node5).Symbol;
var symbol6 = semanticModel.GetSymbolInfo(node6).Symbol;
var symbol7 = semanticModel.GetSymbolInfo(node7).Symbol;
var symbol8 = semanticModel.GetSymbolInfo(node8).Symbol;
Assert.Equal(symbol1, symbol5);
Assert.Equal(symbol2, symbol6);
Assert.Equal(symbol3, symbol7);
Assert.Equal(symbol4, symbol8);
if ((object)symbol1 != null && symbol1.IsImplicitlyDeclared)
{
Assert.NotSame(symbol1, symbol5);
Assert.Equal(symbol1.GetHashCode(), symbol5.GetHashCode());
for (int i = 0; i < 2; i++)
{
Assert.Equal(symbol1.Parameters[i], symbol5.Parameters[i]);
Assert.Equal(symbol1.Parameters[i].GetHashCode(), symbol5.Parameters[i].GetHashCode());
}
Assert.NotEqual(symbol1.Parameters[0], symbol5.Parameters[1]);
}
switch (op)
{
case BinaryOperatorKind.LogicalAnd:
case BinaryOperatorKind.LogicalOr:
Assert.Null(symbol1);
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
BinaryOperatorKind result = OverloadResolution.BinopEasyOut.OpKind(op, leftType, rightType);
BinaryOperatorSignature signature;
bool isDynamic = (leftType.IsDynamic() || rightType.IsDynamic());
if (result == BinaryOperatorKind.Error)
{
if (leftType.IsDynamic() && !rightType.IsPointerType() && !rightType.IsRestrictedType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Dynamic, leftType, rightType, leftType);
}
else if (rightType.IsDynamic() && !leftType.IsPointerType() && !leftType.IsRestrictedType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Dynamic, leftType, rightType, rightType);
}
else if ((op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) &&
leftType.IsReferenceType && rightType.IsReferenceType &&
(TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2) || compilation.Conversions.ClassifyConversionFromType(leftType, rightType, ref useSiteDiagnostics).IsReference))
{
if (leftType.IsDelegateType() && rightType.IsDelegateType())
{
Assert.Equal(leftType, rightType);
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Delegate,
leftType, // TODO: this feels like a spec violation
leftType, // TODO: this feels like a spec violation
compilation.GetSpecialType(SpecialType.System_Boolean));
}
else if (leftType.SpecialType == SpecialType.System_Delegate && rightType.SpecialType == SpecialType.System_Delegate)
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Delegate,
compilation.GetSpecialType(SpecialType.System_Delegate), compilation.GetSpecialType(SpecialType.System_Delegate),
compilation.GetSpecialType(SpecialType.System_Boolean));
}
else
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Object, compilation.ObjectType, compilation.ObjectType,
compilation.GetSpecialType(SpecialType.System_Boolean));
}
}
else if (op == BinaryOperatorKind.Addition &&
((leftType.IsStringType() && !rightType.IsPointerType()) || (!leftType.IsPointerType() && rightType.IsStringType())))
{
Assert.False(leftType.IsStringType() && rightType.IsStringType());
if (leftType.IsStringType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.String, leftType, compilation.ObjectType, leftType);
}
else
{
Assert.True(rightType.IsStringType());
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.String, compilation.ObjectType, rightType, rightType);
}
}
else if (op == BinaryOperatorKind.Addition &&
(((leftType.IsIntegralType() || leftType.IsCharType()) && rightType.IsPointerType()) ||
(leftType.IsPointerType() && (rightType.IsIntegralType() || rightType.IsCharType()))))
{
if (leftType.IsPointerType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer, leftType, symbol1.Parameters[1].Type.GetSymbol(), leftType);
Assert.True(symbol1.Parameters[1].Type.GetSymbol().IsIntegralType());
}
else
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer, symbol1.Parameters[0].Type.GetSymbol(), rightType, rightType);
Assert.True(symbol1.Parameters[0].Type.GetSymbol().IsIntegralType());
}
}
else if (op == BinaryOperatorKind.Subtraction &&
(leftType.IsPointerType() && (rightType.IsIntegralType() || rightType.IsCharType())))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.String, leftType, symbol1.Parameters[1].Type.GetSymbol(), leftType);
Assert.True(symbol1.Parameters[1].Type.GetSymbol().IsIntegralType());
}
else if (op == BinaryOperatorKind.Subtraction && leftType.IsPointerType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer, leftType, rightType, compilation.GetSpecialType(SpecialType.System_Int64));
}
else if ((op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction) &&
leftType.IsEnumType() && (rightType.IsIntegralType() || rightType.IsCharType()) &&
(result = OverloadResolution.BinopEasyOut.OpKind(op, leftType.EnumUnderlyingTypeOrSelf(), rightType)) != BinaryOperatorKind.Error &&
TypeSymbol.Equals((signature = compilation.builtInOperators.GetSignature(result)).RightType, leftType.EnumUnderlyingTypeOrSelf(), TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(signature.Kind | BinaryOperatorKind.EnumAndUnderlying, leftType, signature.RightType, leftType);
}
else if ((op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction) &&
rightType.IsEnumType() && (leftType.IsIntegralType() || leftType.IsCharType()) &&
(result = OverloadResolution.BinopEasyOut.OpKind(op, leftType, rightType.EnumUnderlyingTypeOrSelf())) != BinaryOperatorKind.Error &&
TypeSymbol.Equals((signature = compilation.builtInOperators.GetSignature(result)).LeftType, rightType.EnumUnderlyingTypeOrSelf(), TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(signature.Kind | BinaryOperatorKind.EnumAndUnderlying, signature.LeftType, rightType, rightType);
}
else if (op == BinaryOperatorKind.Subtraction &&
leftType.IsEnumType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Enum, leftType, rightType, leftType.EnumUnderlyingTypeOrSelf());
}
else if ((op == BinaryOperatorKind.Equal ||
op == BinaryOperatorKind.NotEqual ||
op == BinaryOperatorKind.LessThan ||
op == BinaryOperatorKind.LessThanOrEqual ||
op == BinaryOperatorKind.GreaterThan ||
op == BinaryOperatorKind.GreaterThanOrEqual) &&
leftType.IsEnumType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Enum, leftType, rightType, compilation.GetSpecialType(SpecialType.System_Boolean));
}
else if ((op == BinaryOperatorKind.Xor ||
op == BinaryOperatorKind.And ||
op == BinaryOperatorKind.Or) &&
leftType.IsEnumType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Enum, leftType, rightType, leftType);
}
else if ((op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction) &&
leftType.IsDelegateType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Delegate, leftType, leftType, leftType);
}
else if ((op == BinaryOperatorKind.Equal ||
op == BinaryOperatorKind.NotEqual ||
op == BinaryOperatorKind.LessThan ||
op == BinaryOperatorKind.LessThanOrEqual ||
op == BinaryOperatorKind.GreaterThan ||
op == BinaryOperatorKind.GreaterThanOrEqual) &&
leftType.IsPointerType() && rightType.IsPointerType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer,
compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Void)),
compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Void)),
compilation.GetSpecialType(SpecialType.System_Boolean));
}
else
{
if ((object)symbol1 != null)
{
Assert.False(symbol1.IsImplicitlyDeclared);
Assert.Equal(MethodKind.UserDefinedOperator, symbol1.MethodKind);
if (leftType.IsValueType && !leftType.IsPointerType())
{
if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Same(symbol1, symbol2);
Assert.Same(symbol1, symbol3);
Assert.Same(symbol1, symbol4);
return;
}
else
{
Assert.Null(symbol2);
Assert.Same(symbol1, symbol3);
Assert.Null(symbol4);
return;
}
}
else if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Same(symbol1, symbol4);
return;
}
else
{
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
}
Assert.Null(symbol1);
Assert.Null(symbol2);
if (!rightType.IsDynamic())
{
Assert.Null(symbol3);
}
if (!leftType.IsDynamic())
{
Assert.Null(symbol4);
}
return;
}
}
else if ((op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) &&
!TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2) &&
(!leftType.IsValueType || !rightType.IsValueType ||
leftType.SpecialType == SpecialType.System_Boolean || rightType.SpecialType == SpecialType.System_Boolean ||
(leftType.SpecialType == SpecialType.System_Decimal && (rightType.SpecialType == SpecialType.System_Double || rightType.SpecialType == SpecialType.System_Single)) ||
(rightType.SpecialType == SpecialType.System_Decimal && (leftType.SpecialType == SpecialType.System_Double || leftType.SpecialType == SpecialType.System_Single))) &&
(!leftType.IsReferenceType || !rightType.IsReferenceType ||
!compilation.Conversions.ClassifyConversionFromType(leftType, rightType, ref useSiteDiagnostics).IsReference))
{
Assert.Null(symbol1);
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
else
{
signature = compilation.builtInOperators.GetSignature(result);
}
Assert.NotNull(symbol1);
string containerName = signature.LeftType.ToTestDisplayString();
string leftName = containerName;
string rightName = signature.RightType.ToTestDisplayString();
string returnName = signature.ReturnType.ToTestDisplayString();
if (isDynamic)
{
containerName = compilation.DynamicType.ToTestDisplayString();
}
else if (op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction)
{
if (signature.LeftType.IsObjectType() && signature.RightType.IsStringType())
{
containerName = rightName;
}
else if ((leftType.IsEnumType() || leftType.IsPointerType()) && (rightType.IsIntegralType() || rightType.IsCharType()))
{
containerName = leftType.ToTestDisplayString();
leftName = containerName;
returnName = containerName;
}
else if ((rightType.IsEnumType() || rightType.IsPointerType()) && (leftType.IsIntegralType() || leftType.IsCharType()))
{
containerName = rightType.ToTestDisplayString();
rightName = containerName;
returnName = containerName;
}
}
Assert.Equal(isDynamic, signature.ReturnType.IsDynamic());
string expectedSymbol = String.Format("{4} {0}.{2}({1} left, {3} right)",
containerName,
leftName,
OperatorFacts.BinaryOperatorNameFromOperatorKind(op),
rightName,
returnName);
string actualSymbol = symbol1.ToTestDisplayString();
Assert.Equal(expectedSymbol, actualSymbol);
Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind);
Assert.True(symbol1.IsImplicitlyDeclared);
bool isChecked;
switch (op)
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Division:
isChecked = isDynamic || symbol1.ContainingSymbol.Kind == SymbolKind.PointerType || symbol1.ContainingType.EnumUnderlyingTypeOrSelf().SpecialType.IsIntegralType();
break;
default:
isChecked = isDynamic;
break;
}
Assert.Equal(isChecked, symbol1.IsCheckedBuiltin);
Assert.False(symbol1.IsGenericMethod);
Assert.False(symbol1.IsExtensionMethod);
Assert.False(symbol1.IsExtern);
Assert.False(symbol1.CanBeReferencedByName);
Assert.Null(symbol1.GetSymbol().DeclaringCompilation);
Assert.Equal(symbol1.Name, symbol1.MetadataName);
Assert.True(SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[0].Type) ||
SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[1].Type));
int match = 0;
if (SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.ReturnType))
{
match++;
}
if (SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[0].Type))
{
match++;
}
if (SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[1].Type))
{
match++;
}
Assert.True(match >= 2);
Assert.Equal(0, symbol1.Locations.Length);
Assert.Null(symbol1.GetDocumentationCommentId());
Assert.Equal("", symbol1.GetDocumentationCommentXml());
Assert.True(symbol1.GetSymbol().HasSpecialName);
Assert.True(symbol1.IsStatic);
Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility);
Assert.False(symbol1.HidesBaseMethodsByName);
Assert.False(symbol1.IsOverride);
Assert.False(symbol1.IsVirtual);
Assert.False(symbol1.IsAbstract);
Assert.False(symbol1.IsSealed);
Assert.Equal(2, symbol1.Parameters.Length);
Assert.Equal(0, symbol1.Parameters[0].Ordinal);
Assert.Equal(1, symbol1.Parameters[1].Ordinal);
var otherSymbol = (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol;
Assert.Equal(symbol1, otherSymbol);
if (leftType.IsValueType && !leftType.IsPointerType())
{
if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Equal(symbol1, symbol2);
Assert.Equal(symbol1, symbol3);
Assert.Equal(symbol1, symbol4);
return;
}
else
{
Assert.Null(symbol2);
if (rightType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol3);
}
else
{
Assert.Equal(rightType.IsPointerType() ? null : symbol1, symbol3);
}
Assert.Null(symbol4);
return;
}
}
else if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Null(symbol2);
Assert.Null(symbol3);
if (leftType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol4);
}
else
{
Assert.Equal(leftType.IsPointerType() ? null : symbol1, symbol4);
}
return;
}
Assert.Null(symbol2);
if (rightType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol3);
}
else
{
Assert.Null(symbol3);
}
if (leftType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol4);
}
else
{
Assert.Null(symbol4);
}
}
[Fact()]
public void BinaryIntrinsicSymbols3()
{
var source =
@"
class Module1
{
void Test(object x)
{
var z1 = x as string;
var z2 = x is string;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select node as BinaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(2, nodes.Length);
foreach (var node1 in nodes)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(node1);
Assert.Null(info1.Symbol);
Assert.Equal(0, info1.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, info1.CandidateReason);
}
}
[Fact()]
public void CheckedBinaryIntrinsicSymbols()
{
var source =
@"
class Module1
{
void Test(int x, int y)
{
var z1 = x + y;
x += y;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(false));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = tree.GetRoot().DescendantNodes().Where(node => node is BinaryExpressionSyntax || node is AssignmentExpressionSyntax).ToArray();
Assert.Equal(2, nodes.Length);
var symbols1 = (from node1 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol).ToArray();
foreach (var symbol1 in symbols1)
{
Assert.False(symbol1.IsCheckedBuiltin);
}
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(true));
semanticModel = compilation.GetSemanticModel(tree);
var symbols2 = (from node2 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node2).Symbol).ToArray();
foreach (var symbol2 in symbols2)
{
Assert.True(symbol2.IsCheckedBuiltin);
}
for (int i = 0; i < symbols1.Length; i++)
{
Assert.NotEqual(symbols1[i], symbols2[i]);
}
}
[Fact()]
public void DynamicBinaryIntrinsicSymbols()
{
var source =
@"
class Module1
{
void Test(dynamic x)
{
var z1 = x == null;
var z2 = null == x;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(false));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select node as BinaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(2, nodes.Length);
var symbols1 = (from node1 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol).ToArray();
foreach (var symbol1 in symbols1)
{
Assert.False(symbol1.IsCheckedBuiltin);
Assert.True(((ITypeSymbol)symbol1.ContainingSymbol).IsDynamic());
Assert.Null(symbol1.ContainingType);
}
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(true));
semanticModel = compilation.GetSemanticModel(tree);
var symbols2 = (from node2 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node2).Symbol).ToArray();
foreach (var symbol2 in symbols2)
{
Assert.True(symbol2.IsCheckedBuiltin);
Assert.True(((ITypeSymbol)symbol2.ContainingSymbol).IsDynamic());
Assert.Null(symbol2.ContainingType);
}
for (int i = 0; i < symbols1.Length; i++)
{
Assert.NotEqual(symbols1[i], symbols2[i]);
}
}
[Fact(), WorkItem(721565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/721565")]
public void Bug721565()
{
var source =
@"
class Module1
{
void Test(TestStr? x, int? y, TestStr? x1, int? y1)
{
var z1 = (x == null);
var z2 = (x != null);
var z3 = (null == x);
var z4 = (null != x);
var z5 = (y == null);
var z6 = (y != null);
var z7 = (null == y);
var z8 = (null != y);
var z9 = (y == y1);
var z10 = (y != y1);
var z11 = (x == x1);
var z12 = (x != x1);
}
}
struct TestStr
{}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (17,20): error CS0019: Operator '==' cannot be applied to operands of type 'TestStr?' and 'TestStr?'
// var z11 = (x == x1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == x1").WithArguments("==", "TestStr?", "TestStr?"),
// (18,20): error CS0019: Operator '!=' cannot be applied to operands of type 'TestStr?' and 'TestStr?'
// var z12 = (x != x1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x != x1").WithArguments("!=", "TestStr?", "TestStr?")
);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select node as BinaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(12, nodes.Length);
for (int i = 0; i < 12; i++)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(nodes[i]);
switch (i)
{
case 0:
case 2:
case 4:
case 6:
Assert.Equal("System.Boolean System.Object.op_Equality(System.Object left, System.Object right)", info1.Symbol.ToTestDisplayString());
break;
case 1:
case 3:
case 5:
case 7:
Assert.Equal("System.Boolean System.Object.op_Inequality(System.Object left, System.Object right)", info1.Symbol.ToTestDisplayString());
break;
case 8:
Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", info1.Symbol.ToTestDisplayString());
break;
case 9:
Assert.Equal("System.Boolean System.Int32.op_Inequality(System.Int32 left, System.Int32 right)", info1.Symbol.ToTestDisplayString());
break;
case 10:
case 11:
Assert.Null(info1.Symbol);
break;
default:
throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(i);
}
}
}
[Fact]
public void IntrinsicBinaryOperatorSignature_EqualsAndGetHashCode()
{
var source =
@"class C
{
static object F(int i)
{
return i += 1;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
var methodBody = methodDecl.Body;
var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(methodBody.SpanStart);
var diagnostics = DiagnosticBag.GetInstance();
var block = binder.BindEmbeddedBlock(methodBody, diagnostics);
diagnostics.Free();
// Rewriter should use Equals.
var rewriter = new EmptyRewriter();
var node = rewriter.Visit(block);
Assert.Same(node, block);
var visitor = new FindCompoundAssignmentWalker();
visitor.Visit(block);
var op = visitor.FirstNode.Operator;
Assert.Null(op.Method);
// Equals and GetHashCode should support null Method.
Assert.Equal(op, new BinaryOperatorSignature(op.Kind, op.LeftType, op.RightType, op.ReturnType, op.Method));
op.GetHashCode();
}
[Fact]
public void StrictEnumSubtraction()
{
var source1 =
@"public enum Color { Red, Blue, Green }
public static class Program
{
public static void M<T>(T t) {}
public static void Main(string[] args)
{
M(1 - Color.Red);
}
}";
CreateCompilation(source1, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(
// (7,11): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'Color'
// M(1 - Color.Red);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 - Color.Red").WithArguments("-", "int", "Color").WithLocation(7, 11)
);
}
/// <summary>
/// Operators && and || are supported when operators
/// & and | are defined on the same type or a derived type
/// from operators true and false only. This matches Dev12.
/// </summary>
[WorkItem(1079034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079034")]
[Fact]
public void UserDefinedShortCircuitingOperators_TrueAndFalseOnBaseType()
{
var source =
@"class A<T>
{
public static bool operator true(A<T> o) { return true; }
public static bool operator false(A<T> o) { return false; }
}
class B : A<object>
{
public static B operator &(B x, B y) { return x; }
}
class C : B
{
public static C operator |(C x, C y) { return x; }
}
class P
{
static void M(C x, C y)
{
if (x && y)
{
}
if (x || y)
{
}
}
}";
var verifier = CompileAndVerify(source);
verifier.Compilation.VerifyDiagnostics();
verifier.VerifyIL("P.M",
@"
{
// Code size 53 (0x35)
.maxstack 2
.locals init (B V_0,
C V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call ""bool A<object>.op_False(A<object>)""
IL_0008: brtrue.s IL_0013
IL_000a: ldloc.0
IL_000b: ldarg.1
IL_000c: call ""B B.op_BitwiseAnd(B, B)""
IL_0011: br.s IL_0014
IL_0013: ldloc.0
IL_0014: call ""bool A<object>.op_True(A<object>)""
IL_0019: pop
IL_001a: ldarg.0
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: call ""bool A<object>.op_True(A<object>)""
IL_0022: brtrue.s IL_002d
IL_0024: ldloc.1
IL_0025: ldarg.1
IL_0026: call ""C C.op_BitwiseOr(C, C)""
IL_002b: br.s IL_002e
IL_002d: ldloc.1
IL_002e: call ""bool A<object>.op_True(A<object>)""
IL_0033: pop
IL_0034: ret
}");
}
/// <summary>
/// Operators && and || are supported when operators
/// & and | are defined on the same type or a derived type
/// from operators true and false only. This matches Dev12.
/// </summary>
[Fact]
public void UserDefinedShortCircuitingOperators_TrueAndFalseOnDerivedType()
{
var source =
@"class A<T>
{
public static A<T> operator |(A<T> x, A<T> y) { return x; }
}
class B : A<object>
{
public static B operator &(B x, B y) { return x; }
}
class C : B
{
public static bool operator true(C o) { return true; }
public static bool operator false(C o) { return false; }
}
class P
{
static void M(C x, C y)
{
if (x && y)
{
}
if (x || y)
{
}
}
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (18,13): error CS0218: In order for 'B.operator &(B, B)' to be applicable as a short circuit operator, its declaring type 'B' must define operator true and operator false
// if (x && y)
Diagnostic(ErrorCode.ERR_MustHaveOpTF, "x && y").WithArguments("B.operator &(B, B)", "B").WithLocation(18, 13),
// (21,13): error CS0218: In order for 'A<object>.operator |(A<object>, A<object>)' to be applicable as a short circuit operator, its declaring type 'A<object>' must define operator true and operator false
// if (x || y)
Diagnostic(ErrorCode.ERR_MustHaveOpTF, "x || y").WithArguments("A<object>.operator |(A<object>, A<object>)", "A<object>").WithLocation(21, 13));
}
private sealed class EmptyRewriter : BoundTreeRewriter
{
protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node)
{
throw new NotImplementedException();
}
}
private sealed class FindCompoundAssignmentWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
internal BoundCompoundAssignmentOperator FirstNode;
public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node)
{
if (FirstNode == null)
{
FirstNode = node;
}
return base.VisitCompoundAssignmentOperator(node);
}
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_0()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
const int y = 0;
x -= y;
}
}
enum E : short { }
";
CompileAndVerify(source: source);
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_1()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
x -= new Test();
}
}
enum E : short { }
class Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_2()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
var y = new Test() - x;
}
}
enum E : short { }
class Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_3()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
const int y = 0;
Print(x - y);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}
enum E : short { }";
CompileAndVerify(source: source, expectedOutput: "System.Int16");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_4()
{
string source = @"
class Program
{
static void Main()
{
E? x = 0;
x -= new Test?(new Test());
}
}
enum E : short { }
struct Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_5()
{
string source = @"
class Program
{
static void Main()
{
E? x = 0;
var y = new Test?(new Test());
var z = y - x;
}
}
enum E : short { }
struct Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_6()
{
string source = @"
class Program
{
static void Main()
{
E? x = 0;
const int y = 0;
Print(x - y);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}
enum E : short { }";
CompileAndVerify(source: source, expectedOutput: "System.Nullable`1[System.Int16]");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_7()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
Base64FormattingOptions? xn0 = Base64FormattingOptions.None;
Print(xn0 - 0);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
CompileAndVerify(source: source, expectedOutput: "System.Nullable`1[System.Base64FormattingOptions]");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_8()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
Base64FormattingOptions? xn0 = Base64FormattingOptions.None;
Print(0 - xn0);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
CompileAndVerify(source: source, expectedOutput: "System.Nullable`1[System.Int32]");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_9()
{
string source = @"
using System;
enum MyEnum1 : short
{
A, B
}
enum MyEnum2
{
A, B
}
class Program
{
static void M<T>(T t)
{
Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
MyEnum1 m1 = (long)0;
M((short)0 - m1);
M((int)0 - m1);
M((long)0 - m1);
MyEnum2 m2 = 0;
M((short)0 - m2);
M((int)0 - m2);
M((long)0 - m2);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Int16
System.Int16
System.Int16
System.Int32
System.Int32
System.Int32");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_10()
{
string source = @"
enum TestEnum : short
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
}
static void Test1()
{
TestEnum x = 0;
byte a = 1;
short b = 1;
byte e = 0;
short f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test2()
{
TestEnum? x = 0;
byte a = 1;
short b = 1;
byte e = 0;
short f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test3()
{
TestEnum x = 0;
byte? a = 1;
short? b = 1;
byte? e = 0;
short? f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test4()
{
TestEnum? x = 0;
byte? a = 1;
short? b = 1;
byte? e = 0;
short? f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test5()
{
TestEnum x = 0;
const byte a = 1;
const short b = 1;
const int c = 1;
const byte e = 0;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - a);
Print(x - b);
Print(x - c);
Print(x - e);
Print(x - f);
Print(x - g);
Print(x - h);
Print(a - x);
Print(b - x);
Print(c - x);
Print(e - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test6()
{
TestEnum? x = 0;
const byte a = 1;
const short b = 1;
const int c = 1;
const byte e = 0;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - a);
Print(x - b);
Print(x - c);
Print(x - e);
Print(x - f);
Print(x - g);
Print(x - h);
Print(a - x);
Print(b - x);
Print(c - x);
Print(e - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (byte)1);
Print(x - (short)1);
Print(x - (int)1);
Print(x - (byte)0);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((byte)1 - x);
Print((short)1 - x);
Print((int)1 - x);
Print((byte)0 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (byte)1);
Print(x - (short)1);
Print(x - (int)1);
Print(x - (byte)0);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((byte)1 - x);
Print((short)1 - x);
Print((int)1 - x);
Print((byte)0 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test9()
{
TestEnum x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
static void Test10()
{
TestEnum? x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
TestEnum
TestEnum
TestEnum
System.Int16
TestEnum
System.Int16
System.Int16
TestEnum
TestEnum
TestEnum
System.Int16
System.Int16
System.Int16
System.Int16
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
TestEnum
TestEnum
TestEnum
System.Int16
TestEnum
System.Int16
System.Int16
TestEnum
TestEnum
TestEnum
System.Int16
System.Int16
System.Int16
System.Int16
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
TestEnum
System.Int16
TestEnum
System.Int16
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_11()
{
string source = @"
enum TestEnum : short
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
}
static void Test1()
{
TestEnum x = 0;
int c = 1;
long d = 1;
int g = 0;
long h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test2()
{
TestEnum? x = 0;
int c = 1;
long d = 1;
int g = 0;
long h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test3()
{
TestEnum x = 0;
int? c = 1;
long? d = 1;
int? g = 0;
long? h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test4()
{
TestEnum? x = 0;
int? c = 1;
long? d = 1;
int? g = 0;
long? h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test5()
{
TestEnum x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test6()
{
TestEnum? x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (26,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum", "int").WithLocation(26, 15),
// (27,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(27, 15),
// (28,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum", "int").WithLocation(28, 15),
// (29,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long").WithLocation(29, 15),
// (30,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int", "TestEnum").WithLocation(30, 15),
// (31,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(31, 15),
// (32,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int", "TestEnum").WithLocation(32, 15),
// (33,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum").WithLocation(33, 15),
// (44,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum?", "int").WithLocation(44, 15),
// (45,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(45, 15),
// (46,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum?", "int").WithLocation(46, 15),
// (47,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long").WithLocation(47, 15),
// (48,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum?'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int", "TestEnum?").WithLocation(48, 15),
// (49,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(49, 15),
// (50,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum?'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int", "TestEnum?").WithLocation(50, 15),
// (51,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum?").WithLocation(51, 15),
// (62,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int?'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum", "int?").WithLocation(62, 15),
// (63,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long?").WithLocation(63, 15),
// (64,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int?'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum", "int?").WithLocation(64, 15),
// (65,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long?").WithLocation(65, 15),
// (66,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int?", "TestEnum").WithLocation(66, 15),
// (67,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum").WithLocation(67, 15),
// (68,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int?", "TestEnum").WithLocation(68, 15),
// (69,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum").WithLocation(69, 15),
// (80,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int?'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum?", "int?").WithLocation(80, 15),
// (81,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long?").WithLocation(81, 15),
// (82,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int?'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum?", "int?").WithLocation(82, 15),
// (83,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long?").WithLocation(83, 15),
// (84,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum?'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int?", "TestEnum?").WithLocation(84, 15),
// (85,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum?").WithLocation(85, 15),
// (86,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum?'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int?", "TestEnum?").WithLocation(86, 15),
// (87,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum?").WithLocation(87, 15),
// (95,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(95, 15),
// (96,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(96, 15),
// (104,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(104, 15),
// (105,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(105, 15),
// (112,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum", "long").WithLocation(112, 15),
// (113,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum").WithLocation(113, 15),
// (120,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum?", "long").WithLocation(120, 15),
// (121,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum?").WithLocation(121, 15)
);
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_12()
{
string source = @"
enum TestEnum : int
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
}
static void Test1()
{
TestEnum x = 0;
short b = 1;
int c = 1;
short f = 0;
int g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test2()
{
TestEnum? x = 0;
short b = 1;
int c = 1;
short f = 0;
int g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test3()
{
TestEnum x = 0;
short? b = 1;
int? c = 1;
short? f = 0;
int? g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test4()
{
TestEnum? x = 0;
short? b = 1;
int? c = 1;
short? f = 0;
int? g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test5()
{
TestEnum x = 0;
const short b = 1;
const int c = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test6()
{
TestEnum? x = 0;
const short b = 1;
const int c = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test9()
{
TestEnum x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
static void Test10()
{
TestEnum? x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
TestEnum
TestEnum
System.Int32
TestEnum
System.Int32
TestEnum
TestEnum
System.Int32
System.Int32
System.Int32
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
TestEnum
TestEnum
System.Int32
TestEnum
System.Int32
TestEnum
TestEnum
System.Int32
System.Int32
System.Int32
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
TestEnum
TestEnum
TestEnum
System.Int32
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_13()
{
string source = @"
enum TestEnum : int
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
}
static void Test1()
{
TestEnum x = 0;
long d = 1;
long h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test2()
{
TestEnum? x = 0;
long d = 1;
long h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test3()
{
TestEnum x = 0;
long? d = 1;
long? h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test4()
{
TestEnum? x = 0;
long? d = 1;
long? h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test5()
{
TestEnum x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test6()
{
TestEnum? x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (24,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(24, 15),
// (25,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long").WithLocation(25, 15),
// (26,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(26, 15),
// (27,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum").WithLocation(27, 15),
// (36,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(36, 15),
// (37,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long").WithLocation(37, 15),
// (38,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(38, 15),
// (39,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum?").WithLocation(39, 15),
// (48,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long?").WithLocation(48, 15),
// (49,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long?").WithLocation(49, 15),
// (50,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum").WithLocation(50, 15),
// (51,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum").WithLocation(51, 15),
// (60,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long?").WithLocation(60, 15),
// (61,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long?").WithLocation(61, 15),
// (62,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum?").WithLocation(62, 15),
// (63,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum?").WithLocation(63, 15),
// (71,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(71, 15),
// (72,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(72, 15),
// (80,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(80, 15),
// (81,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(81, 15),
// (88,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum", "long").WithLocation(88, 15),
// (89,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum").WithLocation(89, 15),
// (96,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum?", "long").WithLocation(96, 15),
// (97,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum?").WithLocation(97, 15)
);
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_14()
{
string source = @"
enum TestEnum : long
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
}
static void Test1()
{
TestEnum x = 0;
short b = 1;
int c = 1;
long d = 1;
short f = 0;
int g = 0;
long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test2()
{
TestEnum? x = 0;
short b = 1;
int c = 1;
long d = 1;
short f = 0;
int g = 0;
long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test3()
{
TestEnum x = 0;
short? b = 1;
int? c = 1;
long? d = 1;
short? f = 0;
int? g = 0;
long? h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test4()
{
TestEnum? x = 0;
short? b = 1;
int? c = 1;
long? d = 1;
short? f = 0;
int? g = 0;
long? h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test5()
{
TestEnum x = 0;
const short b = 1;
const int c = 1;
const long d = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test6()
{
TestEnum? x = 0;
const short b = 1;
const int c = 1;
const long d = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (long)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((long)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (long)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((long)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test9()
{
TestEnum x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
static void Test10()
{
TestEnum? x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
TestEnum
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
System.Int64
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
TestEnum
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
System.Int64
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
TestEnum
System.Int64
TestEnum
System.Int64
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_15()
{
string source = @"
enum TestEnumShort : short
{}
enum TestEnumInt : int
{ }
enum TestEnumLong : long
{ }
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
}
static void Test1()
{
TestEnumShort? x = 0;
Print(x - null);
Print(null - x);
}
static void Test2()
{
TestEnumInt? x = 0;
Print(x - null);
Print(null - x);
}
static void Test3()
{
TestEnumLong? x = 0;
Print(x - null);
Print(null - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_16()
{
string source = @"
enum TestEnumShort : short
{}
enum TestEnumInt : int
{ }
enum TestEnumLong : long
{ }
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
}
static void Test1()
{
TestEnumShort x = 0;
Print(x - null);
Print(null - x);
}
static void Test2()
{
TestEnumInt x = 0;
Print(x - null);
Print(null - x);
}
static void Test3()
{
TestEnumLong x = 0;
Print(x - null);
Print(null - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
");
}
[Fact, WorkItem(1090786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090786")]
public void Bug1090786_01()
{
string source = @"
class Test
{
static void Main()
{
Test0();
Test1();
Test2();
Test3();
Test4();
}
static void Test0()
{
Print(((System.TypeCode)0) as int?);
Print(0 as int?);
Print(((int?)0) as int?);
Print(0 as long?);
Print(0 as ulong?);
Print(GetNullableInt() as long?);
}
static int? GetNullableInt()
{
return 0;
}
static void Test1()
{
var c1 = new C1<int>();
c1.M1(0);
}
static void Test2()
{
var c1 = new C1<ulong>();
c1.M1<ulong>(0);
}
static void Test3()
{
var c1 = new C2();
c1.M1(0);
}
static void Test4()
{
var c1 = new C3();
c1.M1<int?>(0);
}
public static void Print<T>(T? v) where T : struct
{
System.Console.WriteLine(v.HasValue);
}
}
class C1<T>
{
public virtual void M1<S>(S x) where S :T
{
Test.Print(x as ulong?);
}
}
class C2 : C1<int>
{
public override void M1<S>(S x)
{
Test.Print(x as ulong?);
}
}
class C3 : C1<int?>
{
public override void M1<S>(S x)
{
Test.Print(x as ulong?);
}
}
";
var verifier = CompileAndVerify(source: source, expectedOutput:
@"False
True
True
False
False
False
False
True
False
False
");
verifier.VerifyIL("Test.Test0",
@"
{
// Code size 85 (0x55)
.maxstack 1
.locals init (int? V_0,
long? V_1,
ulong? V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""int?""
IL_0008: ldloc.0
IL_0009: call ""void Test.Print<int>(int?)""
IL_000e: ldc.i4.0
IL_000f: newobj ""int?..ctor(int)""
IL_0014: call ""void Test.Print<int>(int?)""
IL_0019: ldc.i4.0
IL_001a: newobj ""int?..ctor(int)""
IL_001f: call ""void Test.Print<int>(int?)""
IL_0024: ldloca.s V_1
IL_0026: initobj ""long?""
IL_002c: ldloc.1
IL_002d: call ""void Test.Print<long>(long?)""
IL_0032: ldloca.s V_2
IL_0034: initobj ""ulong?""
IL_003a: ldloc.2
IL_003b: call ""void Test.Print<ulong>(ulong?)""
IL_0040: call ""int? Test.GetNullableInt()""
IL_0045: pop
IL_0046: ldloca.s V_1
IL_0048: initobj ""long?""
IL_004e: ldloc.1
IL_004f: call ""void Test.Print<long>(long?)""
IL_0054: ret
}");
verifier.VerifyIL("C1<T>.M1<S>",
@"
{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""S""
IL_0006: isinst ""ulong?""
IL_000b: unbox.any ""ulong?""
IL_0010: call ""void Test.Print<ulong>(ulong?)""
IL_0015: ret
}");
verifier.VerifyIL("C2.M1<S>",
@"
{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""S""
IL_0006: isinst ""ulong?""
IL_000b: unbox.any ""ulong?""
IL_0010: call ""void Test.Print<ulong>(ulong?)""
IL_0015: ret
}");
verifier.VerifyIL("C3.M1<S>",
@"
{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""S""
IL_0006: isinst ""ulong?""
IL_000b: unbox.any ""ulong?""
IL_0010: call ""void Test.Print<ulong>(ulong?)""
IL_0015: ret
}");
verifier.VerifyDiagnostics(
// (15,15): warning CS0458: The result of the expression is always 'null' of type 'int?'
// Print(((System.TypeCode)0) as int?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "((System.TypeCode)0) as int?").WithArguments("int?").WithLocation(15, 15),
// (18,15): warning CS0458: The result of the expression is always 'null' of type 'long?'
// Print(0 as long?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "0 as long?").WithArguments("long?").WithLocation(18, 15),
// (19,15): warning CS0458: The result of the expression is always 'null' of type 'ulong?'
// Print(0 as ulong?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "0 as ulong?").WithArguments("ulong?").WithLocation(19, 15),
// (20,15): warning CS0458: The result of the expression is always 'null' of type 'long?'
// Print(GetNullableInt() as long?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "GetNullableInt() as long?").WithArguments("long?").WithLocation(20, 15)
);
}
[Fact, WorkItem(1090786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090786")]
public void Bug1090786_02()
{
string source = @"
using System;
class Program
{
static void Main()
{
var x = 0 as long?;
Console.WriteLine(x.HasValue);
var y = 0 as ulong?;
Console.WriteLine(y.HasValue);
}
}
";
CompileAndVerify(source: source, expectedOutput:
@"False
False
");
}
[Fact, WorkItem(1090786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090786")]
public void Bug1090786_03()
{
string source = @"
class Test
{
static void Main()
{
Test0();
}
static void Test0()
{
var c2 = new C2();
c2.M1<C1>(null);
}
public static void Print<T>(T v) where T : class
{
System.Console.WriteLine(v != null);
}
}
class C1
{}
class C2
{
public void M1<S>(C1 x) where S : C1
{
Test.Print(x as S);
Test.Print(((C1)null) as S);
}
}";
var verifier = CompileAndVerify(source: source, expectedOutput:
@"False
False
");
verifier.VerifyIL("C2.M1<S>",
@"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (S V_0)
IL_0000: ldarg.1
IL_0001: isinst ""S""
IL_0006: unbox.any ""S""
IL_000b: call ""void Test.Print<S>(S)""
IL_0010: ldloca.s V_0
IL_0012: initobj ""S""
IL_0018: ldloc.0
IL_0019: call ""void Test.Print<S>(S)""
IL_001e: ret
}");
}
[Fact, WorkItem(2075, "https://github.com/dotnet/roslyn/issues/2075")]
public void NegateALiteral()
{
string source = @"
using System;
namespace roslynChanges
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ((-(2147483648)).GetType ());
Console.WriteLine ((-2147483648).GetType ());
}
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Int64
System.Int32
");
}
[Fact, WorkItem(4132, "https://github.com/dotnet/roslyn/issues/4132")]
public void Issue4132()
{
string source = @"
using System;
namespace NullableMathRepro
{
class Program
{
static void Main(string[] args)
{
int? x = 0;
x += 5;
Console.WriteLine(""'x' is {0}"", x);
IntHolder? y = 0;
y += 5;
Console.WriteLine(""'y' is {0}"", y);
}
}
struct IntHolder
{
private int x;
public static implicit operator int (IntHolder ih)
{
Console.WriteLine(""operator int (IntHolder ih)"");
return ih.x;
}
public static implicit operator IntHolder(int i)
{
Console.WriteLine(""operator IntHolder(int i)"");
return new IntHolder { x = i };
}
public override string ToString()
{
return x.ToString();
}
}
}";
CompileAndVerify(source: source, expectedOutput:
@"'x' is 5
operator IntHolder(int i)
operator int (IntHolder ih)
operator IntHolder(int i)
'y' is 5");
}
[Fact, WorkItem(8190, "https://github.com/dotnet/roslyn/issues/8190")]
public void Issue8190_1()
{
string source = @"
using System;
namespace RoslynNullableStringRepro
{
public class Program
{
public static void Main(string[] args)
{
NonNullableString? irony = ""abc"";
irony += ""def"";
string ynori = ""abc"";
ynori += (NonNullableString?)""def"";
Console.WriteLine(irony);
Console.WriteLine(ynori);
ynori += (NonNullableString?) null;
Console.WriteLine(ynori);
}
}
struct NonNullableString
{
NonNullableString(string value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
this.value = value;
}
readonly string value;
public override string ToString() => value;
public static implicit operator string(NonNullableString self) => self.value;
public static implicit operator NonNullableString(string value) => new NonNullableString(value);
public static string operator +(NonNullableString lhs, NonNullableString rhs) => lhs.value + rhs.value;
}
}";
CompileAndVerify(source: source, expectedOutput: "abcdef" + Environment.NewLine + "abcdef" + Environment.NewLine + "abcdef");
}
[Fact, WorkItem(8190, "https://github.com/dotnet/roslyn/issues/8190")]
public void Issue8190_2()
{
string source = @"
using System;
namespace RoslynNullableIntRepro
{
public class Program
{
public static void Main(string[] args)
{
NonNullableInt? irony = 1;
irony += 2;
int? ynori = 1;
ynori += (NonNullableInt?) 2;
Console.WriteLine(irony);
Console.WriteLine(ynori);
ynori += (NonNullableInt?) null;
Console.WriteLine(ynori);
}
}
struct NonNullableInt
{
NonNullableInt(int? value)
{
if (value == null)
{
throw new ArgumentNullException();
}
this.value = value;
}
readonly int? value;
public override string ToString() {return value.ToString();}
public static implicit operator int? (NonNullableInt self) {return self.value;}
public static implicit operator NonNullableInt(int? value) {return new NonNullableInt(value);}
public static int? operator +(NonNullableInt lhs, NonNullableInt rhs) { return lhs.value + rhs.value; }
}
}";
CompileAndVerify(source: source, expectedOutput: "3" + Environment.NewLine + "3" + Environment.NewLine);
}
[Fact, WorkItem(4027, "https://github.com/dotnet/roslyn/issues/4027")]
public void NotSignExtendedOperand()
{
string source = @"
class MainClass
{
public static void Main ()
{
short a = 0;
int b = 0;
a |= (short)b;
a = (short)(a | (short)b);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
}
[Fact]
[WorkItem(12345, "https://github.com/dotnet/roslyn/issues/12345")]
public void Bug12345()
{
string source = @"
class EnumRepro
{
public static void Main()
{
EnumWrapper<FlagsEnum> wrappedEnum = FlagsEnum.Goo;
wrappedEnum |= FlagsEnum.Bar;
System.Console.Write(wrappedEnum.Enum);
}
}
public struct EnumWrapper<T>
where T : struct
{
public T? Enum { get; private set; }
public static implicit operator T? (EnumWrapper<T> safeEnum)
{
return safeEnum.Enum;
}
public static implicit operator EnumWrapper<T>(T source)
{
return new EnumWrapper<T> { Enum = source };
}
}
[System.Flags]
public enum FlagsEnum
{
None = 0,
Goo = 1,
Bar = 2,
}
";
var verifier = CompileAndVerify(source, expectedOutput: "Goo, Bar");
verifier.VerifyDiagnostics();
}
[Fact]
public void IsWarningWithNonNullConstant()
{
var source =
@"class Program
{
public static void Main(string[] args)
{
const string d = ""goo"";
var x = d is string;
}
}
";
var compilation = CreateCompilation(source)
.VerifyDiagnostics(
// (6,17): warning CS0183: The given expression is always of the provided ('string') type
// var x = d is string;
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "d is string").WithArguments("string").WithLocation(6, 17)
);
}
[Fact, WorkItem(19310, "https://github.com/dotnet/roslyn/issues/19310")]
public void IsWarningWithTupleConversion()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
var t = (x: 1, y: 2);
if (t is ValueTuple<long, int>) { } // too big
if (t is ValueTuple<short, int>) { } // too small
if (t is ValueTuple<int, int>) { } // goldilocks
}
}";
var compilation = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef })
.VerifyDiagnostics(
// (7,13): warning CS0184: The given expression is never of the provided ('(long, int)') type
// if (t is ValueTuple<long, int>) { } // too big
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "t is ValueTuple<long, int>").WithArguments("(long, int)").WithLocation(7, 13),
// (8,13): warning CS0184: The given expression is never of the provided ('(short, int)') type
// if (t is ValueTuple<short, int>) { } // too small
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "t is ValueTuple<short, int>").WithArguments("(short, int)").WithLocation(8, 13),
// (9,13): warning CS0183: The given expression is always of the provided ('(int, int)') type
// if (t is ValueTuple<int, int>) { } // goldilocks
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "t is ValueTuple<int, int>").WithArguments("(int, int)").WithLocation(9, 13)
);
}
[Fact, WorkItem(21486, "https://github.com/dotnet/roslyn/issues/21486")]
public void TypeOfErrorUnaryOperator()
{
var source =
@"
public class C {
public void M2() {
var local = !invalidExpression;
if (local) { }
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,22): error CS0103: The name 'invalidExpression' does not exist in the current context
// var local = !invalidExpression;
Diagnostic(ErrorCode.ERR_NameNotInContext, "invalidExpression").WithArguments("invalidExpression").WithLocation(4, 22)
);
var tree = compilation.SyntaxTrees.Single();
var negNode = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("!invalidExpression", negNode.ToString());
var type = (ITypeSymbol)compilation.GetSemanticModel(tree).GetTypeInfo(negNode).Type;
Assert.Equal("?", type.ToTestDisplayString());
Assert.True(type.IsErrorType());
}
[Fact, WorkItem(529600, "DevDiv"), WorkItem(7398, "https://github.com/dotnet/roslyn/issues/7398")]
public void Bug529600()
{
// History of this bug: When constant folding a long sequence of string concatentations, there is
// an intermediate constant value for every left-hand operand. So the total memory consumed to
// compute the whole concatenation was O(n^2). The compiler would simply perform this work and
// eventually run out of memory, simply crashing with no useful diagnostic. Later, the concatenation
// implementation was instrumented so it would detect when it was likely to run out of memory soon,
// and would instead report a diagnostic at the last step. This test was added to demonstrate that
// we produced a diagnostic. However, the compiler still consumed O(n^2) memory for the
// concatenation and this test used to consume so much memory that it would cause other tests running
// in parallel to fail because they might not have enough memory to succeed. So the test was
// disabled and eventually removed. The compiler would still crash with programs constaining large
// string concatenations, so the underlying problem had not been addressed. Now we have revised the
// implementation of constant folding so that it requires O(n) memory. As a consequence this test now
// runs very quickly and does not consume gobs of memory.
string source = $@"
class M
{{
static void Main()
{{}}
const string C0 = ""{new string('0', 65000)}"";
const string C1 = C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0;
const string C2 = C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1;
}}
";
CreateCompilation(source).VerifyDiagnostics(
// (28,68): error CS8095: Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.
// C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
Diagnostic(ErrorCode.ERR_ConstantStringTooLong, "C1").WithLocation(28, 68)
);
}
[Fact, WorkItem(39975, "https://github.com/dotnet/roslyn/issues/39975")]
public void EnsureOperandsConvertedInErrorExpression_01()
{
string source =
@"class C
{
static unsafe void M(dynamic d, int* p)
{
d += p;
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (5,9): error CS0019: Operator '+=' cannot be applied to operands of type 'dynamic' and 'int*'
// d += p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d += p").WithArguments("+=", "dynamic", "int*").WithLocation(5, 9)
);
}
}
}
| 39.853953 | 252 | 0.573945 | [
"Apache-2.0"
] | DongchengWang/roslyn | src/Compilers/CSharp/Test/Semantic/Semantics/OperatorTests.cs | 435,554 | C# |
using System;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.ResourceManager.Resources;
using NUnit.Framework;
namespace Azure.ResourceManager.Tests
{
public class ProviderOperationsTests : ResourceManagerTestBase
{
public ProviderOperationsTests(bool isAsync)
: base(isAsync) //, RecordedTestMode.Record)
{
}
[TestCase]
[RecordedTest]
public async Task Get()
{
ProviderContainer providerContainer = Client.DefaultSubscription.GetProviders();
Response<Provider> response = await providerContainer.GetAsync("microsoft.insights");
Provider result = response.Value;
Assert.IsNotNull(result);
}
[TestCase]
[RecordedTest]
public async Task Register()
{
ProviderContainer providerContainer = Client.DefaultSubscription.GetProviders();
Response<Provider> response = await providerContainer.GetAsync("microsoft.compute");
var result = response.Value;
var register = await result.RegisterAsync("microsoft.insights");
Assert.IsNotNull(register);
}
[TestCase]
[RecordedTest]
public async Task RegisterNullException()
{
ProviderContainer providerContainer = Client.DefaultSubscription.GetProviders();
Response<Provider> response = await providerContainer.GetAsync("microsoft.insights");
Assert.ThrowsAsync<ArgumentNullException>(async () => {await response.Value.RegisterAsync(null); });
}
[TestCase]
[RecordedTest]
public async Task RegisterEmptyException()
{
ProviderContainer providerContainer = Client.DefaultSubscription.GetProviders();
Response<Provider> response = await providerContainer.GetAsync("microsoft.insights");
Assert.ThrowsAsync<RequestFailedException>(async () => {await response.Value.RegisterAsync(""); });
}
[TestCase]
[RecordedTest]
public async Task Unregister()
{
ProviderContainer providerContainer = Client.DefaultSubscription.GetProviders();
Response<Provider> response = await providerContainer.GetAsync("microsoft.insights");
var result = response.Value;
var unregister = await result.UnregisterAsync("microsoft.insights");
Assert.IsNotNull(unregister);
}
[TestCase]
[RecordedTest]
public async Task UnregisterNullException()
{
ProviderContainer providerContainer = Client.DefaultSubscription.GetProviders();
Response<Provider> response = await providerContainer.GetAsync("microsoft.insights");
Assert.ThrowsAsync<ArgumentNullException>(async () => {await response.Value.UnregisterAsync(null); });
}
[TestCase]
[RecordedTest]
public async Task UnregisterEmptyException()
{
ProviderContainer providerContainer = Client.DefaultSubscription.GetProviders();
Response<Provider> response = await providerContainer.GetAsync("microsoft.insights");
Assert.ThrowsAsync<RequestFailedException>(async () => {await response.Value.UnregisterAsync(""); });
}
}
}
| 39.282353 | 114 | 0.654987 | [
"MIT"
] | OlhaTkachenko/azure-sdk-for-net | sdk/resourcemanager/Azure.ResourceManager/tests/Scenario/ProviderOperationsTests.cs | 3,341 | C# |
using HatTrick.DbEx.CodeTemplating.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HatTrick.DbEx.CodeTemplating.Builder
{
public class TypeBuilder
{
private static readonly TypeModel _bool = new TypeModel<bool>("bool");
private static readonly TypeModel _byte = new TypeModel<byte>("byte");
private static readonly TypeModel _decimal = new TypeModel<decimal>("decimal");
private static readonly TypeModel _dateTime = new TypeModel<DateTime>("DateTime");
private static readonly TypeModel _dateTimeOffset = new TypeModel<DateTimeOffset>("DateTimeOffset");
private static readonly TypeModel _double = new TypeModel<double>("double");
private static readonly TypeModel _float = new TypeModel<float>("float");
private static readonly TypeModel _guid = new TypeModel<Guid>("Guid");
private static readonly TypeModel _short = new TypeModel<short>("short");
private static readonly TypeModel _int = new TypeModel<int>("int");
private static readonly TypeModel _long = new TypeModel<long>("long");
private static readonly TypeModel _string = new TypeModel<string>("string");
private static readonly TypeModel _timeSpan = new TypeModel<TimeSpan>("TimeSpan");
private static readonly TypeModel _object = new TypeModel<object>("object");
private static readonly Dictionary<Type, TypeModel> allTypes = new Dictionary<Type, TypeModel>()
{
{ typeof(bool), _bool },
{ typeof(byte), _byte },
{ typeof(decimal), _decimal },
{ typeof(DateTime), _dateTime },
{ typeof(DateTimeOffset), _dateTimeOffset },
{ typeof(double), _double },
{ typeof(float), _float },
{ typeof(Guid), _guid },
{ typeof(short), _short },
{ typeof(int), _int },
{ typeof(long), _long },
{ typeof(string), _string },
{ typeof(TimeSpan), _timeSpan },
{ typeof(object), _object }
};
private static readonly Dictionary<Type, TypeModel> numericTypes = new Dictionary<Type, TypeModel>()
{
{ typeof(byte), _byte },
{ typeof(decimal), _decimal },
{ typeof(double), _double },
{ typeof(float), _float },
{ typeof(short), _short },
{ typeof(int), _int },
{ typeof(long), _long }
};
private static readonly Dictionary<Type, TypeModel> dateTypes = new Dictionary<Type, TypeModel>()
{
{ typeof(DateTime), _dateTime },
{ typeof(DateTimeOffset), _dateTimeOffset }
};
private HashSet<TypeModel> @types = new HashSet<TypeModel>();
private HashSet<TypeModel> exceptTypes = new HashSet<TypeModel>();
public TypeBuilder AddAllTypes()
{
foreach (var @type in allTypes)
if (!@types.Contains(@type.Value))
@types.Add(@type.Value);
return this;
}
public TypeBuilder AddNumericTypes()
{
foreach (var @type in numericTypes)
if (!@types.Contains(@type.Value))
@types.Add(@type.Value);
return this;
}
public TypeBuilder AddDateTypes()
{
foreach (var @type in dateTypes)
if (!@types.Contains(@type.Value))
@types.Add(@type.Value);
return this;
}
public TypeBuilder Add<T>()
{
if (!@types.Contains(allTypes[typeof(T)]))
@types.Add(allTypes[typeof(T)]);
return this;
}
public TypeBuilder Add(TypeModel type)
{
if (!@types.Contains(type))
@types.Add(type);
return this;
}
public TypeBuilder Except<T>()
{
var t = typeof(T);
if (!exceptTypes.Contains(allTypes[typeof(T)]))
exceptTypes.Add(allTypes[typeof(T)]);
return this;
}
public TypeBuilder Except(params Type[] remove)
{
foreach (var t in remove)
{
if (!exceptTypes.Contains(allTypes[t]))
exceptTypes.Add(allTypes[t]);
}
return this;
}
public List<TypeModel> ToList() => @types.Except(exceptTypes).ToList();
public static TypeBuilder CreateBuilder()
=> new TypeBuilder();
public static TypeModel Get<T>()
=> allTypes[typeof(T)];
public static TypeModel Create<T>()
=> new TypeModel(typeof(T), allTypes[typeof(T)].Alias);
public static TypeModel Get(Type type)
=> allTypes[type];
public static TypeModel InferReturnType<TSource, TTarget>()
{
return InferReturnType(Get<TSource>(), Get<TTarget>());
}
public static TypeModel InferReturnType(TypeModel sourceType, TypeModel targetType)
{
if (sourceType == Get<byte>() || sourceType == Get<object>())
{
return targetType;
}
if (sourceType == Get<decimal>())
{
if (targetType == Get<byte>()) return Get<decimal>();
if (targetType == Get<decimal>()) return Get<decimal>();
if (targetType == Get<DateTime>()) return Get<DateTime>();
if (targetType == Get<DateTimeOffset>()) return Get<DateTimeOffset>();
if (targetType == Get<double>()) return Get<decimal>();
if (targetType == Get<float>()) return Get<decimal>();
if (targetType == Get<int>()) return Get<decimal>();
if (targetType == Get<long>()) return Get<decimal>();
if (targetType == Get<short>()) return Get<decimal>();
if (targetType == Get<string>()) return Get<string>();
}
if (sourceType == Get<DateTime>())
{
if (targetType == Get<string>()) return Get<string>();
return sourceType;
}
if (sourceType == Get<DateTimeOffset>())
{
if (targetType == Get<string>()) return Get<string>();
return sourceType;
}
if (sourceType == Get<double>())
{
if (targetType == Get<byte>()) return Get<double>();
if (targetType == Get<decimal>()) return Get<decimal>();
if (targetType == Get<DateTime>()) return Get<DateTime>();
if (targetType == Get<DateTimeOffset>()) return Get<DateTimeOffset>();
if (targetType == Get<double>()) return Get<double>();
if (targetType == Get<float>()) return Get<double>();
if (targetType == Get<int>()) return Get<double>();
if (targetType == Get<long>()) return Get<double>();
if (targetType == Get<short>()) return Get<double>();
if (targetType == Get<string>()) return Get<string>();
}
if (sourceType == Get<short>())
{
if (targetType == Get<byte>()) return Get<short>();
if (targetType == Get<decimal>()) return Get<decimal>();
if (targetType == Get<DateTime>()) return Get<DateTime>();
if (targetType == Get<DateTimeOffset>()) return Get<DateTimeOffset>();
if (targetType == Get<double>()) return Get<double>();
if (targetType == Get<float>()) return Get<float>();
if (targetType == Get<int>()) return Get<int>();
if (targetType == Get<long>()) return Get<long>();
if (targetType == Get<short>()) return Get<short>();
if (targetType == Get<string>()) return Get<string>();
}
if (sourceType == Get<int>())
{
if (targetType == Get<byte>()) return Get<int>();
if (targetType == Get<decimal>()) return Get<decimal>();
if (targetType == Get<DateTime>()) return Get<DateTime>();
if (targetType == Get<DateTimeOffset>()) return Get<DateTimeOffset>();
if (targetType == Get<double>()) return Get<double>();
if (targetType == Get<float>()) return Get<float>();
if (targetType == Get<int>()) return Get<int>();
if (targetType == Get<long>()) return Get<long>();
if (targetType == Get<short>()) return Get<int>();
if (targetType == Get<string>()) return Get<string>();
}
if (sourceType == Get<long>())
{
if (targetType == Get<byte>()) return Get<long>();
if (targetType == Get<decimal>()) return Get<decimal>();
if (targetType == Get<DateTime>()) return Get<DateTime>();
if (targetType == Get<DateTimeOffset>()) return Get<DateTimeOffset>();
if (targetType == Get<double>()) return Get<double>();
if (targetType == Get<float>()) return Get<float>();
if (targetType == Get<int>()) return Get<long>();
if (targetType == Get<long>()) return Get<long>();
if (targetType == Get<short>()) return Get<long>();
if (targetType == Get<string>()) return Get<string>();
}
if (sourceType == Get<float>())
{
if (targetType == Get<byte>()) return Get<float>();
if (targetType == Get<decimal>()) return Get<decimal>();
if (targetType == Get<DateTime>()) return Get<DateTime>();
if (targetType == Get<DateTimeOffset>()) return Get<DateTimeOffset>();
if (targetType == Get<double>()) return Get<double>();
if (targetType == Get<float>()) return Get<float>();
if (targetType == Get<int>()) return Get<float>();
if (targetType == Get<long>()) return Get<float>();
if (targetType == Get<short>()) return Get<float>();
if (targetType == Get<string>()) return Get<string>();
}
if (sourceType == Get<TimeSpan>())
{
if (targetType == Get<DateTime>()) return Get<DateTime>();
return sourceType;
}
return sourceType;
}
}
}
| 43.63786 | 108 | 0.524896 | [
"Apache-2.0"
] | HatTrickLabs/dbExpression | tools/HatTrick.DbEx.CodeTemplating/Builder/TypeBuilder.cs | 10,606 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("p05MaxNumber")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP Inc.")]
[assembly: AssemblyProduct("p05MaxNumber")]
[assembly: AssemblyCopyright("Copyright © HP Inc. 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2f297240-4371-4194-a010-11c0d55b0f0c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38 | 84 | 0.747511 | [
"MIT"
] | vesy53/SoftUni | Programming Basics - C#/Exercises/05.SimpleLoops/p05MaxNumber/Properties/AssemblyInfo.cs | 1,409 | C# |
using LitJson;
using System;
namespace Assets.Scripts.Tool
{
public static class JsonDataHelper
{
public static int GetValue(this JsonData data, string valueName, int defaultValue)
{
if (valueName == null)
{
return defaultValue;
}
int result;
try
{
JsonData jsonData = data[valueName];
if (jsonData.IsInt)
{
result = Convert.ToInt32(jsonData.ToString());
}
else
{
result = defaultValue;
}
}
catch (Exception var_1_38)
{
result = defaultValue;
}
return result;
}
public static bool GetValue(this JsonData data, string valueName, bool defaultValue)
{
if (valueName == null)
{
return defaultValue;
}
bool result;
try
{
JsonData jsonData = data[valueName];
if (jsonData.IsBoolean)
{
result = Convert.ToBoolean(jsonData.ToString());
}
else
{
result = defaultValue;
}
}
catch (Exception var_1_38)
{
result = defaultValue;
}
return result;
}
public static string GetValue(this JsonData data, string valueName, string defaultValue)
{
if (valueName == null)
{
return defaultValue;
}
string result;
try
{
JsonData jsonData = data[valueName];
result = jsonData.ToString();
}
catch (Exception var_1_21)
{
result = defaultValue;
}
return result;
}
}
}
| 17.125 | 90 | 0.621168 | [
"MIT"
] | moto2002/kaituo_src | src/Assets.Scripts.Tool/JsonDataHelper.cs | 1,370 | C# |
using Locust.ServiceModel;
using Locust.Modules.Api.Model;
using Locust.ServiceModel.Babbage;
namespace Locust.Modules.Api.Strategies
{
public class ServiceSettingAddContext : BabbageContext<ServiceSettingAddResponse, object, ServiceSettingAddStatus, ServiceSettingAddRequest>
{
}
} | 29.2 | 141 | 0.825342 | [
"MIT"
] | mansoor-omrani/Locust.NET | Modules/Locust.Modules.Api/Service/ServiceSetting/Add/Context.cs | 292 | C# |
using ModelEditor.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModelEditor.Main.ViewModels
{
class PropertyViewModel
{
public PropertyViewModel(CommonViewModel commonViewModel)
{
_commonViewModel = commonViewModel;
}
private CommonViewModel _commonViewModel;
}
}
| 20.7 | 65 | 0.719807 | [
"MIT"
] | MUV38/Tools | ModelEditor/Main/ViewModels/PropertyViewModel.cs | 416 | C# |
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Myproject.Authors.DTO
{
[AutoMapFrom(typeof(Author))]
public class CreateAuthorInput : EntityDto
{
public string AuthorName { get; set; }
public DateTime Created_at { get; set; }
public DateTime Modified_at { get; set; }
}
}
| 19.782609 | 49 | 0.703297 | [
"MIT"
] | ahmetkursatesim/ASPNETProject | src/Myproject.Application/Authors/DTO/CreateAuthorInput.cs | 457 | C# |
//
// Copyright 2020 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using Google.Solutions.IapDesktop.Extensions.Activity.History;
using Google.Solutions.IapDesktop.Extensions.Activity.Services.UsageReport;
using Google.Solutions.IapDesktop.Extensions.Activity.Views.UsageReport;
using NUnit.Framework;
using System;
namespace Google.Solutions.IapDesktop.Extensions.Activity.Test.Views.UsageReport
{
[TestFixture]
public class TestReportViewModel : ActivityFixtureBase
{
private static readonly DateTime BaselineTime = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static ReportArchive CreateReportArchive()
{
var builder = new InstanceSetHistoryBuilder(
BaselineTime,
BaselineTime.AddDays(7));
return new ReportArchive(builder.Build());
}
[Test]
public void WhenIncludeXxSet_ThenGetIncludeXxReflectsThat()
{
var viewModel = new ReportViewModel(CreateReportArchive());
viewModel.IncludeByolInstances =
viewModel.IncludeSplaInstances =
viewModel.IncludeUnknownLicensedInstances =
viewModel.IncludeFleetInstances =
viewModel.IncludeSoleTenantInstances =
viewModel.IncludeLinuxInstances =
viewModel.IncludeWindowsInstances =
viewModel.IncludeUnknownOsInstances = false;
Assert.IsFalse(viewModel.IncludeByolInstances);
Assert.IsFalse(viewModel.IncludeSplaInstances);
Assert.IsFalse(viewModel.IncludeUnknownLicensedInstances);
Assert.IsFalse(viewModel.IncludeFleetInstances);
Assert.IsFalse(viewModel.IncludeSoleTenantInstances);
Assert.IsFalse(viewModel.IncludeLinuxInstances);
Assert.IsFalse(viewModel.IncludeWindowsInstances);
Assert.IsFalse(viewModel.IncludeUnknownOsInstances);
viewModel.IncludeByolInstances =
viewModel.IncludeSplaInstances =
viewModel.IncludeUnknownLicensedInstances =
viewModel.IncludeFleetInstances =
viewModel.IncludeSoleTenantInstances =
viewModel.IncludeLinuxInstances =
viewModel.IncludeWindowsInstances =
viewModel.IncludeUnknownOsInstances = true;
Assert.IsTrue(viewModel.IncludeByolInstances);
Assert.IsTrue(viewModel.IncludeSplaInstances);
Assert.IsTrue(viewModel.IncludeUnknownLicensedInstances);
Assert.IsTrue(viewModel.IncludeFleetInstances);
Assert.IsTrue(viewModel.IncludeSoleTenantInstances);
Assert.IsTrue(viewModel.IncludeLinuxInstances);
Assert.IsTrue(viewModel.IncludeWindowsInstances);
Assert.IsTrue(viewModel.IncludeUnknownOsInstances);
}
[Test]
public void WhenInstancesTabSelected_ThenRightMenusAreEnabled()
{
var viewModel = new ReportViewModel(CreateReportArchive());
viewModel.SelectNodeTab();
viewModel.SelectInstancesTab();
Assert.IsTrue(viewModel.IsTenancyMenuEnabled);
Assert.IsTrue(viewModel.IsOsMenuEnabled);
Assert.IsTrue(viewModel.IsLicenseMenuEnabled);
}
[Test]
public void WhenNodesTabSelected_ThenRightMenusAreEnabled()
{
var viewModel = new ReportViewModel(CreateReportArchive());
viewModel.SelectNodeTab();
Assert.IsFalse(viewModel.IsTenancyMenuEnabled);
Assert.IsTrue(viewModel.IsOsMenuEnabled);
Assert.IsTrue(viewModel.IsLicenseMenuEnabled);
}
[Test]
public void WhenLicensesTabSelected_ThenRightMenusAreEnabled()
{
var viewModel = new ReportViewModel(CreateReportArchive());
viewModel.SelectLicensesTab();
Assert.IsFalse(viewModel.IsTenancyMenuEnabled);
Assert.IsFalse(viewModel.IsOsMenuEnabled);
Assert.IsFalse(viewModel.IsLicenseMenuEnabled);
}
}
}
| 37.992248 | 108 | 0.681698 | [
"Apache-2.0"
] | Bhisma19/iap-desktop | sources/Google.Solutions.IapDesktop.Extensions.Activity.Test/Views/UsageReport/TestReportViewModel.cs | 4,903 | C# |
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using AzerothSharp.Auth;
using AzerothSharp.Common;
using AzerothSharp.Network.Tcp;
namespace AzerothSharp.Auth.Network;
public class AUTH_LOGON_CHALLENGE_C_Reader : IPacketReader<AUTH_LOGON_CHALLENGE_C>
{
public async ValueTask<AUTH_LOGON_CHALLENGE_C> ReadAsync(ChannelReader<byte> reader)
{
AUTH_LOGON_CHALLENGE_C request = new();
request.Command = (byte)AuthCMD.CMD_AUTH_LOGON_CHALLENGE;
request.ErrorCode = await reader.ReadAsync();
request.Length = BitConverter.ToInt16(await reader.ReadArrayAsync(2));
request.GameName = Encoding.UTF8.GetString(await reader.ReadArrayAsync(4));
request.Version1 = await reader.ReadAsync();
request.Version2 = await reader.ReadAsync();
request.Version3 = await reader.ReadAsync();
request.ClientBuild = BitConverter.ToUInt16(await reader.ReadArrayAsync(2));
request.Platform = await reader.ReadArrayAsync(AUTH_LOGON_CHALLENGE_C.PLATFORM_LENGTH);
request.OS = await reader.ReadArrayAsync(AUTH_LOGON_CHALLENGE_C.OS_LENGTH);
request.Country = await reader.ReadArrayAsync(AUTH_LOGON_CHALLENGE_C.COUNTRY_LENGTH);
request.TimeZoneBias = BitConverter.ToInt32(await reader.ReadArrayAsync(4));
request.IpAddress = BitConverter.ToInt32(await reader.ReadArrayAsync(4));
request.AccountNameLength = await reader.ReadAsync();
request.AccountName = Encoding.UTF8.GetString(await reader.ReadArrayAsync(request.AccountNameLength));
return request;
}
}
| 44.148148 | 110 | 0.753356 | [
"MIT"
] | eyeofstorm/AzerothSharp | Common/Auth.Network/Readers/AUTH_LOGON_CHALLENGE_C_Reader.cs | 2,384 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameStart : MonoBehaviour {
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
TransitionToResult();
}
}
public void TransitionToResult()
{
SceneManager.LoadScene("Battle");
}
}
| 18.863636 | 41 | 0.640964 | [
"MIT"
] | dependd/Fight-Animal | Assets/Scripts/GameStart.cs | 417 | C# |
namespace Ann.Layers
{
internal class BaseLayer
{
private readonly MessageShape _inputMessageShape;
private readonly MessageShape _outputMessageShape;
public BaseLayer(
MessageShape inputMessageShape,
MessageShape outputMessageShape)
{
_outputMessageShape = outputMessageShape;
_inputMessageShape = inputMessageShape;
}
public MessageShape GetOutputMessageShape()
{
return _outputMessageShape;
}
public MessageShape GetInputMessageShape()
{
return _inputMessageShape;
}
}
}
| 24.111111 | 58 | 0.619048 | [
"MIT"
] | koryakinp/ann | Ann/Layers/BaseLayer.cs | 653 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("CakeStoreApi")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("CakeStoreApi")]
[assembly: System.Reflection.AssemblyTitleAttribute("CakeStoreApi")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 41.083333 | 80 | 0.649087 | [
"MIT"
] | dabina2018/20486D-Developing-ASP-NET-MVC-Web-Apps | Allfiles/Mod01/Labfiles/02_CakeStoreApi_begin/CakeStoreApi/CakeStoreApi/obj/Debug/netcoreapp2.1/CakeStoreApi.AssemblyInfo.cs | 986 | C# |
using Probability.Core.Models;
namespace Probability.Core.Contracts
{
public interface IProbabilityCalculator
{
decimal Calculate(CalculateProbabilityInput input);
}
} | 21 | 59 | 0.751323 | [
"MIT"
] | alex-piccione/ProbabilityExercise | Core/Contracts/IProbabilityCalculator.cs | 191 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using BlazorBoilerplate.Server.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
//# Links
//## ASP.NET Core Roles/Policies/Claims
//- https://www.red-gate.com/simple-talk/dotnet/c-programming/policy-based-authorization-in-asp-net-core-a-deep-dive/
//- https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.2
//- https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-2.2
//- https://gooroo.io/GoorooTHINK/Article/17333/Custom-user-roles-and-rolebased-authorization-in-ASPNET-core/32835
//- https://gist.github.com/SteveSandersonMS/175a08dcdccb384a52ba760122cd2eda
//- (Suppress redirect on API URLs in ASP.NET Core)[https://stackoverflow.com/a/56384729/54159]
//https://adrientorris.github.io/aspnet-core/identity/extend-user-model.html
namespace BlazorBoilerplate.Server.Authorization
{
public class AdditionalUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole<Guid>>
{
public AdditionalUserClaimsPrincipalFactory(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole<Guid>> roleManager,
IOptions<IdentityOptions> optionsAccessor)
: base(userManager, roleManager, optionsAccessor)
{ }
public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
var principal = await base.CreateAsync(user);
var identity = (ClaimsIdentity)principal.Identity;
if (!string.IsNullOrWhiteSpace(user.FirstName))
{
((ClaimsIdentity)principal.Identity).AddClaims(new[] { new Claim(ClaimTypes.GivenName, user.FirstName)});
}
if (!string.IsNullOrWhiteSpace(user.LastName))
{
((ClaimsIdentity)principal.Identity).AddClaims(new[] {new Claim(ClaimTypes.Surname, user.LastName)});
}
//Example of a trivial claim - https://www.c-sharpcorner.com/article/claim-based-and-policy-based-authorization-with-asp-net-core-2-1/
if (user.Email == "readonly@blazorboilerplate.com")
{
identity.AddClaim(new Claim("ReadOnly", "true"));
}
return principal;
}
}
}
| 37.892308 | 146 | 0.697523 | [
"MIT"
] | marcoscavaleiro/blazorboilerplate | src/BlazorBoilerplate.Server/Authorization/AdditionalUserClaimsPrincipalFactory.cs | 2,465 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Vibration")]
[assembly: AssemblyProduct("Vibration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Hewlett-Packard")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]
// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("25f934ac-0eb9-47a5-ada0-fdaa370839a7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")] | 39.705882 | 77 | 0.758519 | [
"MIT"
] | ookumaneko/Blog_XNA | Vibration/Vibration/Vibration/Properties/AssemblyInfo.cs | 1,353 | C# |
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/Beef
using Beef.Entities;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Beef.RefData
{
/// <summary>
/// Represents a collection that supports multiple Reference Data collections.
/// </summary>
public class ReferenceDataMultiCollection : List<ReferenceDataMultiItem> { }
/// <summary>
/// Represents a <see cref="Name">named</see> <see cref="IReferenceDataCollection"/>.
/// </summary>
public class ReferenceDataMultiItem : IETag
{
/// <summary>
/// Initializes a new instance of the <see cref="ReferenceDataMultiItem"/> class for a <paramref name="name"/> and <paramref name="refDataResult"/>.
/// </summary>
/// <param name="name">The <see cref="Name"/>.</param>
/// <param name="refDataResult">The <see cref="IReferenceDataFilterResult"/>.</param>
public ReferenceDataMultiItem(string name, IReferenceDataFilterResult refDataResult)
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(refDataResult, nameof(refDataResult));
Name = name;
Items = refDataResult.Collection;
ETag = refDataResult.ETag;
}
/// <summary>
/// Gets or sets the reference data name.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the collection <see cref="IETag.ETag"/>.
/// </summary>
[JsonProperty("etag", DefaultValueHandling = DefaultValueHandling.Ignore)]
public string? ETag { get; set; }
/// <summary>
/// Gets or sets the reference data collection.
/// </summary>
[JsonProperty("items")]
public IEnumerable<ReferenceDataBase> Items { get; set; }
}
} | 36.365385 | 156 | 0.617663 | [
"MIT"
] | Avanade/Beef | src/Beef.Abstractions/RefData/ReferenceDataMultiCollection.cs | 1,893 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("StringLength")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StringLength")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f3d02246-1a8d-4750-b400-67bbc65c4064")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.756757 | 84 | 0.745168 | [
"MIT"
] | siderisltd/Telerik-Academy | All Courses Homeworks/C#_Part_2/6. StringsAndText/StringLength/Properties/AssemblyInfo.cs | 1,400 | C# |
//
// Copyright (c) 2004-2019 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests
{
using System;
using System.Collections.Generic;
using Xunit;
public class LogLevelTests : NLogTestBase
{
[Fact]
[Trait("Component", "Core")]
public void OrdinalTest()
{
Assert.True(LogLevel.Trace < LogLevel.Debug);
Assert.True(LogLevel.Debug < LogLevel.Info);
Assert.True(LogLevel.Info < LogLevel.Warn);
Assert.True(LogLevel.Warn < LogLevel.Error);
Assert.True(LogLevel.Error < LogLevel.Fatal);
Assert.True(LogLevel.Fatal < LogLevel.Off);
Assert.False(LogLevel.Trace > LogLevel.Debug);
Assert.False(LogLevel.Debug > LogLevel.Info);
Assert.False(LogLevel.Info > LogLevel.Warn);
Assert.False(LogLevel.Warn > LogLevel.Error);
Assert.False(LogLevel.Error > LogLevel.Fatal);
Assert.False(LogLevel.Fatal > LogLevel.Off);
Assert.True(LogLevel.Trace <= LogLevel.Debug);
Assert.True(LogLevel.Debug <= LogLevel.Info);
Assert.True(LogLevel.Info <= LogLevel.Warn);
Assert.True(LogLevel.Warn <= LogLevel.Error);
Assert.True(LogLevel.Error <= LogLevel.Fatal);
Assert.True(LogLevel.Fatal <= LogLevel.Off);
Assert.False(LogLevel.Trace >= LogLevel.Debug);
Assert.False(LogLevel.Debug >= LogLevel.Info);
Assert.False(LogLevel.Info >= LogLevel.Warn);
Assert.False(LogLevel.Warn >= LogLevel.Error);
Assert.False(LogLevel.Error >= LogLevel.Fatal);
Assert.False(LogLevel.Fatal >= LogLevel.Off);
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelEqualityTest()
{
LogLevel levelTrace = LogLevel.Trace;
LogLevel levelInfo = LogLevel.Info;
Assert.True(LogLevel.Trace == levelTrace);
Assert.True(LogLevel.Info == levelInfo);
Assert.False(LogLevel.Trace == levelInfo);
Assert.False(LogLevel.Trace != levelTrace);
Assert.False(LogLevel.Info != levelInfo);
Assert.True(LogLevel.Trace != levelInfo);
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelFromOrdinal_InputInRange_ExpectValidLevel()
{
Assert.Same(LogLevel.FromOrdinal(0), LogLevel.Trace);
Assert.Same(LogLevel.FromOrdinal(1), LogLevel.Debug);
Assert.Same(LogLevel.FromOrdinal(2), LogLevel.Info);
Assert.Same(LogLevel.FromOrdinal(3), LogLevel.Warn);
Assert.Same(LogLevel.FromOrdinal(4), LogLevel.Error);
Assert.Same(LogLevel.FromOrdinal(5), LogLevel.Fatal);
Assert.Same(LogLevel.FromOrdinal(6), LogLevel.Off);
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelFromOrdinal_InputOutOfRange_ExpectException()
{
Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(100));
// Boundary conditions.
Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(-1));
Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(7));
}
[Fact]
[Trait("Component", "Core")]
public void FromStringTest()
{
Assert.Same(LogLevel.FromString("trace"), LogLevel.Trace);
Assert.Same(LogLevel.FromString("debug"), LogLevel.Debug);
Assert.Same(LogLevel.FromString("info"), LogLevel.Info);
Assert.Same(LogLevel.FromString("warn"), LogLevel.Warn);
Assert.Same(LogLevel.FromString("error"), LogLevel.Error);
Assert.Same(LogLevel.FromString("fatal"), LogLevel.Fatal);
Assert.Same(LogLevel.FromString("off"), LogLevel.Off);
Assert.Same(LogLevel.FromString("Trace"), LogLevel.Trace);
Assert.Same(LogLevel.FromString("Debug"), LogLevel.Debug);
Assert.Same(LogLevel.FromString("Info"), LogLevel.Info);
Assert.Same(LogLevel.FromString("Warn"), LogLevel.Warn);
Assert.Same(LogLevel.FromString("Error"), LogLevel.Error);
Assert.Same(LogLevel.FromString("Fatal"), LogLevel.Fatal);
Assert.Same(LogLevel.FromString("Off"), LogLevel.Off);
Assert.Same(LogLevel.FromString("TracE"), LogLevel.Trace);
Assert.Same(LogLevel.FromString("DebuG"), LogLevel.Debug);
Assert.Same(LogLevel.FromString("InfO"), LogLevel.Info);
Assert.Same(LogLevel.FromString("WarN"), LogLevel.Warn);
Assert.Same(LogLevel.FromString("ErroR"), LogLevel.Error);
Assert.Same(LogLevel.FromString("FataL"), LogLevel.Fatal);
Assert.Same(LogLevel.FromString("TRACE"), LogLevel.Trace);
Assert.Same(LogLevel.FromString("DEBUG"), LogLevel.Debug);
Assert.Same(LogLevel.FromString("INFO"), LogLevel.Info);
Assert.Same(LogLevel.FromString("WARN"), LogLevel.Warn);
Assert.Same(LogLevel.FromString("ERROR"), LogLevel.Error);
Assert.Same(LogLevel.FromString("FATAL"), LogLevel.Fatal);
}
[Fact]
[Trait("Component", "Core")]
public void FromStringFailingTest()
{
Assert.Throws<ArgumentException>(() => LogLevel.FromString("zzz"));
Assert.Throws<ArgumentNullException>(() => LogLevel.FromString(null));
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelNullComparison()
{
LogLevel level = LogLevel.Info;
Assert.False(level == null);
Assert.True(level != null);
Assert.False(null == level);
Assert.True(null != level);
level = null;
Assert.True(level == null);
Assert.False(level != null);
Assert.True(null == level);
Assert.False(null != level);
}
[Fact]
[Trait("Component", "Core")]
public void ToStringTest()
{
Assert.Equal("Trace", LogLevel.Trace.ToString());
Assert.Equal("Debug", LogLevel.Debug.ToString());
Assert.Equal("Info", LogLevel.Info.ToString());
Assert.Equal("Warn", LogLevel.Warn.ToString());
Assert.Equal("Error", LogLevel.Error.ToString());
Assert.Equal("Fatal", LogLevel.Fatal.ToString());
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelCompareTo_ValidLevels_ExpectIntValues()
{
LogLevel levelTrace = LogLevel.Trace;
LogLevel levelDebug = LogLevel.Debug;
LogLevel levelInfo = LogLevel.Info;
LogLevel levelWarn = LogLevel.Warn;
LogLevel levelError = LogLevel.Error;
LogLevel levelFatal = LogLevel.Fatal;
LogLevel levelOff = LogLevel.Off;
LogLevel levelMin = LogLevel.MinLevel;
LogLevel levelMax = LogLevel.MaxLevel;
Assert.Equal(LogLevel.Trace.CompareTo(levelDebug), -1);
Assert.Equal(LogLevel.Debug.CompareTo(levelInfo), -1);
Assert.Equal(LogLevel.Info.CompareTo(levelWarn), -1);
Assert.Equal(LogLevel.Warn.CompareTo(levelError), -1);
Assert.Equal(LogLevel.Error.CompareTo(levelFatal), -1);
Assert.Equal(LogLevel.Fatal.CompareTo(levelOff), -1);
Assert.Equal(1, LogLevel.Debug.CompareTo(levelTrace));
Assert.Equal(1, LogLevel.Info.CompareTo(levelDebug));
Assert.Equal(1, LogLevel.Warn.CompareTo(levelInfo));
Assert.Equal(1, LogLevel.Error.CompareTo(levelWarn));
Assert.Equal(1, LogLevel.Fatal.CompareTo(levelError));
Assert.Equal(1, LogLevel.Off.CompareTo(levelFatal));
Assert.Equal(0, LogLevel.Debug.CompareTo(levelDebug));
Assert.Equal(0, LogLevel.Info.CompareTo(levelInfo));
Assert.Equal(0, LogLevel.Warn.CompareTo(levelWarn));
Assert.Equal(0, LogLevel.Error.CompareTo(levelError));
Assert.Equal(0, LogLevel.Fatal.CompareTo(levelFatal));
Assert.Equal(0, LogLevel.Off.CompareTo(levelOff));
Assert.Equal(0, LogLevel.Trace.CompareTo(levelMin));
Assert.Equal(1, LogLevel.Debug.CompareTo(levelMin));
Assert.Equal(2, LogLevel.Info.CompareTo(levelMin));
Assert.Equal(3, LogLevel.Warn.CompareTo(levelMin));
Assert.Equal(4, LogLevel.Error.CompareTo(levelMin));
Assert.Equal(5, LogLevel.Fatal.CompareTo(levelMin));
Assert.Equal(6, LogLevel.Off.CompareTo(levelMin));
Assert.Equal(LogLevel.Trace.CompareTo(levelMax), -5);
Assert.Equal(LogLevel.Debug.CompareTo(levelMax), -4);
Assert.Equal(LogLevel.Info.CompareTo(levelMax), -3);
Assert.Equal(LogLevel.Warn.CompareTo(levelMax), -2);
Assert.Equal(LogLevel.Error.CompareTo(levelMax), -1);
Assert.Equal(0, LogLevel.Fatal.CompareTo(levelMax));
Assert.Equal(1, LogLevel.Off.CompareTo(levelMax));
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelCompareTo_Null_ExpectException()
{
Assert.Throws<ArgumentNullException>(() => LogLevel.MinLevel.CompareTo(null));
Assert.Throws<ArgumentNullException>(() => LogLevel.MaxLevel.CompareTo(null));
Assert.Throws<ArgumentNullException>(() => LogLevel.Debug.CompareTo(null));
}
[Fact]
[Trait("Component", "Core")]
public void LogLevel_MinMaxLevels_ExpectConstantValues()
{
Assert.Same(LogLevel.Trace, LogLevel.MinLevel);
Assert.Same(LogLevel.Fatal, LogLevel.MaxLevel);
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelGetHashCode()
{
Assert.Equal(0, LogLevel.Trace.GetHashCode());
Assert.Equal(1, LogLevel.Debug.GetHashCode());
Assert.Equal(2, LogLevel.Info.GetHashCode());
Assert.Equal(3, LogLevel.Warn.GetHashCode());
Assert.Equal(4, LogLevel.Error.GetHashCode());
Assert.Equal(5, LogLevel.Fatal.GetHashCode());
Assert.Equal(6, LogLevel.Off.GetHashCode());
}
[Fact]
[Trait("Component", "Core")]
public void LogLevelEquals_Null_ExpectFalse()
{
Assert.False(LogLevel.Debug.Equals(null));
LogLevel logLevel = null;
Assert.False(LogLevel.Debug.Equals(logLevel));
Object obj = logLevel;
Assert.False(LogLevel.Debug.Equals(obj));
}
[Fact]
public void LogLevelEqual_TypeOfObject()
{
// Objects of any other type should always return false.
Assert.False(LogLevel.Debug.Equals((int) 1));
Assert.False(LogLevel.Debug.Equals((string)"Debug"));
// Valid LogLevel objects boxed as Object type.
Object levelTrace = LogLevel.Trace;
Object levelDebug = LogLevel.Debug;
Object levelInfo = LogLevel.Info;
Object levelWarn = LogLevel.Warn;
Object levelError = LogLevel.Error;
Object levelFatal = LogLevel.Fatal;
Object levelOff = LogLevel.Off;
Assert.False(LogLevel.Warn.Equals(levelTrace));
Assert.False(LogLevel.Warn.Equals(levelDebug));
Assert.False(LogLevel.Warn.Equals(levelInfo));
Assert.True(LogLevel.Warn.Equals(levelWarn));
Assert.False(LogLevel.Warn.Equals(levelError));
Assert.False(LogLevel.Warn.Equals(levelFatal));
Assert.False(LogLevel.Warn.Equals(levelOff));
}
[Fact]
public void LogLevelEqual_TypeOfLogLevel()
{
Assert.False(LogLevel.Warn.Equals(LogLevel.Trace));
Assert.False(LogLevel.Warn.Equals(LogLevel.Debug));
Assert.False(LogLevel.Warn.Equals(LogLevel.Info));
Assert.True(LogLevel.Warn.Equals(LogLevel.Warn));
Assert.False(LogLevel.Warn.Equals(LogLevel.Error));
Assert.False(LogLevel.Warn.Equals(LogLevel.Fatal));
Assert.False(LogLevel.Warn.Equals(LogLevel.Off));
}
[Fact]
public void LogLevel_GetAllLevels()
{
Assert.Equal(
new List<LogLevel>() { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal, LogLevel.Off },
LogLevel.AllLevels);
}
[Fact]
public void LogLevel_SetAllLevels()
{
Assert.Throws<NotSupportedException>(() => ((ICollection<LogLevel>) LogLevel.AllLevels).Add(LogLevel.Fatal));
}
[Fact]
public void LogLevel_GetAllLoggingLevels()
{
Assert.Equal(
new List<LogLevel>() { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal },
LogLevel.AllLoggingLevels);
}
[Fact]
public void LogLevel_SetAllLoggingLevels()
{
Assert.Throws<NotSupportedException>(() => ((ICollection<LogLevel>)LogLevel.AllLoggingLevels).Add(LogLevel.Fatal));
}
}
}
| 42.805714 | 148 | 0.618609 | [
"BSD-3-Clause"
] | ALFNeT/NLog | tests/NLog.UnitTests/LogLevelTests.cs | 14,982 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using UCS.Core.Network;
using UCS.Files;
using UCS.Files.CSV;
using UCS.Files.Logic;
using UCS.Logic;
using UCS.PacketProcessing.Messages.Server;
using Timer = System.Threading.Timer;
using static UCS.Core.Logger;
namespace UCS.Core
{
internal class ObjectManager : IDisposable
{
private static long m_vAllianceSeed;
private static long m_vAvatarSeed;
public static int m_vDonationSeed;
private static int m_vRandomBaseAmount;
private static DatabaseManager m_vDatabase;
private static string m_vHomeDefault;
public static bool m_vTimerCanceled;
public static Timer TimerReference;
public static Dictionary<int, string> NpcLevels;
public static Dictionary<int, string> m_vRandomBases;
public static FingerPrint FingerPrint;
public ObjectManager()
{
m_vTimerCanceled = false;
m_vDatabase = new DatabaseManager();
NpcLevels = new Dictionary<int, string>();
m_vRandomBases = new Dictionary<int, string>();
FingerPrint = new FingerPrint();
m_vAvatarSeed = m_vDatabase.GetMaxPlayerId() + 1;
m_vAllianceSeed = m_vDatabase.GetMaxAllianceId() + 1;
m_vHomeDefault = File.ReadAllText(@"Gamefiles/starting_home.json");
//m_vDatabase.CheckConnection();
LoadNpcLevels();
LoadRandomBase();
TimerReference = new Timer(Save, null, 0, 5000);
Say("UCS Database has been succesfully loaded.");
}
void Save(object state)
{
var level = m_vDatabase.Save(ResourcesManager.GetInMemoryLevels());
var alliance = m_vDatabase.Save(ResourcesManager.GetInMemoryAlliances());
level.Wait();
alliance.Wait();
if (m_vTimerCanceled)
TimerReference.Dispose();
}
public static Alliance CreateAlliance(long seed)
{
Alliance alliance;
if (seed == 0)
seed = m_vAllianceSeed;
alliance = new Alliance(seed);
m_vAllianceSeed++;
m_vDatabase.CreateAlliance(alliance);
ResourcesManager.AddAllianceInMemory(alliance);
return alliance;
}
public static Level CreateAvatar(long seed, string token)
{
Level pl;
if (seed == 0)
{
seed = m_vAvatarSeed;
}
pl = new Level(seed, token);
m_vAvatarSeed++;
pl.LoadFromJSON(m_vHomeDefault);
m_vDatabase.CreateAccount(pl);
return pl;
}
public static void Load100AlliancesFromDB()
{
ResourcesManager.AddAllianceInMemory(m_vDatabase.Get100Alliances());
}
public static void LoadAllAlliancesFromDB()
{
ResourcesManager.AddAllianceInMemory(m_vDatabase.GetAllAlliances());
}
public static Alliance GetAlliance(long allianceId)
{
Alliance alliance;
if (ResourcesManager.InMemoryAlliancesContain(allianceId))
{
return ResourcesManager.GetInMemoryAlliance(allianceId);
}
var alliancedb = m_vDatabase.GetAlliance(allianceId);
alliancedb.Wait();
alliance = alliancedb.Result;
if (alliance != null)
{
ResourcesManager.AddAllianceInMemory(alliance);
return alliance;
}
return null;
}
public static List<Alliance> GetInMemoryAlliances()
{
return ResourcesManager.GetInMemoryAlliances();
}
public static Level GetRandomOnlinePlayer()
{
int index = new Random().Next(0, ResourcesManager.GetInMemoryLevels().Count);
return ResourcesManager.GetInMemoryLevels().ElementAt(index);
}
public static Level GetRandomPlayerFromAll()
{
int index = new Random().Next(0, ResourcesManager.GetAllPlayerIds().Count);
return ResourcesManager.GetPlayer(ResourcesManager.GetAllPlayerIds()[index]);
}
public static void LoadNpcLevels()
{
NpcLevels.Add(17000000, new StreamReader(@"Gamefiles/level/NPC/tutorial_npc.json").ReadToEnd());
NpcLevels.Add(17000001, new StreamReader(@"Gamefiles/level/NPC/tutorial_npc2.json").ReadToEnd());
for (int i = 2; i < 50; i++)
using (StreamReader sr = new StreamReader(@"Gamefiles/level/NPC/level" + (i + 1) + ".json"))
NpcLevels.Add(i + 17000000, sr.ReadToEnd());
Say("NPC Levels have been succesfully loaded.");
}
public static void LoadRandomBase()
{
m_vRandomBaseAmount = Directory.GetFiles(@"Gamefiles/level/PVP", "Base*.json").Count();
for (int i = 0; i < m_vRandomBaseAmount; i++)
using (StreamReader sr2 = new StreamReader(@"Gamefiles/level/PVP/Base" + (i + 1) + ".json"))
m_vRandomBases.Add(i, sr2.ReadToEnd());
Say("PVP Levels have been succesfully loaded.");
}
public static void RemoveInMemoryAlliance(long id)
{
ResourcesManager.RemoveAllianceFromMemory(id);
}
public static int RandomBaseCount()
{
return m_vRandomBaseAmount;
}
public void Dispose()
{
if (TimerReference != null)
{
TimerReference.Dispose();
TimerReference = null;
}
}
}
}
| 32.622222 | 109 | 0.59094 | [
"Apache-2.0"
] | Dekryptor/UCS | Ultrapowa Clash Server/Core/ObjectManager.cs | 5,872 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Ce code a été généré par un outil.
// Version du runtime :4.0.30319.42000
//
// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
// le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Manina.Windows.Forms.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 42.148148 | 152 | 0.579086 | [
"Apache-2.0"
] | Cocotteseb/imagelistview | ImageListViewDemo/Properties/Settings.Designer.cs | 1,151 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EDA
{
class Program
{
static void Main(string[] args)
{
//UT_BOA_Binary.RunMain();
//UT_UMDA_Binary.RunMain();
//UT_CGA_Binary.RunMain();
//UT_PBIL_Binary.RunMain();
//UT_CrossEntropy_Continuous.Run_Sphere();
UT_MIMIC_Continuous.Run_Sphere();
//UT_PBIL_Continuous.Run_Sphere();
//UT_CGA_Continuous.Run_Sphere();
//UT_UMDA_Continuous.Run_Sphere();
}
}
}
| 22.428571 | 54 | 0.593949 | [
"MIT"
] | chen0040/cs-estimation-of-distribution-algorithms | cs-estimation-of-distribution-algorithms-samples/Program.cs | 630 | C# |
namespace Sisu_Nipunatha
{
partial class competition_name_list
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
// competition_name_list
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(629, 336);
this.Name = "competition_name_list";
this.Text = "competition_name_list";
this.Load += new System.EventHandler(this.competition_name_list_Load);
this.ResumeLayout(false);
}
#endregion
}
} | 32.361702 | 108 | 0.551611 | [
"Apache-2.0"
] | oshadaamila/Sisu-Nipunatha-2017 | Sisu Nipunatha/Sisu Nipunatha/competition_name_list.Designer.cs | 1,523 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Owin.Hosting;
using Owin;
namespace KatanaIntro
{
using AppFunc = Func<IDictionary<string, object>, Task>;
class Program
{
static void Main(string[] args)
{
var uri = "http://localhost:8080";
using (WebApp.Start<Startup>(uri))
{
Console.WriteLine("Starting...");
Console.WriteLine(uri);
Console.ReadKey();
Console.WriteLine("Stopping...");
}
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use(async (env, next) =>
{
Console.WriteLine("Requesting : " + env.Request.Path);
await next();
Console.WriteLine("Respone: " + env.Response.StatusCode);
});
// This is is ugly code
app.Use(async (environment, next) =>
{
var color = Console.ForegroundColor;
foreach (var pair in environment.Environment)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("{0}: ", pair.Key);
Console.ForegroundColor = color;
if (pair.Key == "owin.ResponseStatusCode") {
if(pair.Value.ToString() == "200")
Console.ForegroundColor = ConsoleColor.Green;
else if (pair.Value.ToString().StartsWith("5"))
Console.ForegroundColor = ConsoleColor.Red;
else
Console.ForegroundColor = ConsoleColor.Yellow;
}
var subs = pair.Value as IDictionary<string, object>;
if (subs != null)
{
foreach (var sub in subs)
{
Console.WriteLine("\t{0}:{1}", sub.Key, sub.Value);
}
}
else
Console.WriteLine("{0}", pair.Value);
}
Console.ForegroundColor = color;
await next();
});
ConfigureWebApi(app);
app.UseHelloWorld();
//app.UseWelcomePage();
}
private void ConfigureWebApi(IAppBuilder app)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
"DefaultApi",
"api/{controller}/{id}",
new {id = RouteParameter.Optional}
);
app.UseWebApi(config);
}
}
public static class AppBuilderExtensions
{
public static void UseHelloWorld(this IAppBuilder app)
{
app.Use<HelloWorldComponent>();
}
}
public class HelloWorldComponent
{
private AppFunc _nextComponent;
public HelloWorldComponent(AppFunc nextComponent)
{
_nextComponent = nextComponent;
}
public Task Invoke(IDictionary<string, object> environment)
{
_nextComponent(environment);
var response = environment["owin.ResponseBody"] as Stream;
using (var writer = new StreamWriter(response))
{
return writer.WriteAsync("Hello!!");
}
}
}
}
| 28.992188 | 79 | 0.484506 | [
"MIT"
] | kenwilcox/KatanaIntro | KatanaIntro/Program.cs | 3,713 | C# |
using Microsoft.Extensions.DependencyInjection;
using Sentry.Extensibility;
using Sentry.Reflection;
namespace Sentry.AspNetCore.Grpc;
/// <summary>
/// Extension methods for <see cref="ISentryBuilder"/>
/// </summary>
public static class SentryBuilderExtensions
{
/// <summary>
/// Adds gRPC integration to Sentry
/// </summary>
/// <param name="builder"></param>
public static ISentryBuilder AddGrpc(this ISentryBuilder builder)
{
_ = builder.Services
.AddSingleton<IProtobufRequestPayloadExtractor, DefaultProtobufRequestPayloadExtractor>()
.AddSingleton<ISentryEventProcessor, SentryGrpcEventProcessor>();
_ = builder.Services.AddGrpc(options =>
{
options.Interceptors.Add<SentryGrpcInterceptor>();
});
return builder;
}
private class SentryGrpcEventProcessor : ISentryEventProcessor
{
private static readonly SdkVersion NameAndVersion
= typeof(SentryGrpcInterceptor).Assembly.GetNameAndVersion();
private static readonly string ProtocolPackageName = "nuget:" + NameAndVersion.Name;
private const string SdkName = "sentry.dotnet.aspnetcore.grpc";
public SentryEvent Process(SentryEvent @event)
{
// Take over the SDK name since this wraps ASP.NET Core
@event.Sdk.Name = SdkName;
@event.Sdk.Version = NameAndVersion.Version;
if (NameAndVersion.Version != null)
{
@event.Sdk.AddPackage(ProtocolPackageName, NameAndVersion.Version);
}
return @event;
}
}
}
| 30.981132 | 101 | 0.657125 | [
"MIT"
] | TawasalMessenger/sentry-dotnet | src/Sentry.AspNetCore.Grpc/SentryBuilderExtensions.cs | 1,642 | C# |
// <auto-generated>
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.SecurityInsights.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Expansion result metadata.
/// </summary>
public partial class ExpansionResultsMetadata
{
/// <summary>
/// Initializes a new instance of the ExpansionResultsMetadata class.
/// </summary>
public ExpansionResultsMetadata()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ExpansionResultsMetadata class.
/// </summary>
/// <param name="aggregations">Information of the aggregated nodes in
/// the expansion result.</param>
public ExpansionResultsMetadata(IList<ExpansionResultAggregation> aggregations = default(IList<ExpansionResultAggregation>))
{
Aggregations = aggregations;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets information of the aggregated nodes in the expansion
/// result.
/// </summary>
[JsonProperty(PropertyName = "aggregations")]
public IList<ExpansionResultAggregation> Aggregations { get; set; }
}
}
| 32.017857 | 132 | 0.644172 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/securityinsights/Microsoft.Azure.Management.SecurityInsights/src/Generated/Models/ExpansionResultsMetadata.cs | 1,793 | C# |
using System;
using Microsoft.Extensions.DependencyInjection;
namespace Scorpio.EntityFrameworkCore
{
internal class DefaultDbContextProvider<TDbContext> : IDbContextProvider<TDbContext>
where TDbContext : ScorpioDbContext<TDbContext>
{
private readonly IServiceProvider _serviceProvider;
public DefaultDbContextProvider(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider;
public TDbContext GetDbContext() => _serviceProvider.GetRequiredService<TDbContext>();
}
} | 35.466667 | 112 | 0.781955 | [
"MIT"
] | project-scorpio/Scorpio | src/EntityFrameworkCore/src/Scorpio.EntityFrameworkCore/Scorpio/EntityFrameworkCore/DefaultDbContextProvider.cs | 534 | C# |
// ------------------------------------------------------------------------------
// 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.
// <auto-generated/>
// Template Source: IStreamRequest.cs.tt
namespace Microsoft.Graph
{
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IEventMessageResponseContentRequest.
/// </summary>
public partial interface IEventMessageResponseContentRequest : IBaseRequest
{
/// <summary>
/// Gets the stream.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
/// <returns>The stream.</returns>
System.Threading.Tasks.Task<Stream> GetAsync(CancellationToken cancellationToken = default, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead);
/// <summary>
/// Gets the <see cref="GraphResponse"/> object of the request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
/// <returns>The <see cref="GraphResponse"/> object of the request.</returns>
System.Threading.Tasks.Task<GraphResponse> GetResponseAsync(CancellationToken cancellationToken = default, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead);
/// <summary>
/// PUTs the specified stream.
/// </summary>
/// <param name="content">The stream to PUT.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
/// <returns>The updated stream.</returns>
System.Threading.Tasks.Task<Stream> PutAsync(Stream content, CancellationToken cancellationToken = default, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead);
/// <summary>
/// PUTs the specified stream and returns a <see cref="GraphResponse"/> object.
/// </summary>
/// <param name="content">The stream to PUT.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
/// <returns>The <see cref="GraphResponse"/> object returned by the PUT call.</returns>
System.Threading.Tasks.Task<GraphResponse> PutResponseAsync(Stream content, CancellationToken cancellationToken = default, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead);
}
}
| 56.616667 | 213 | 0.659111 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IEventMessageResponseContentRequest.cs | 3,397 | C# |
using MathNet.Numerics.Distributions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utilities;
namespace EddiDataDefinitions
{
/// <summary>
/// Details of a star class
/// </summary>
public class StarClass
{
private static readonly List<StarClass> CLASSES = new List<StarClass>();
public string edname { get; private set; }
public string name { get; private set; }
public string chromaticity { get; private set; }
public decimal percentage { get; private set; }
public IUnivariateDistribution massdistribution { get; private set; }
public IUnivariateDistribution radiusdistribution { get; private set; }
public IUnivariateDistribution tempdistribution { get; private set; }
public IUnivariateDistribution agedistribution { get; private set; }
private StarClass(string edname, string name, string chromaticity, decimal percentage, IUnivariateDistribution massdistribution, IUnivariateDistribution radiusdistribution, IUnivariateDistribution tempdistribution, IUnivariateDistribution agedistribution)
{
this.edname = edname;
this.name = name;
this.chromaticity = chromaticity;
this.percentage = percentage;
this.massdistribution = massdistribution;
this.radiusdistribution = radiusdistribution;
this.tempdistribution = tempdistribution;
this.agedistribution = agedistribution;
CLASSES.Add(this);
}
// Percentages are obtained from a combination of https://en.wikipedia.org/wiki/Stellar_classification#Harvard_spectral_classification
// and http://physics.stackexchange.com/questions/153150/what-does-this-stellar-mass-distribution-mean
public static readonly StarClass O = new StarClass("O", "O", "blue", 0.0000009M, new Normal(37.57, 27.50), new Normal(14.52, 29.67), new Normal(49698, 21338), new Normal(138, 262));
public static readonly StarClass B = new StarClass("B", "B", "blue-white", 0.039M, new Normal(5.81, 4.52), new Normal(3.36, 13.42), new Normal(16478, 6044), new Normal(237, 289));
public static readonly StarClass A = new StarClass("A", "A", "blue-white", 0.18M, new Normal(1.82, 2.78), new Normal(2.29, 16.63), new Normal(8208, 1179), new Normal(1809, 20152));
public static readonly StarClass F = new StarClass("F", "F", "white", 0.9M, new Normal(1.30, 0.20), new Normal(1.30, 3.86), new Normal(6743, 531), new Normal(2141, 1662));
public static readonly StarClass G = new StarClass("G", "G", "yellow-white", 2.28M, new Normal(0.94, 0.13), new Normal(1.01, 0.76), new Normal(5653, 7672), new Normal(4713, 3892));
public static readonly StarClass K = new StarClass("K", "K", "yellow-orange", 3.63M, new Normal(1.04, 45.55), new Normal(0.94, 2.11), new Normal(4452, 3284), new Normal(6291, 4144));
public static readonly StarClass M = new StarClass("M", "M", "orange-red", 22.935M, new Normal(0.66, 33.23), new Normal(1.58, 47.11), new Normal(2835, 481), new Normal(6609, 8645));
/// <summary>
/// Provide the cumulative probability that a star of this class will have a temp equal to or lower than that supplied
/// </summary>
public decimal tempCP(decimal l)
{
return (decimal)tempdistribution.CumulativeDistribution((double)l);
}
/// <summary>
/// Provide the cumulative probability that a star of this class will have a temp equal to or lower than that supplied
/// </summary>
public decimal ageCP(decimal l)
{
return (decimal)agedistribution.CumulativeDistribution((double)l);
}
/// <summary>
/// Provide the cumulative probability that a star of this class will have a stellar radius equal to or lower than that supplied
/// </summary>
public decimal stellarRadiusCP(decimal l)
{
return (decimal)radiusdistribution.CumulativeDistribution((double)l);
}
/// <summary>
/// Provide the cumulative probability that a star of this class will have a stellar mass equal to or lower than that supplied
/// </summary>
public decimal stellarMassCP(decimal l)
{
return (decimal)massdistribution.CumulativeDistribution((double)l);
}
public static StarClass FromName(string from)
{
return CLASSES.FirstOrDefault(v => v.name == from);
}
public static StarClass FromEDName(string from)
{
if (from == null)
{
return null;
}
return CLASSES.FirstOrDefault(v => v.edname == from);
}
/// <summary>
/// Convert radius in m in to stellar radius
/// </summary>
public static decimal solarradius(decimal radius)
{
return radius / 695500000;
}
/// <summary>
/// Convert absolute magnitude in to luminosity
/// </summary>
public static decimal luminosity(decimal absoluteMagnitude)
{
double solAbsoluteMagnitude = 4.83;
return (decimal)Math.Pow(Math.Pow(100, 0.2), (solAbsoluteMagnitude - (double)absoluteMagnitude));
}
public static decimal temperature(decimal luminosity, decimal radius)
{
double solLuminosity = 3.846e26;
double stefanBoltzmann = 5.670367e-8;
return (decimal)Math.Pow(((double)luminosity * solLuminosity) / (4 * Math.PI * Math.Pow((double)radius, 2) * stefanBoltzmann), 0.25);
}
public static decimal sanitiseCP(decimal cp)
{
// Trim decimal places appropriately
if (cp < .00001M || cp > .9999M)
{
return Math.Round(cp * 100, 4);
}
else if (cp < .0001M || cp > .999M)
{
return Math.Round(cp * 100, 3);
}
else if (cp < .001M || cp > .99M)
{
return Math.Round(cp * 100, 2);
}
else
{
return Math.Round(cp * 100);
}
}
}
}
| 41.405229 | 263 | 0.614207 | [
"Apache-2.0"
] | cmdrmcdonald/EliteDangerousDataProvider | DataDefinitions/StarClass.cs | 6,337 | C# |
using System.Collections.Generic;
using PizzaWorld.Domain.Abstracts;
using PizzaWorld.Domian.Models;
namespace PizzaWorld.Domain.Models
{
public class VeggiePizza : APizzaModel
{
protected override void AddCrust()
{
Crust = new Crust();
}
protected override void AddSize()
{
Size = new Size();
}
protected override void AddToppings()
{
Toppings = new List<Toppings>
{
new Toppings("cheese", 0),
new Toppings("bell pepper", 0)
};
}
public override string ToString()
{
string output = "Veggie Pizza";
return output;
}
}
} | 19.30303 | 41 | 0.610675 | [
"MIT"
] | elock721/project-p0 | PizzaWorld.Domain/Models/VeggiePizza.cs | 637 | C# |
using System;
using System.Threading;
namespace AMWD.Modbus.Proxy
{
internal static class Extensions
{
public static IDisposable GetReadLock(this ReaderWriterLockSlim rwLock, int millisecondsTimeout = -1)
{
if (!rwLock.TryEnterReadLock(millisecondsTimeout))
throw new TimeoutException("Trying to enter a read lock.");
return new DisposableReaderWriterLockSlim(rwLock, DisposableReaderWriterLockSlim.LockMode.ReadLock);
}
public static IDisposable GetReadLock(this ReaderWriterLockSlim rwLock, TimeSpan timeSpan)
{
if (!rwLock.TryEnterReadLock(timeSpan))
throw new TimeoutException("Trying to enter a read lock.");
return new DisposableReaderWriterLockSlim(rwLock, DisposableReaderWriterLockSlim.LockMode.ReadLock);
}
public static IDisposable GetUpgradableReadLock(this ReaderWriterLockSlim rwLock, int millisecondsTimeout = -1)
{
if (!rwLock.TryEnterUpgradeableReadLock(millisecondsTimeout))
throw new TimeoutException("Trying to enter an upgradable read lock.");
return new DisposableReaderWriterLockSlim(rwLock, DisposableReaderWriterLockSlim.LockMode.UpgradableReadLock);
}
public static IDisposable GetUpgradableReadLock(this ReaderWriterLockSlim rwLock, TimeSpan timeSpan)
{
if (!rwLock.TryEnterUpgradeableReadLock(timeSpan))
throw new TimeoutException("Trying to enter an upgradable read lock.");
return new DisposableReaderWriterLockSlim(rwLock, DisposableReaderWriterLockSlim.LockMode.UpgradableReadLock);
}
public static IDisposable GetWriteLock(this ReaderWriterLockSlim rwLock, int millisecondsTimeout = -1)
{
if (!rwLock.TryEnterWriteLock(millisecondsTimeout))
throw new TimeoutException("Trying to enter a write lock.");
return new DisposableReaderWriterLockSlim(rwLock, DisposableReaderWriterLockSlim.LockMode.WriteLock);
}
public static IDisposable GetWriteLock(this ReaderWriterLockSlim rwLock, TimeSpan timeSpan)
{
if (!rwLock.TryEnterWriteLock(timeSpan))
throw new TimeoutException("Trying to enter a write lock.");
return new DisposableReaderWriterLockSlim(rwLock, DisposableReaderWriterLockSlim.LockMode.WriteLock);
}
private class DisposableReaderWriterLockSlim : IDisposable
{
private ReaderWriterLockSlim rwLock;
private LockMode mode;
public DisposableReaderWriterLockSlim(ReaderWriterLockSlim rwLock, LockMode mode)
{
this.rwLock = rwLock;
this.mode = mode;
}
public void Dispose()
{
if (rwLock == null || mode == LockMode.None)
return;
if (mode == LockMode.ReadLock)
rwLock.ExitReadLock();
if (mode == LockMode.UpgradableReadLock && rwLock.IsWriteLockHeld)
rwLock.ExitWriteLock();
if (mode == LockMode.UpgradableReadLock)
rwLock.ExitUpgradeableReadLock();
if (mode == LockMode.WriteLock)
rwLock.ExitWriteLock();
mode = LockMode.None;
}
public enum LockMode
{
None,
ReadLock,
UpgradableReadLock,
WriteLock
}
}
}
}
| 31.639175 | 114 | 0.739655 | [
"MIT"
] | blinds52/Modbus | src/Modbus.Proxy/Extensions.cs | 3,071 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
namespace System.Data.Entity.Infrastructure.DependencyResolution
{
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Infrastructure.Interception;
using System.Data.Entity.Infrastructure.Pluralization;
using System.Data.Entity.Internal;
using System.Data.Entity.Migrations.History;
using System.Data.Entity.ModelConfiguration.Utilities;
using System.Data.Entity.Utilities;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
// <summary>
// This resolver is always the last resolver in the internal resolver chain and is
// responsible for providing the default service for each dependency or throwing an
// exception if there is no reasonable default service.
// </summary>
internal class RootDependencyResolver : IDbDependencyResolver
{
private readonly ResolverChain _defaultProviderResolvers = new ResolverChain();
private readonly ResolverChain _defaultResolvers = new ResolverChain();
private readonly ResolverChain _resolvers = new ResolverChain();
private readonly DatabaseInitializerResolver _databaseInitializerResolver;
public RootDependencyResolver()
: this(new DefaultProviderServicesResolver(), new DatabaseInitializerResolver())
{
}
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
[SuppressMessage("Microsoft.Reliability", "CA2000: Dispose objects before losing scope")]
public RootDependencyResolver(
DefaultProviderServicesResolver defaultProviderServicesResolver,
DatabaseInitializerResolver databaseInitializerResolver)
{
DebugCheck.NotNull(defaultProviderServicesResolver);
DebugCheck.NotNull(databaseInitializerResolver);
_databaseInitializerResolver = databaseInitializerResolver;
_resolvers.Add(new TransactionContextInitializerResolver());
_resolvers.Add(_databaseInitializerResolver);
_resolvers.Add(new DefaultExecutionStrategyResolver());
_resolvers.Add(new CachingDependencyResolver(defaultProviderServicesResolver));
_resolvers.Add(new CachingDependencyResolver(new DefaultProviderFactoryResolver()));
_resolvers.Add(new CachingDependencyResolver(new DefaultInvariantNameResolver()));
_resolvers.Add(new SingletonDependencyResolver<IDbConnectionFactory>(new SqlConnectionFactory()));
_resolvers.Add(new SingletonDependencyResolver<Func<DbContext, IDbModelCacheKey>>(new DefaultModelCacheKeyFactory().Create));
_resolvers.Add(new SingletonDependencyResolver<IManifestTokenResolver>(new DefaultManifestTokenResolver()));
_resolvers.Add(new SingletonDependencyResolver<Func<DbConnection, string, HistoryContext>>(HistoryContext.DefaultFactory));
_resolvers.Add(new SingletonDependencyResolver<IPluralizationService>(new EnglishPluralizationService()));
_resolvers.Add(new SingletonDependencyResolver<AttributeProvider>(new AttributeProvider()));
_resolvers.Add(new SingletonDependencyResolver<Func<DbContext, Action<string>, DatabaseLogFormatter>>((c, w) => new DatabaseLogFormatter(c, w)));
_resolvers.Add(new SingletonDependencyResolver<Func<TransactionHandler>>(() => new DefaultTransactionHandler(), k => k is ExecutionStrategyKey));
#if NET40
_resolvers.Add(new SingletonDependencyResolver<IDbProviderFactoryResolver>(new Net40DefaultDbProviderFactoryResolver()));
#else
_resolvers.Add(new SingletonDependencyResolver<IDbProviderFactoryResolver>(new DefaultDbProviderFactoryResolver()));
#endif
_resolvers.Add(new SingletonDependencyResolver<Func<IMetadataAnnotationSerializer>>(
() => new ClrTypeAnnotationSerializer(), XmlConstants.ClrTypeAnnotation));
_resolvers.Add(new SingletonDependencyResolver<Func<IMetadataAnnotationSerializer>>(
() => new IndexAnnotationSerializer(), IndexAnnotation.AnnotationName));
}
public DatabaseInitializerResolver DatabaseInitializerResolver
{
get { return _databaseInitializerResolver; }
}
// <inheritdoc />
public virtual object GetService(Type type, object key)
{
return _defaultResolvers.GetService(type, key)
?? _defaultProviderResolvers.GetService(type, key)
?? _resolvers.GetService(type, key);
}
public virtual void AddDefaultResolver(IDbDependencyResolver resolver)
{
DebugCheck.NotNull(resolver);
_defaultResolvers.Add(resolver);
}
public virtual void SetDefaultProviderServices(DbProviderServices provider, string invariantName)
{
DebugCheck.NotNull(provider);
DebugCheck.NotEmpty(invariantName);
_defaultProviderResolvers.Add(new SingletonDependencyResolver<DbProviderServices>(provider, invariantName));
_defaultProviderResolvers.Add(provider);
}
public IEnumerable<object> GetServices(Type type, object key)
{
return _defaultResolvers.GetServices(type, key).Concat(_resolvers.GetServices(type, key));
}
}
}
| 52.045872 | 157 | 0.728715 | [
"MIT"
] | dotnet/ef6tools | src/EntityFramework/Infrastructure/DependencyResolution/RootDependencyResolver.cs | 5,673 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using EncompassRest.Loans.Enums;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// Application
/// </summary>
public sealed partial class Application : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<string?>? _accountNumber1;
private DirtyValue<string?>? _accountNumber2;
private DirtyList<AdditionalLoan>? _additionalLoans;
private DirtyValue<decimal?>? _allOtherPaymentsAmount;
private DirtyValue<string?>? _applicationId;
private DirtyValue<int?>? _applicationIndex;
private DirtyValue<DateTime?>? _applicationSignedDate;
private DirtyList<Asset>? _assets;
private DirtyValue<decimal?>? _assetsAvailableAmount;
private DirtyValue<ATRQMBorrower?>? _aTRQMBorrower;
private DirtyList<ATRQMBorrower>? _aTRQMBorrowers;
private DirtyList<AUSTrackingLog>? _aUSTrackingLogs;
private DirtyValue<decimal?>? _balanceAvailableFamilySupportGuideline;
private Borrower? _borrower;
private DirtyValue<string?>? _borrowerPairId;
private DirtyValue<decimal?>? _bottomRatioPercent;
private DirtyValue<decimal?>? _brwCoBrwTotalTaxDeductions;
private DirtyValue<DateTime?>? _closingDisclosureBorDeliveryDate;
private DirtyValue<DateTime?>? _closingDisclosureBorReceivedDate;
private Borrower? _coborrower;
private DirtyValue<string?>? _creditAliasName1;
private DirtyValue<string?>? _creditAliasName2;
private DirtyValue<string?>? _creditorName1;
private DirtyValue<string?>? _creditorName2;
private DirtyValue<string?>? _creditReportReferenceIdentifier;
private DirtyList<Employment>? _employment;
private DirtyValue<bool?>? _entityDeleted;
private DirtyValue<string?>? _equifaxAddress;
private DirtyValue<string?>? _equifaxCity;
private DirtyValue<string?>? _equifaxFax;
private DirtyValue<string?>? _equifaxModel;
private DirtyValue<string?>? _equifaxName;
private DirtyValue<string?>? _equifaxPhone;
private DirtyValue<string?>? _equifaxPostalCode;
private DirtyValue<string?>? _equifaxScoreRangeFrom;
private DirtyValue<string?>? _equifaxScoreRangeTo;
private DirtyValue<StringEnumValue<State>>? _equifaxState;
private DirtyValue<string?>? _equifaxWebsite;
private DirtyValue<string?>? _experianAddress;
private DirtyValue<string?>? _experianCity;
private DirtyValue<string?>? _experianFax;
private DirtyValue<string?>? _experianModel;
private DirtyValue<string?>? _experianName;
private DirtyValue<string?>? _experianPhone;
private DirtyValue<string?>? _experianPostalCode;
private DirtyValue<string?>? _experianScoreRangeFrom;
private DirtyValue<string?>? _experianScoreRangeTo;
private DirtyValue<StringEnumValue<State>>? _experianState;
private DirtyValue<string?>? _experianWebsite;
private DirtyValue<decimal?>? _fhaVaDebtIncomeRatio;
private DirtyValue<decimal?>? _fhaVaFamilySupportAmount;
private DirtyValue<decimal?>? _fhaVaTotalEstimatedMonthlyShelterExpenseAmount;
private DirtyValue<decimal?>? _fhaVaTotalNetEffectiveIncomeAmount;
private DirtyValue<decimal?>? _fhaVaTotalNetIncomeAmount;
private DirtyValue<decimal?>? _fhaVaTotalNetTakeHomePayAmount;
private DirtyValue<decimal?>? _fhaVaTotalOtherNetIncome;
private DirtyValue<decimal?>? _firstMortgagePrincipalAndInterestAmount;
private DirtyValue<string?>? _freddieMacCreditReportReferenceIdentifier;
private DirtyValue<decimal?>? _freddieMacOccupantDebtRatio;
private DirtyValue<decimal?>? _freddieMacOccupantHousingRatio;
private DirtyValue<decimal?>? _freDebtToHousingGapRatio;
private DirtyList<GiftGrant>? _giftsGrants;
private DirtyValue<decimal?>? _grossBaseIncomeAmount;
private DirtyValue<decimal?>? _grossIncomeForComortSet;
private DirtyValue<decimal?>? _grossNegativeCashFlow;
private DirtyValue<decimal?>? _grossOtherIncomeAmount;
private DirtyValue<decimal?>? _grossPositiveCashFlow;
private DirtyValue<string?>? _hazardInsuranceAmount;
private DirtyValue<string?>? _homeownersAssociationDuesAndCondoFeesAmount;
private DirtyValue<string?>? _hudAutoLienHolderName1;
private DirtyValue<string?>? _hudAutoLienHolderName2;
private DirtyValue<decimal?>? _hudAutoLoanAmount1;
private DirtyValue<decimal?>? _hudAutoLoanAmount2;
private DirtyValue<decimal?>? _hudAutoMonthlyPayment1;
private DirtyValue<decimal?>? _hudAutoMonthlyPayment2;
private DirtyValue<decimal?>? _hudAutoPresentBalance1;
private DirtyValue<decimal?>? _hudAutoPresentBalance2;
private DirtyValue<string?>? _hudAutoYearAndMake1;
private DirtyValue<string?>? _hudAutoYearAndMake2;
private DirtyValue<decimal?>? _hudLoanAmount1;
private DirtyValue<decimal?>? _hudLoanAmount10;
private DirtyValue<decimal?>? _hudLoanAmount11;
private DirtyValue<decimal?>? _hudLoanAmount2;
private DirtyValue<decimal?>? _hudLoanAmount3;
private DirtyValue<decimal?>? _hudLoanAmount4;
private DirtyValue<decimal?>? _hudLoanAmount5;
private DirtyValue<decimal?>? _hudLoanAmount6;
private DirtyValue<decimal?>? _hudLoanAmount7;
private DirtyValue<decimal?>? _hudLoanAmount8;
private DirtyValue<decimal?>? _hudLoanAmount9;
private DirtyValue<bool?>? _hudRealEstateFhaInsured1;
private DirtyValue<bool?>? _hudRealEstateFhaInsured2;
private DirtyValue<string?>? _hudRealEstateLienHolder1;
private DirtyValue<string?>? _hudRealEstateLienHolder2;
private DirtyValue<decimal?>? _hudRealEstateLoanAmount1;
private DirtyValue<decimal?>? _hudRealEstateLoanAmount2;
private DirtyValue<decimal?>? _hudRealEstateMonthlyPayment1;
private DirtyValue<decimal?>? _hudRealEstateMonthlyPayment2;
private DirtyValue<decimal?>? _hudRealEstatePresentBalance1;
private DirtyValue<decimal?>? _hudRealEstatePresentBalance2;
private DirtyValue<string?>? _id;
private DirtyList<Income>? _income;
private DirtyValue<bool?>? _incomeOfBorrowersSpouseUsedIndicator;
private DirtyValue<bool?>? _incomeOtherThanBorrowerUsedIndicator;
private DirtyValue<bool?>? _jointAssetLiabilityReportingIndicator;
private DirtyValue<string?>? _lastModified;
private DirtyList<Liability>? _liabilities;
private DirtyValue<decimal?>? _liquidAssetsComortSet;
private DirtyValue<string?>? _loanAmount;
private DirtyValue<DateTime?>? _loanEstimateDeliveryDate;
private DirtyValue<string?>? _loanOfficerId;
private DirtyValue<string?>? _loanOfficerName;
private DirtyValue<decimal?>? _mcawBorrowerOtherMonthlyIncomeAmount;
private DirtyValue<decimal?>? _mcawCoborrowerOtherMonthlyIncomeAmount;
private DirtyValue<decimal?>? _mcawGrossMonthlyIncomeAmount;
private DirtyValue<decimal?>? _mcawMortgagePaymentToIncome1Amount;
private DirtyValue<decimal?>? _mcawMortgagePaymentToIncome2Amount;
private DirtyValue<decimal?>? _mcawOtherAmount;
private DirtyValue<decimal?>? _mcawOtherDebtsAndObligationsAmount;
private DirtyValue<decimal?>? _mcawTotalFixedPaymentForPurchaseAmount;
private DirtyValue<decimal?>? _mcawTotalFixedPaymentForRefinanceAmount;
private DirtyValue<decimal?>? _mcawTotalFixedPaymentToIncome1Amount;
private DirtyValue<decimal?>? _mcawTotalFixedPaymentToIncome2Amount;
private DirtyValue<decimal?>? _mcawTotalMonthlyPaymentsAmount;
private DirtyValue<decimal?>? _mcawTotalMortgagePaymentAmount;
private DirtyValue<decimal?>? _monthlyExpenseComortSet;
private DirtyValue<decimal?>? _monthlyHousingExpenseAmount;
private DirtyValue<decimal?>? _monthlyInstallmentExpenseAmount;
private DirtyValue<decimal?>? _monthlyNegativeRealEstateAmount;
private DirtyValue<decimal?>? _monthlySecondHomeAmount;
private DirtyValue<string?>? _mortgageInsuranceAmount;
private DirtyValue<decimal?>? _netWorthAmount;
private DirtyList<OtherAsset>? _otherAssets;
private DirtyValue<decimal?>? _otherHousingExpenseAmount;
private DirtyList<OtherIncomeSource>? _otherIncomeSources;
private DirtyValue<decimal?>? _otherItemsDeducted;
private DirtyList<OtherLiability>? _otherLiabilities;
private DirtyValue<decimal?>? _otherMortgagePrincipalAndInterestAmount;
private DirtyValue<decimal?>? _otherTotalIncome;
private DirtyValue<StringEnumValue<PastCreditRecord>>? _pastCreditRecord;
private DirtyValue<decimal?>? _presentHousingExpComortSet;
private DirtyValue<decimal?>? _primaryResidenceComortSet;
private DirtyValue<StringEnumValue<PropertyUsageType>>? _propertyUsageType;
private DirtyValue<string?>? _proposedDuesAmount;
private DirtyValue<decimal?>? _proposedFirstMortgageAmount;
private DirtyValue<decimal?>? _proposedGroundRentAmount;
private DirtyValue<string?>? _proposedHazardInsuranceAmount;
private DirtyValue<string?>? _proposedMortgageInsuranceAmount;
private DirtyValue<decimal?>? _proposedOtherAmount;
private DirtyValue<decimal?>? _proposedOtherMortgagesAmount;
private DirtyValue<string?>? _proposedRealEstateTaxesAmount;
private DirtyList<ProvidedDocument>? _providedDocuments;
private DirtyValue<string?>? _realEstateTaxAmount;
private DirtyValue<decimal?>? _rentAmount;
private DirtyList<ReoProperty>? _reoProperties;
private DirtyValue<decimal?>? _reoTotalGrossRentalIncomeAmount;
private DirtyValue<decimal?>? _reoTotalMaintenanceAmount;
private DirtyValue<decimal?>? _reoTotalMarketValueAmount;
private DirtyValue<decimal?>? _reoTotalMortgagePaymentsAmount;
private DirtyValue<decimal?>? _reoTotalMortgagesAndLiensAmount;
private DirtyValue<int?>? _reoTotalNetRentalIncomeAmount;
private DirtyValue<DateTime?>? _rescissionDate;
private DirtyValue<DateTime?>? _rescissionNoteSignedDate;
private DirtyList<Residence>? _residences;
private DirtyValue<string?>? _respa6;
private DirtyList<SelfEmployedIncome>? _selfEmployedIncomes;
private DirtyValue<string?>? _sofDBorrCountry;
private DirtyValue<bool?>? _sofDBorrForeignAddressIndicator;
private DirtyValue<string?>? _sofDBorrowerAddress;
private DirtyValue<string?>? _sofDBorrowerAddressCity;
private DirtyValue<StringEnumValue<State>>? _sofDBorrowerAddressState;
private DirtyValue<StringEnumValue<SofDBorrowerAddressType>>? _sofDBorrowerAddressType;
private DirtyValue<string?>? _sofDBorrowerAddressZipcode;
private DirtyValue<string?>? _sofDCoBorrCountry;
private DirtyValue<bool?>? _sofDCoBorrForeignAddressIndicator;
private DirtyValue<string?>? _sofDCoBorrowerAddress;
private DirtyValue<string?>? _sofDCoBorrowerAddressCity;
private DirtyValue<StringEnumValue<State>>? _sofDCoBorrowerAddressState;
private DirtyValue<StringEnumValue<SofDBorrowerAddressType>>? _sofDCoBorrowerAddressType;
private DirtyValue<string?>? _sofDCoBorrowerAddressZipcode;
private DirtyValue<bool?>? _spouseIncomeConsider;
private DirtyList<Tax4506>? _tax4506s;
private DirtyValue<decimal?>? _topRatioPercent;
private DirtyValue<decimal?>? _totalAdditionalAssetsAmount;
private DirtyValue<decimal?>? _totalAdditionalLoansAmount;
private DirtyValue<decimal?>? _totalAdditionalOtherAssetsAmount;
private DirtyValue<decimal?>? _totalAppliedToDownpayment;
private DirtyValue<decimal?>? _totalAssetsAmount;
private DirtyValue<decimal?>? _totalBaseIncomeAmount;
private DirtyValue<decimal?>? _totalBonusAmount;
private DirtyValue<decimal?>? _totalCommissionsAmount;
private DirtyValue<decimal?>? _totalDeposit;
private DirtyValue<decimal?>? _totalDividendsInterestAmount;
private DirtyValue<decimal?>? _totalEmploymentAmount;
private DirtyValue<decimal?>? _totalFixedPaymentAmount;
private DirtyValue<decimal?>? _totalGrossMonthlyIncomeAmount;
private DirtyValue<decimal?>? _totalIncomeAmount;
private DirtyValue<decimal?>? _totalMonthlyPaymentAmount;
private DirtyValue<decimal?>? _totalMortgagesBalanceAmount;
private DirtyValue<decimal?>? _totalMortgagesMonthlyPaymentAmount;
private DirtyValue<decimal?>? _totalNetRentalIncomeAmount;
private DirtyValue<decimal?>? _totalOther1Amount;
private DirtyValue<decimal?>? _totalOther2Amount;
private DirtyValue<decimal?>? _totalOtherAssetsAmount;
private DirtyValue<decimal?>? _totalOvertimeAmount;
private DirtyValue<decimal?>? _totalPaymentsAmount;
private DirtyValue<decimal?>? _totalPrimaryHousingExpenseAmount;
private DirtyValue<decimal?>? _totalReoMarketValueAmount;
private DirtyValue<decimal?>? _totalURLA2020AssetsAmount;
private DirtyValue<decimal?>? _totalUserDefinedIncome;
private DirtyList<TQLReportInformation>? _tQLReports;
private DirtyValue<string?>? _transUnionAddress;
private DirtyValue<string?>? _transUnionCity;
private DirtyValue<string?>? _transUnionFax;
private DirtyValue<string?>? _transUnionModel;
private DirtyValue<string?>? _transUnionName;
private DirtyValue<string?>? _transUnionPhone;
private DirtyValue<string?>? _transUnionPostalCode;
private DirtyValue<string?>? _transUnionScoreRangeFrom;
private DirtyValue<string?>? _transUnionScoreRangeTo;
private DirtyValue<StringEnumValue<State>>? _transUnionState;
private DirtyValue<string?>? _transUnionWebsite;
private DirtyList<URLAAlternateName>? _uRLAAlternateNames;
private DirtyValue<decimal?>? _userDefinedIncome;
private DirtyValue<string?>? _userDefinedIncomeDescription;
private DirtyValue<StringEnumValue<YOrN>>? _vACreditStandards;
private DirtyValue<decimal?>? _vaSummarySpouseIncomeAmount;
private DirtyValue<decimal?>? _vaSummaryTotalMonthlyGrossIncomeAmount;
/// <summary>
/// Liabilities Alternate Acct # 1 [1735]
/// </summary>
public string? AccountNumber1 { get => _accountNumber1; set => SetField(ref _accountNumber1, value); }
/// <summary>
/// Liabilities Alternate Acct # 2 [1737]
/// </summary>
public string? AccountNumber2 { get => _accountNumber2; set => SetField(ref _accountNumber2, value); }
/// <summary>
/// Application AdditionalLoans
/// </summary>
[AllowNull]
public IList<AdditionalLoan> AdditionalLoans { get => GetField(ref _additionalLoans); set => SetField(ref _additionalLoans, value); }
/// <summary>
/// Underwriting All Other Pymts [1733]
/// </summary>
public decimal? AllOtherPaymentsAmount { get => _allOtherPaymentsAmount; set => SetField(ref _allOtherPaymentsAmount, value); }
/// <summary>
/// Application ApplicationId
/// </summary>
public string? ApplicationId { get => _applicationId; set => SetField(ref _applicationId, value); }
/// <summary>
/// Application ApplicationIndex
/// </summary>
public int? ApplicationIndex { get => _applicationIndex; set => SetField(ref _applicationIndex, value); }
/// <summary>
/// Fannie Mae Signature Date [MORNET.X68]
/// </summary>
public DateTime? ApplicationSignedDate { get => _applicationSignedDate; set => SetField(ref _applicationSignedDate, value); }
/// <summary>
/// Application Assets
/// </summary>
[AllowNull]
public IList<Asset> Assets { get => GetField(ref _assets); set => SetField(ref _assets, value); }
/// <summary>
/// FHA MCAW Assets Available [1094]
/// </summary>
public decimal? AssetsAvailableAmount { get => _assetsAvailableAmount; set => SetField(ref _assetsAvailableAmount, value); }
/// <summary>
/// Application ATRQMBorrower
/// </summary>
public ATRQMBorrower? ATRQMBorrower { get => _aTRQMBorrower; set => SetField(ref _aTRQMBorrower, value); }
/// <summary>
/// Application ATRQMBorrowers
/// </summary>
[AllowNull]
public IList<ATRQMBorrower> ATRQMBorrowers { get => GetField(ref _aTRQMBorrowers); set => SetField(ref _aTRQMBorrowers, value); }
/// <summary>
/// Application AUSTrackingLogs
/// </summary>
[AllowNull]
public IList<AUSTrackingLog> AUSTrackingLogs { get => GetField(ref _aUSTrackingLogs); set => SetField(ref _aUSTrackingLogs, value); }
/// <summary>
/// VA Bal Avail Family Support Guideline [1340]
/// </summary>
public decimal? BalanceAvailableFamilySupportGuideline { get => _balanceAvailableFamilySupportGuideline; set => SetField(ref _balanceAvailableFamilySupportGuideline, value); }
/// <summary>
/// Application Borrower
/// </summary>
[AllowNull]
public Borrower Borrower { get => GetField(ref _borrower); set => SetField(ref _borrower, value); }
/// <summary>
/// Borrower Pair ID [BORPAIRID]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? BorrowerPairId { get => _borrowerPairId; set => SetField(ref _borrowerPairId, value); }
/// <summary>
/// Trans Details Qual Ratio Bottom [742]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? BottomRatioPercent { get => _bottomRatioPercent; set => SetField(ref _bottomRatioPercent, value); }
/// <summary>
/// Income Total Deductions Spouse/Borr [1312]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? BrwCoBrwTotalTaxDeductions { get => _brwCoBrwTotalTaxDeductions; set => SetField(ref _brwCoBrwTotalTaxDeductions, value); }
/// <summary>
/// Correspondent Closing Disclosure Borrower Delivery Date [CORRESPONDENT.X145]
/// </summary>
public DateTime? ClosingDisclosureBorDeliveryDate { get => _closingDisclosureBorDeliveryDate; set => SetField(ref _closingDisclosureBorDeliveryDate, value); }
/// <summary>
/// Correspondent Closing Disclosure Received Date [CORRESPONDENT.X146]
/// </summary>
public DateTime? ClosingDisclosureBorReceivedDate { get => _closingDisclosureBorReceivedDate; set => SetField(ref _closingDisclosureBorReceivedDate, value); }
/// <summary>
/// Application Coborrower
/// </summary>
[AllowNull]
public Borrower Coborrower { get => GetField(ref _coborrower); set => SetField(ref _coborrower, value); }
/// <summary>
/// Liabilities Alternate Name 1 [206]
/// </summary>
public string? CreditAliasName1 { get => _creditAliasName1; set => SetField(ref _creditAliasName1, value); }
/// <summary>
/// Liabilities Alternate Name 2 [203]
/// </summary>
public string? CreditAliasName2 { get => _creditAliasName2; set => SetField(ref _creditAliasName2, value); }
/// <summary>
/// Liabilities Creditor Name 1 [1734]
/// </summary>
public string? CreditorName1 { get => _creditorName1; set => SetField(ref _creditorName1, value); }
/// <summary>
/// Liabilities Creditor Name 2 [1736]
/// </summary>
public string? CreditorName2 { get => _creditorName2; set => SetField(ref _creditorName2, value); }
/// <summary>
/// Trans Details Credit Rpt Ref # [300]
/// </summary>
public string? CreditReportReferenceIdentifier { get => _creditReportReferenceIdentifier; set => SetField(ref _creditReportReferenceIdentifier, value); }
/// <summary>
/// Application Employment
/// </summary>
[AllowNull]
public IList<Employment> Employment { get => GetField(ref _employment); set => SetField(ref _employment, value); }
/// <summary>
/// Application EntityDeleted
/// </summary>
public bool? EntityDeleted { get => _entityDeleted; set => SetField(ref _entityDeleted, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co Addr [DISCLOSURE.X42]
/// </summary>
public string? EquifaxAddress { get => _equifaxAddress; set => SetField(ref _equifaxAddress, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co City [DISCLOSURE.X43]
/// </summary>
public string? EquifaxCity { get => _equifaxCity; set => SetField(ref _equifaxCity, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co Fax [DISCLOSURE.X47]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? EquifaxFax { get => _equifaxFax; set => SetField(ref _equifaxFax, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co Model [DISCLOSURE.X48]
/// </summary>
public string? EquifaxModel { get => _equifaxModel; set => SetField(ref _equifaxModel, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co Name [DISCLOSURE.X41]
/// </summary>
public string? EquifaxName { get => _equifaxName; set => SetField(ref _equifaxName, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co Phone [DISCLOSURE.X46]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? EquifaxPhone { get => _equifaxPhone; set => SetField(ref _equifaxPhone, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co Zip [DISCLOSURE.X45]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)]
public string? EquifaxPostalCode { get => _equifaxPostalCode; set => SetField(ref _equifaxPostalCode, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co Range Scores From [DISCLOSURE.X49]
/// </summary>
public string? EquifaxScoreRangeFrom { get => _equifaxScoreRangeFrom; set => SetField(ref _equifaxScoreRangeFrom, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co Range Scores To [DISCLOSURE.X50]
/// </summary>
public string? EquifaxScoreRangeTo { get => _equifaxScoreRangeTo; set => SetField(ref _equifaxScoreRangeTo, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co State [DISCLOSURE.X44]
/// </summary>
public StringEnumValue<State> EquifaxState { get => _equifaxState; set => SetField(ref _equifaxState, value); }
/// <summary>
/// Disclosure Cred Bureau 3 Co Website [DISCLOSURE.X640]
/// </summary>
public string? EquifaxWebsite { get => _equifaxWebsite; set => SetField(ref _equifaxWebsite, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co Addr [DISCLOSURE.X2]
/// </summary>
public string? ExperianAddress { get => _experianAddress; set => SetField(ref _experianAddress, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co City [DISCLOSURE.X3]
/// </summary>
public string? ExperianCity { get => _experianCity; set => SetField(ref _experianCity, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co Fax [DISCLOSURE.X7]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? ExperianFax { get => _experianFax; set => SetField(ref _experianFax, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co Model Used [DISCLOSURE.X8]
/// </summary>
public string? ExperianModel { get => _experianModel; set => SetField(ref _experianModel, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co Name [DISCLOSURE.X1]
/// </summary>
public string? ExperianName { get => _experianName; set => SetField(ref _experianName, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co Phone [DISCLOSURE.X6]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? ExperianPhone { get => _experianPhone; set => SetField(ref _experianPhone, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co Zip [DISCLOSURE.X5]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)]
public string? ExperianPostalCode { get => _experianPostalCode; set => SetField(ref _experianPostalCode, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co Range Scores From [DISCLOSURE.X9]
/// </summary>
public string? ExperianScoreRangeFrom { get => _experianScoreRangeFrom; set => SetField(ref _experianScoreRangeFrom, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co Range Scores To [DISCLOSURE.X10]
/// </summary>
public string? ExperianScoreRangeTo { get => _experianScoreRangeTo; set => SetField(ref _experianScoreRangeTo, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co State [DISCLOSURE.X4]
/// </summary>
public StringEnumValue<State> ExperianState { get => _experianState; set => SetField(ref _experianState, value); }
/// <summary>
/// Disclosure Cred Bureau 1 Co Website [DISCLOSURE.X638]
/// </summary>
public string? ExperianWebsite { get => _experianWebsite; set => SetField(ref _experianWebsite, value); }
/// <summary>
/// VA Debt-to-Income Ratio [1341]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? FhaVaDebtIncomeRatio { get => _fhaVaDebtIncomeRatio; set => SetField(ref _fhaVaDebtIncomeRatio, value); }
/// <summary>
/// Income Total Residual Income Spouse/Borr [1325]
/// </summary>
public decimal? FhaVaFamilySupportAmount { get => _fhaVaFamilySupportAmount; set => SetField(ref _fhaVaFamilySupportAmount, value); }
/// <summary>
/// Expenses Total Mo Shelter Exp Est [1349]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? FhaVaTotalEstimatedMonthlyShelterExpenseAmount { get => _fhaVaTotalEstimatedMonthlyShelterExpenseAmount; set => SetField(ref _fhaVaTotalEstimatedMonthlyShelterExpenseAmount, value); }
/// <summary>
/// Income Total Net Effective Income [1323]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? FhaVaTotalNetEffectiveIncomeAmount { get => _fhaVaTotalNetEffectiveIncomeAmount; set => SetField(ref _fhaVaTotalNetEffectiveIncomeAmount, value); }
/// <summary>
/// Income Total Net Spouse/Borr [1321]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? FhaVaTotalNetIncomeAmount { get => _fhaVaTotalNetIncomeAmount; set => SetField(ref _fhaVaTotalNetIncomeAmount, value); }
/// <summary>
/// Income Net Take Home Pay Spouse/Borr [1315]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? FhaVaTotalNetTakeHomePayAmount { get => _fhaVaTotalNetTakeHomePayAmount; set => SetField(ref _fhaVaTotalNetTakeHomePayAmount, value); }
/// <summary>
/// Income Other Net Spouse/Borr [1318]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? FhaVaTotalOtherNetIncome { get => _fhaVaTotalOtherNetIncome; set => SetField(ref _fhaVaTotalOtherNetIncome, value); }
/// <summary>
/// Expenses Present Mtg Pymt [120]
/// </summary>
public decimal? FirstMortgagePrincipalAndInterestAmount { get => _firstMortgagePrincipalAndInterestAmount; set => SetField(ref _firstMortgagePrincipalAndInterestAmount, value); }
/// <summary>
/// Freddie Mac Credit Ref # [CASASRN.X198]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? FreddieMacCreditReportReferenceIdentifier { get => _freddieMacCreditReportReferenceIdentifier; set => SetField(ref _freddieMacCreditReportReferenceIdentifier, value); }
/// <summary>
/// Freddie Mac Additional Data - Occupancy Debt Ratio [CASASRN.X202]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? FreddieMacOccupantDebtRatio { get => _freddieMacOccupantDebtRatio; set => SetField(ref _freddieMacOccupantDebtRatio, value); }
/// <summary>
/// Freddie Mac Additional Data - Occupancy Housing Ratio [CASASRN.X201]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? FreddieMacOccupantHousingRatio { get => _freddieMacOccupantHousingRatio; set => SetField(ref _freddieMacOccupantHousingRatio, value); }
/// <summary>
/// Trans Details Qual Ratio Debt-to-Housing [1539]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? FreDebtToHousingGapRatio { get => _freDebtToHousingGapRatio; set => SetField(ref _freDebtToHousingGapRatio, value); }
/// <summary>
/// Application GiftsGrants
/// </summary>
[AllowNull]
public IList<GiftGrant> GiftsGrants { get => GetField(ref _giftsGrants); set => SetField(ref _giftsGrants, value); }
/// <summary>
/// Income Total Base Income (Borr/Co-Borr) [273]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? GrossBaseIncomeAmount { get => _grossBaseIncomeAmount; set => SetField(ref _grossBaseIncomeAmount, value); }
/// <summary>
/// Underwriting Co-Mortgagor Income [1374]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? GrossIncomeForComortSet { get => _grossIncomeForComortSet; set => SetField(ref _grossIncomeForComortSet, value); }
/// <summary>
/// Underwriting Negative Cash Flow [462]
/// </summary>
public decimal? GrossNegativeCashFlow { get => _grossNegativeCashFlow; set => SetField(ref _grossNegativeCashFlow, value); }
/// <summary>
/// Income Total Other Income (Borr/Co-Borr) [1168]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? GrossOtherIncomeAmount { get => _grossOtherIncomeAmount; set => SetField(ref _grossOtherIncomeAmount, value); }
/// <summary>
/// Income Total Positive Cash Flow (Borr/Co-Borr) [1171]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? GrossPositiveCashFlow { get => _grossPositiveCashFlow; set => SetField(ref _grossPositiveCashFlow, value); }
/// <summary>
/// Expenses Present Haz Ins [122]
/// </summary>
public string? HazardInsuranceAmount { get => _hazardInsuranceAmount; set => SetField(ref _hazardInsuranceAmount, value); }
/// <summary>
/// Expenses Present HOA [125]
/// </summary>
public string? HomeownersAssociationDuesAndCondoFeesAmount { get => _homeownersAssociationDuesAndCondoFeesAmount; set => SetField(ref _homeownersAssociationDuesAndCondoFeesAmount, value); }
/// <summary>
/// HUD Property Improve Auto 1 Lienholder [CAPIAP.X134]
/// </summary>
public string? HudAutoLienHolderName1 { get => _hudAutoLienHolderName1; set => SetField(ref _hudAutoLienHolderName1, value); }
/// <summary>
/// HUD Property Improve Auto 2 Lienholder [CAPIAP.X139]
/// </summary>
public string? HudAutoLienHolderName2 { get => _hudAutoLienHolderName2; set => SetField(ref _hudAutoLienHolderName2, value); }
/// <summary>
/// HUD Property Improve Auto 1 Loan Amt [CAPIAP.X136]
/// </summary>
public decimal? HudAutoLoanAmount1 { get => _hudAutoLoanAmount1; set => SetField(ref _hudAutoLoanAmount1, value); }
/// <summary>
/// HUD Property Improve Auto 2 Loan Amt [CAPIAP.X141]
/// </summary>
public decimal? HudAutoLoanAmount2 { get => _hudAutoLoanAmount2; set => SetField(ref _hudAutoLoanAmount2, value); }
/// <summary>
/// HUD Property Improve Auto 1 Mo Pymt [CAPIAP.X138]
/// </summary>
public decimal? HudAutoMonthlyPayment1 { get => _hudAutoMonthlyPayment1; set => SetField(ref _hudAutoMonthlyPayment1, value); }
/// <summary>
/// HUD Property Improve Auto 2 Mo Pymt [CAPIAP.X143]
/// </summary>
public decimal? HudAutoMonthlyPayment2 { get => _hudAutoMonthlyPayment2; set => SetField(ref _hudAutoMonthlyPayment2, value); }
/// <summary>
/// HUD Property Improve Auto 1 Present Bal [CAPIAP.X137]
/// </summary>
public decimal? HudAutoPresentBalance1 { get => _hudAutoPresentBalance1; set => SetField(ref _hudAutoPresentBalance1, value); }
/// <summary>
/// HUD Property Improve Auto 2 Present Bal [CAPIAP.X142]
/// </summary>
public decimal? HudAutoPresentBalance2 { get => _hudAutoPresentBalance2; set => SetField(ref _hudAutoPresentBalance2, value); }
/// <summary>
/// HUD Property Improve Auto 1 Yr/Make [CAPIAP.X135]
/// </summary>
public string? HudAutoYearAndMake1 { get => _hudAutoYearAndMake1; set => SetField(ref _hudAutoYearAndMake1, value); }
/// <summary>
/// HUD Property Improve Auto 2 Yr/Make [CAPIAP.X140]
/// </summary>
public string? HudAutoYearAndMake2 { get => _hudAutoYearAndMake2; set => SetField(ref _hudAutoYearAndMake2, value); }
/// <summary>
/// HUD Property Improve Liability 1 Loan Amt [CAPIAP.X25]
/// </summary>
public decimal? HudLoanAmount1 { get => _hudLoanAmount1; set => SetField(ref _hudLoanAmount1, value); }
/// <summary>
/// HUD Property Improve Liability 10 Loan Amt [CAPIAP.X38]
/// </summary>
public decimal? HudLoanAmount10 { get => _hudLoanAmount10; set => SetField(ref _hudLoanAmount10, value); }
/// <summary>
/// HUD Property Improve Liability 11 Loan Amt [CAPIAP.X39]
/// </summary>
public decimal? HudLoanAmount11 { get => _hudLoanAmount11; set => SetField(ref _hudLoanAmount11, value); }
/// <summary>
/// HUD Property Improve Liability 2 Loan Amt [CAPIAP.X26]
/// </summary>
public decimal? HudLoanAmount2 { get => _hudLoanAmount2; set => SetField(ref _hudLoanAmount2, value); }
/// <summary>
/// HUD Property Improve Liability 3 Loan Amt [CAPIAP.X31]
/// </summary>
public decimal? HudLoanAmount3 { get => _hudLoanAmount3; set => SetField(ref _hudLoanAmount3, value); }
/// <summary>
/// HUD Property Improve Liability 4 Loan Amt [CAPIAP.X32]
/// </summary>
public decimal? HudLoanAmount4 { get => _hudLoanAmount4; set => SetField(ref _hudLoanAmount4, value); }
/// <summary>
/// HUD Property Improve Liability 5 Loan Amt [CAPIAP.X33]
/// </summary>
public decimal? HudLoanAmount5 { get => _hudLoanAmount5; set => SetField(ref _hudLoanAmount5, value); }
/// <summary>
/// HUD Property Improve Liability 6 Loan Amt [CAPIAP.X34]
/// </summary>
public decimal? HudLoanAmount6 { get => _hudLoanAmount6; set => SetField(ref _hudLoanAmount6, value); }
/// <summary>
/// HUD Property Improve Liability 7 Loan Amt [CAPIAP.X35]
/// </summary>
public decimal? HudLoanAmount7 { get => _hudLoanAmount7; set => SetField(ref _hudLoanAmount7, value); }
/// <summary>
/// HUD Property Improve Liability 8 Loan Amt [CAPIAP.X36]
/// </summary>
public decimal? HudLoanAmount8 { get => _hudLoanAmount8; set => SetField(ref _hudLoanAmount8, value); }
/// <summary>
/// HUD Property Improve Liability 9 Loan Amt [CAPIAP.X37]
/// </summary>
public decimal? HudLoanAmount9 { get => _hudLoanAmount9; set => SetField(ref _hudLoanAmount9, value); }
/// <summary>
/// HUD Property Improve RE 1 FHA Insured [CAPIAP.X28]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"FHA Insured\"}")]
public bool? HudRealEstateFhaInsured1 { get => _hudRealEstateFhaInsured1; set => SetField(ref _hudRealEstateFhaInsured1, value); }
/// <summary>
/// HUD Property Improve RE 2 FHA Insured [CAPIAP.X30]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"FHA Insured\"}")]
public bool? HudRealEstateFhaInsured2 { get => _hudRealEstateFhaInsured2; set => SetField(ref _hudRealEstateFhaInsured2, value); }
/// <summary>
/// HUD Property Improve RE 1 Lienholder [CAPIAP.X148]
/// </summary>
public string? HudRealEstateLienHolder1 { get => _hudRealEstateLienHolder1; set => SetField(ref _hudRealEstateLienHolder1, value); }
/// <summary>
/// HUD Property Improve RE 2 Lienholder [CAPIAP.X149]
/// </summary>
public string? HudRealEstateLienHolder2 { get => _hudRealEstateLienHolder2; set => SetField(ref _hudRealEstateLienHolder2, value); }
/// <summary>
/// HUD Property Improve RE 1 Loan Amt [CAPIAP.X27]
/// </summary>
public decimal? HudRealEstateLoanAmount1 { get => _hudRealEstateLoanAmount1; set => SetField(ref _hudRealEstateLoanAmount1, value); }
/// <summary>
/// HUD Property Improve RE 2 Loan Amt [CAPIAP.X29]
/// </summary>
public decimal? HudRealEstateLoanAmount2 { get => _hudRealEstateLoanAmount2; set => SetField(ref _hudRealEstateLoanAmount2, value); }
/// <summary>
/// HUD Property Improve RE 1 Mo Pymt [CAPIAP.X151]
/// </summary>
public decimal? HudRealEstateMonthlyPayment1 { get => _hudRealEstateMonthlyPayment1; set => SetField(ref _hudRealEstateMonthlyPayment1, value); }
/// <summary>
/// HUD Property Improve RE 2 Mo Pymt [CAPIAP.X153]
/// </summary>
public decimal? HudRealEstateMonthlyPayment2 { get => _hudRealEstateMonthlyPayment2; set => SetField(ref _hudRealEstateMonthlyPayment2, value); }
/// <summary>
/// HUD Property Improve RE 1 Present Bal [CAPIAP.X150]
/// </summary>
public decimal? HudRealEstatePresentBalance1 { get => _hudRealEstatePresentBalance1; set => SetField(ref _hudRealEstatePresentBalance1, value); }
/// <summary>
/// HUD Property Improve RE 2 Present Bal [CAPIAP.X152]
/// </summary>
public decimal? HudRealEstatePresentBalance2 { get => _hudRealEstatePresentBalance2; set => SetField(ref _hudRealEstatePresentBalance2, value); }
/// <summary>
/// Application Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Application Income
/// </summary>
[AllowNull]
public IList<Income> Income { get => GetField(ref _income); set => SetField(ref _income, value); }
/// <summary>
/// Trans Details Income of Spouse will not be used [35]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"The income/assets of the Borrower's spouse will not be used..\"}")]
public bool? IncomeOfBorrowersSpouseUsedIndicator { get => _incomeOfBorrowersSpouseUsedIndicator; set => SetField(ref _incomeOfBorrowersSpouseUsedIndicator, value); }
/// <summary>
/// Trans Details Income of Other will be used [307]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"The income/assets of a person other than Borrower will be used...\"}")]
public bool? IncomeOtherThanBorrowerUsedIndicator { get => _incomeOtherThanBorrowerUsedIndicator; set => SetField(ref _incomeOtherThanBorrowerUsedIndicator, value); }
/// <summary>
/// Assets/Liabilities Completed Jointly/Not Jointly [181]
/// </summary>
public bool? JointAssetLiabilityReportingIndicator { get => _jointAssetLiabilityReportingIndicator; set => SetField(ref _jointAssetLiabilityReportingIndicator, value); }
/// <summary>
/// Application LastModified
/// </summary>
public string? LastModified { get => _lastModified; set => SetField(ref _lastModified, value); }
/// <summary>
/// Application Liabilities
/// </summary>
[AllowNull]
public IList<Liability> Liabilities { get => GetField(ref _liabilities); set => SetField(ref _liabilities, value); }
/// <summary>
/// Assets Co-Borr Liquid Assets [267]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? LiquidAssetsComortSet { get => _liquidAssetsComortSet; set => SetField(ref _liquidAssetsComortSet, value); }
/// <summary>
/// Application LoanAmount
/// </summary>
public string? LoanAmount { get => _loanAmount; set => SetField(ref _loanAmount, value); }
/// <summary>
/// Correspondent Loan Estimate Delivery Date [CORRESPONDENT.X243]
/// </summary>
public DateTime? LoanEstimateDeliveryDate { get => _loanEstimateDeliveryDate; set => SetField(ref _loanEstimateDeliveryDate, value); }
/// <summary>
/// Application LoanOfficerId
/// </summary>
public string? LoanOfficerId { get => _loanOfficerId; set => SetField(ref _loanOfficerId, value); }
/// <summary>
/// Application LoanOfficerName
/// </summary>
public string? LoanOfficerName { get => _loanOfficerName; set => SetField(ref _loanOfficerName, value); }
/// <summary>
/// FHA MCAW Borr Other Mo Income [936]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? McawBorrowerOtherMonthlyIncomeAmount { get => _mcawBorrowerOtherMonthlyIncomeAmount; set => SetField(ref _mcawBorrowerOtherMonthlyIncomeAmount, value); }
/// <summary>
/// FHA MCAW Co-Borr Other Mo Income [938]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? McawCoborrowerOtherMonthlyIncomeAmount { get => _mcawCoborrowerOtherMonthlyIncomeAmount; set => SetField(ref _mcawCoborrowerOtherMonthlyIncomeAmount, value); }
/// <summary>
/// FHA MCAW Total Gross Mo Income [1761]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? McawGrossMonthlyIncomeAmount { get => _mcawGrossMonthlyIncomeAmount; set => SetField(ref _mcawGrossMonthlyIncomeAmount, value); }
/// <summary>
/// FHA MCAW Mtg Pymt-to-Income Ratio [MCAWPUR.X22]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? McawMortgagePaymentToIncome1Amount { get => _mcawMortgagePaymentToIncome1Amount; set => SetField(ref _mcawMortgagePaymentToIncome1Amount, value); }
/// <summary>
/// FHA MCAW Ratio Mtg Pymt-to-Income [GMCAW.X7]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? McawMortgagePaymentToIncome2Amount { get => _mcawMortgagePaymentToIncome2Amount; set => SetField(ref _mcawMortgagePaymentToIncome2Amount, value); }
/// <summary>
/// FHA MCAW Liabilities Other [1161]
/// </summary>
public decimal? McawOtherAmount { get => _mcawOtherAmount; set => SetField(ref _mcawOtherAmount, value); }
/// <summary>
/// FHA MCAW Liabilities Unpaid Bal [1163]
/// </summary>
public decimal? McawOtherDebtsAndObligationsAmount { get => _mcawOtherDebtsAndObligationsAmount; set => SetField(ref _mcawOtherDebtsAndObligationsAmount, value); }
/// <summary>
/// FHA MCAW Total Fixed Pymt [MCAWPUR.X24]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? McawTotalFixedPaymentForPurchaseAmount { get => _mcawTotalFixedPaymentForPurchaseAmount; set => SetField(ref _mcawTotalFixedPaymentForPurchaseAmount, value); }
/// <summary>
/// FHA MCAW Total Fixed Pymt [GMCAW.X9]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? McawTotalFixedPaymentForRefinanceAmount { get => _mcawTotalFixedPaymentForRefinanceAmount; set => SetField(ref _mcawTotalFixedPaymentForRefinanceAmount, value); }
/// <summary>
/// FHA MCAW Total Fixed Pymt-to-Income Ratio [MCAWPUR.X23]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? McawTotalFixedPaymentToIncome1Amount { get => _mcawTotalFixedPaymentToIncome1Amount; set => SetField(ref _mcawTotalFixedPaymentToIncome1Amount, value); }
/// <summary>
/// FHA MCAW Ratio Total Fixed Pymt-to-Income [GMCAW.X8]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? McawTotalFixedPaymentToIncome2Amount { get => _mcawTotalFixedPaymentToIncome2Amount; set => SetField(ref _mcawTotalFixedPaymentToIncome2Amount, value); }
/// <summary>
/// FHA MCAW Liabilities Total Mo Pymt [1150]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? McawTotalMonthlyPaymentsAmount { get => _mcawTotalMonthlyPaymentsAmount; set => SetField(ref _mcawTotalMonthlyPaymentsAmount, value); }
/// <summary>
/// FHA MCAW Total Mtg Pymt [739]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? McawTotalMortgagePaymentAmount { get => _mcawTotalMortgagePaymentAmount; set => SetField(ref _mcawTotalMortgagePaymentAmount, value); }
/// <summary>
/// Underwriting Co-Mortgagor [1384]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MonthlyExpenseComortSet { get => _monthlyExpenseComortSet; set => SetField(ref _monthlyExpenseComortSet, value); }
/// <summary>
/// Expenses Total Housing Expense [1809]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MonthlyHousingExpenseAmount { get => _monthlyHousingExpenseAmount; set => SetField(ref _monthlyHousingExpenseAmount, value); }
/// <summary>
/// Expenses Total Mo Installment Exp [382]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MonthlyInstallmentExpenseAmount { get => _monthlyInstallmentExpenseAmount; set => SetField(ref _monthlyInstallmentExpenseAmount, value); }
/// <summary>
/// Expenses Negative Real Estate [LOANSUB.X1]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MonthlyNegativeRealEstateAmount { get => _monthlyNegativeRealEstateAmount; set => SetField(ref _monthlyNegativeRealEstateAmount, value); }
/// <summary>
/// Expenses 2nd/Vacation Home [1476]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MonthlySecondHomeAmount { get => _monthlySecondHomeAmount; set => SetField(ref _monthlySecondHomeAmount, value); }
/// <summary>
/// Expenses Present MTG Ins [124]
/// </summary>
public string? MortgageInsuranceAmount { get => _mortgageInsuranceAmount; set => SetField(ref _mortgageInsuranceAmount, value); }
/// <summary>
/// Liabilities Net Worth [734]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? NetWorthAmount { get => _netWorthAmount; set => SetField(ref _netWorthAmount, value); }
/// <summary>
/// Application OtherAssets
/// </summary>
[AllowNull]
public IList<OtherAsset> OtherAssets { get => GetField(ref _otherAssets); set => SetField(ref _otherAssets, value); }
/// <summary>
/// Expenses Present Other Housing [126]
/// </summary>
public decimal? OtherHousingExpenseAmount { get => _otherHousingExpenseAmount; set => SetField(ref _otherHousingExpenseAmount, value); }
/// <summary>
/// Application OtherIncomeSources
/// </summary>
[AllowNull]
public IList<OtherIncomeSource> OtherIncomeSources { get => GetField(ref _otherIncomeSources); set => SetField(ref _otherIncomeSources, value); }
/// <summary>
/// Income Deductions Other Items Deducted [198]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? OtherItemsDeducted { get => _otherItemsDeducted; set => SetField(ref _otherItemsDeducted, value); }
/// <summary>
/// Application OtherLiabilities
/// </summary>
[AllowNull]
public IList<OtherLiability> OtherLiabilities { get => GetField(ref _otherLiabilities); set => SetField(ref _otherLiabilities, value); }
/// <summary>
/// Expenses Present Other Pymt [121]
/// </summary>
public decimal? OtherMortgagePrincipalAndInterestAmount { get => _otherMortgagePrincipalAndInterestAmount; set => SetField(ref _otherMortgagePrincipalAndInterestAmount, value); }
/// <summary>
/// Borr Other Total Income [URLA.X44]
/// </summary>
public decimal? OtherTotalIncome { get => _otherTotalIncome; set => SetField(ref _otherTotalIncome, value); }
/// <summary>
/// VA Past Credit Record [1326]
/// </summary>
public StringEnumValue<PastCreditRecord> PastCreditRecord { get => _pastCreditRecord; set => SetField(ref _pastCreditRecord, value); }
/// <summary>
/// Expenses Co-Borr Present Mo Hous Exp [268]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? PresentHousingExpComortSet { get => _presentHousingExpComortSet; set => SetField(ref _presentHousingExpComortSet, value); }
/// <summary>
/// Underwriting Co-Mortgagor Primary Exp [1379]
/// </summary>
public decimal? PrimaryResidenceComortSet { get => _primaryResidenceComortSet; set => SetField(ref _primaryResidenceComortSet, value); }
/// <summary>
/// Subject Property Occupancy Status [1811]
/// </summary>
public StringEnumValue<PropertyUsageType> PropertyUsageType { get => _propertyUsageType; set => SetField(ref _propertyUsageType, value); }
/// <summary>
/// Underwriting HOA Fees [1729]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ProposedDuesAmount { get => _proposedDuesAmount; set => SetField(ref _proposedDuesAmount, value); }
/// <summary>
/// Underwriting First Mtg P&I [1724]
/// </summary>
public decimal? ProposedFirstMortgageAmount { get => _proposedFirstMortgageAmount; set => SetField(ref _proposedFirstMortgageAmount, value); }
/// <summary>
/// Underwriting Rent [1723]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? ProposedGroundRentAmount { get => _proposedGroundRentAmount; set => SetField(ref _proposedGroundRentAmount, value); }
/// <summary>
/// Underwriting Hazard Ins [1726]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ProposedHazardInsuranceAmount { get => _proposedHazardInsuranceAmount; set => SetField(ref _proposedHazardInsuranceAmount, value); }
/// <summary>
/// Insurance Mtg Ins Mo Pymt [1728]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ProposedMortgageInsuranceAmount { get => _proposedMortgageInsuranceAmount; set => SetField(ref _proposedMortgageInsuranceAmount, value); }
/// <summary>
/// Underwriting Other Fees [1730]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? ProposedOtherAmount { get => _proposedOtherAmount; set => SetField(ref _proposedOtherAmount, value); }
/// <summary>
/// Underwriting Second Mtg P&I [1725]
/// </summary>
public decimal? ProposedOtherMortgagesAmount { get => _proposedOtherMortgagesAmount; set => SetField(ref _proposedOtherMortgagesAmount, value); }
/// <summary>
/// Underwriting Taxes [1727]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ProposedRealEstateTaxesAmount { get => _proposedRealEstateTaxesAmount; set => SetField(ref _proposedRealEstateTaxesAmount, value); }
/// <summary>
/// Application ProvidedDocuments
/// </summary>
[AllowNull]
public IList<ProvidedDocument> ProvidedDocuments { get => GetField(ref _providedDocuments); set => SetField(ref _providedDocuments, value); }
/// <summary>
/// Expenses Present Taxes [123]
/// </summary>
public string? RealEstateTaxAmount { get => _realEstateTaxAmount; set => SetField(ref _realEstateTaxAmount, value); }
/// <summary>
/// Expenses Present Rent [119]
/// </summary>
public decimal? RentAmount { get => _rentAmount; set => SetField(ref _rentAmount, value); }
/// <summary>
/// Application ReoProperties
/// </summary>
[AllowNull]
public IList<ReoProperty> ReoProperties { get => GetField(ref _reoProperties); set => SetField(ref _reoProperties, value); }
/// <summary>
/// Income Total Gross Rent Income [921]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? ReoTotalGrossRentalIncomeAmount { get => _reoTotalGrossRentalIncomeAmount; set => SetField(ref _reoTotalGrossRentalIncomeAmount, value); }
/// <summary>
/// Income Total Ins/Tax/Exp Income [923]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? ReoTotalMaintenanceAmount { get => _reoTotalMaintenanceAmount; set => SetField(ref _reoTotalMaintenanceAmount, value); }
/// <summary>
/// Assets Real Estate Owned [919]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? ReoTotalMarketValueAmount { get => _reoTotalMarketValueAmount; set => SetField(ref _reoTotalMarketValueAmount, value); }
/// <summary>
/// Income Total Mortgage Pymts Income [922]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? ReoTotalMortgagePaymentsAmount { get => _reoTotalMortgagePaymentsAmount; set => SetField(ref _reoTotalMortgagePaymentsAmount, value); }
/// <summary>
/// Income Total Amt of Mortgages Income [920]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? ReoTotalMortgagesAndLiensAmount { get => _reoTotalMortgagesAndLiensAmount; set => SetField(ref _reoTotalMortgagesAndLiensAmount, value); }
/// <summary>
/// Income Total Net Rental Income [924]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? ReoTotalNetRentalIncomeAmount { get => _reoTotalNetRentalIncomeAmount; set => SetField(ref _reoTotalNetRentalIncomeAmount, value); }
/// <summary>
/// Correspondent Rescission Date [CORRESPONDENT.X316]
/// </summary>
public DateTime? RescissionDate { get => _rescissionDate; set => SetField(ref _rescissionDate, value); }
/// <summary>
/// Correspondent Rescission Note Signed Date [CORRESPONDENT.X317]
/// </summary>
public DateTime? RescissionNoteSignedDate { get => _rescissionNoteSignedDate; set => SetField(ref _rescissionNoteSignedDate, value); }
/// <summary>
/// Application Residences
/// </summary>
[AllowNull]
public IList<Residence> Residences { get => GetField(ref _residences); set => SetField(ref _residences, value); }
/// <summary>
/// Application Respa6
/// </summary>
public string? Respa6 { get => _respa6; set => SetField(ref _respa6, value); }
/// <summary>
/// Application SelfEmployedIncomes
/// </summary>
[AllowNull]
public IList<SelfEmployedIncome> SelfEmployedIncomes { get => GetField(ref _selfEmployedIncomes); set => SetField(ref _selfEmployedIncomes, value); }
/// <summary>
/// Denial Info - Borrower Country [DENIAL.X98]
/// </summary>
public string? SofDBorrCountry { get => _sofDBorrCountry; set => SetField(ref _sofDBorrCountry, value); }
/// <summary>
/// Denial Info - Borrower Foreign Address Indicator [DENIAL.X97]
/// </summary>
public bool? SofDBorrForeignAddressIndicator { get => _sofDBorrForeignAddressIndicator; set => SetField(ref _sofDBorrForeignAddressIndicator, value); }
/// <summary>
/// Denial Discl Info - Borrower Address [DENIAL.X82]
/// </summary>
public string? SofDBorrowerAddress { get => _sofDBorrowerAddress; set => SetField(ref _sofDBorrowerAddress, value); }
/// <summary>
/// Denial Discl Info - Borrower Address - City [DENIAL.X83]
/// </summary>
public string? SofDBorrowerAddressCity { get => _sofDBorrowerAddressCity; set => SetField(ref _sofDBorrowerAddressCity, value); }
/// <summary>
/// Denial Discl Info - Borrower Address - State [DENIAL.X84]
/// </summary>
public StringEnumValue<State> SofDBorrowerAddressState { get => _sofDBorrowerAddressState; set => SetField(ref _sofDBorrowerAddressState, value); }
/// <summary>
/// Denial Discl Info - Borrower Address Type [DENIAL.X81]
/// </summary>
public StringEnumValue<SofDBorrowerAddressType> SofDBorrowerAddressType { get => _sofDBorrowerAddressType; set => SetField(ref _sofDBorrowerAddressType, value); }
/// <summary>
/// Denial Discl Info - Borrower Address - Zipcode [DENIAL.X85]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)]
public string? SofDBorrowerAddressZipcode { get => _sofDBorrowerAddressZipcode; set => SetField(ref _sofDBorrowerAddressZipcode, value); }
/// <summary>
/// Denial Info - Coborrower Country [DENIAL.X100]
/// </summary>
public string? SofDCoBorrCountry { get => _sofDCoBorrCountry; set => SetField(ref _sofDCoBorrCountry, value); }
/// <summary>
/// Denial Info - Coborrower Foreign Address Indicator [DENIAL.X99]
/// </summary>
public bool? SofDCoBorrForeignAddressIndicator { get => _sofDCoBorrForeignAddressIndicator; set => SetField(ref _sofDCoBorrForeignAddressIndicator, value); }
/// <summary>
/// Denial Discl Info - Coborrower Address [DENIAL.X87]
/// </summary>
public string? SofDCoBorrowerAddress { get => _sofDCoBorrowerAddress; set => SetField(ref _sofDCoBorrowerAddress, value); }
/// <summary>
/// Denial Discl Info - Coborrower Address - City [DENIAL.X88]
/// </summary>
public string? SofDCoBorrowerAddressCity { get => _sofDCoBorrowerAddressCity; set => SetField(ref _sofDCoBorrowerAddressCity, value); }
/// <summary>
/// Denial Discl Info - Coborrower Address - State [DENIAL.X89]
/// </summary>
public StringEnumValue<State> SofDCoBorrowerAddressState { get => _sofDCoBorrowerAddressState; set => SetField(ref _sofDCoBorrowerAddressState, value); }
/// <summary>
/// Denial Discl Info - Coborrower Address Type [DENIAL.X86]
/// </summary>
public StringEnumValue<SofDBorrowerAddressType> SofDCoBorrowerAddressType { get => _sofDCoBorrowerAddressType; set => SetField(ref _sofDCoBorrowerAddressType, value); }
/// <summary>
/// Denial Discl Info - Coborrower Address - Zipcode [DENIAL.X90]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)]
public string? SofDCoBorrowerAddressZipcode { get => _sofDCoBorrowerAddressZipcode; set => SetField(ref _sofDCoBorrowerAddressZipcode, value); }
/// <summary>
/// VA Veteran Income Consider Spouse Income [1006]
/// </summary>
public bool? SpouseIncomeConsider { get => _spouseIncomeConsider; set => SetField(ref _spouseIncomeConsider, value); }
/// <summary>
/// Application Tax4506s
/// </summary>
[AllowNull]
public IList<Tax4506> Tax4506s { get => GetField(ref _tax4506s); set => SetField(ref _tax4506s, value); }
/// <summary>
/// Trans Details Qual Ratio Top [740]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? TopRatioPercent { get => _topRatioPercent; set => SetField(ref _topRatioPercent, value); }
/// <summary>
/// Total Additional Assets Amount [URLA.X49]
/// </summary>
public decimal? TotalAdditionalAssetsAmount { get => _totalAdditionalAssetsAmount; set => SetField(ref _totalAdditionalAssetsAmount, value); }
/// <summary>
/// Total Additional Loans Amount [URLA.X229]
/// </summary>
public decimal? TotalAdditionalLoansAmount { get => _totalAdditionalLoansAmount; set => SetField(ref _totalAdditionalLoansAmount, value); }
/// <summary>
/// Total Additional Other Assets Amount [URLA.X53]
/// </summary>
public decimal? TotalAdditionalOtherAssetsAmount { get => _totalAdditionalOtherAssetsAmount; set => SetField(ref _totalAdditionalOtherAssetsAmount, value); }
/// <summary>
/// Total Applied To Downpayment [URLA.X230]
/// </summary>
public decimal? TotalAppliedToDownpayment { get => _totalAppliedToDownpayment; set => SetField(ref _totalAppliedToDownpayment, value); }
/// <summary>
/// Assets Total Assets [732]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalAssetsAmount { get => _totalAssetsAmount; set => SetField(ref _totalAssetsAmount, value); }
/// <summary>
/// Income Total Base Income (Borr/Co-Borr) [901]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalBaseIncomeAmount { get => _totalBaseIncomeAmount; set => SetField(ref _totalBaseIncomeAmount, value); }
/// <summary>
/// Income Total Bonuses (Borr/Co-Borr) [903]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalBonusAmount { get => _totalBonusAmount; set => SetField(ref _totalBonusAmount, value); }
/// <summary>
/// Income Total Commissions (Borr/Co-Borr) [904]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalCommissionsAmount { get => _totalCommissionsAmount; set => SetField(ref _totalCommissionsAmount, value); }
/// <summary>
/// Assets Total Bank Deposits [979]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalDeposit { get => _totalDeposit; set => SetField(ref _totalDeposit, value); }
/// <summary>
/// Income Total Div/Int (Borr/Co-Borr) [905]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalDividendsInterestAmount { get => _totalDividendsInterestAmount; set => SetField(ref _totalDividendsInterestAmount, value); }
/// <summary>
/// Income Total Mo Income Spouse/Borr [1810]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalEmploymentAmount { get => _totalEmploymentAmount; set => SetField(ref _totalEmploymentAmount, value); }
/// <summary>
/// Expenses Total Mo Expense [1187]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalFixedPaymentAmount { get => _totalFixedPaymentAmount; set => SetField(ref _totalFixedPaymentAmount, value); }
/// <summary>
/// Income Total Mo Income (Borr/Co-Borr) [1389]
/// </summary>
public decimal? TotalGrossMonthlyIncomeAmount { get => _totalGrossMonthlyIncomeAmount; set => SetField(ref _totalGrossMonthlyIncomeAmount, value); }
/// <summary>
/// Income Total Mo Income [736]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalIncomeAmount { get => _totalIncomeAmount; set => SetField(ref _totalIncomeAmount, value); }
/// <summary>
/// Liabilities Total Liability Pymt [350]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalMonthlyPaymentAmount { get => _totalMonthlyPaymentAmount; set => SetField(ref _totalMonthlyPaymentAmount, value); }
/// <summary>
/// Trans Details Total Mtg Bal [941]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalMortgagesBalanceAmount { get => _totalMortgagesBalanceAmount; set => SetField(ref _totalMortgagesBalanceAmount, value); }
/// <summary>
/// Trans Details Total Mtg Mo Pymt [909]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalMortgagesMonthlyPaymentAmount { get => _totalMortgagesMonthlyPaymentAmount; set => SetField(ref _totalMortgagesMonthlyPaymentAmount, value); }
/// <summary>
/// Income Total Net Rent Income (Borr/Co-Borr) [906]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalNetRentalIncomeAmount { get => _totalNetRentalIncomeAmount; set => SetField(ref _totalNetRentalIncomeAmount, value); }
/// <summary>
/// Income Total Other 1 (Borr/Co-Borr) [907]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalOther1Amount { get => _totalOther1Amount; set => SetField(ref _totalOther1Amount, value); }
/// <summary>
/// Income Total Other 2 (Borr/Co-Borr) [908]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalOther2Amount { get => _totalOther2Amount; set => SetField(ref _totalOther2Amount, value); }
/// <summary>
/// Total Other Assets Amount [URLA.X54]
/// </summary>
public decimal? TotalOtherAssetsAmount { get => _totalOtherAssetsAmount; set => SetField(ref _totalOtherAssetsAmount, value); }
/// <summary>
/// Income Total Overtime (Borr/Co-Borr) [902]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalOvertimeAmount { get => _totalOvertimeAmount; set => SetField(ref _totalOvertimeAmount, value); }
/// <summary>
/// Trans Details Total Proposed Mo Pymt [1742]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalPaymentsAmount { get => _totalPaymentsAmount; set => SetField(ref _totalPaymentsAmount, value); }
/// <summary>
/// Expenses Total Primary Expenses [1731]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalPrimaryHousingExpenseAmount { get => _totalPrimaryHousingExpenseAmount; set => SetField(ref _totalPrimaryHousingExpenseAmount, value); }
/// <summary>
/// Application TotalReoMarketValueAmount
/// </summary>
public decimal? TotalReoMarketValueAmount { get => _totalReoMarketValueAmount; set => SetField(ref _totalReoMarketValueAmount, value); }
/// <summary>
/// Total Assets Amount [URLA.X50]
/// </summary>
public decimal? TotalURLA2020AssetsAmount { get => _totalURLA2020AssetsAmount; set => SetField(ref _totalURLA2020AssetsAmount, value); }
/// <summary>
/// Income Total Other Income (User Defined) [1817]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TotalUserDefinedIncome { get => _totalUserDefinedIncome; set => SetField(ref _totalUserDefinedIncome, value); }
/// <summary>
/// Application TQLReports
/// </summary>
[AllowNull]
public IList<TQLReportInformation> TQLReports { get => GetField(ref _tQLReports); set => SetField(ref _tQLReports, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co Addr [DISCLOSURE.X22]
/// </summary>
public string? TransUnionAddress { get => _transUnionAddress; set => SetField(ref _transUnionAddress, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co City [DISCLOSURE.X23]
/// </summary>
public string? TransUnionCity { get => _transUnionCity; set => SetField(ref _transUnionCity, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co Fax [DISCLOSURE.X27]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? TransUnionFax { get => _transUnionFax; set => SetField(ref _transUnionFax, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co Model [DISCLOSURE.X28]
/// </summary>
public string? TransUnionModel { get => _transUnionModel; set => SetField(ref _transUnionModel, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co Name [DISCLOSURE.X21]
/// </summary>
public string? TransUnionName { get => _transUnionName; set => SetField(ref _transUnionName, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co Phone [DISCLOSURE.X26]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? TransUnionPhone { get => _transUnionPhone; set => SetField(ref _transUnionPhone, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co Zip [DISCLOSURE.X25]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)]
public string? TransUnionPostalCode { get => _transUnionPostalCode; set => SetField(ref _transUnionPostalCode, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co Range Scores From [DISCLOSURE.X29]
/// </summary>
public string? TransUnionScoreRangeFrom { get => _transUnionScoreRangeFrom; set => SetField(ref _transUnionScoreRangeFrom, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co Range Scores To [DISCLOSURE.X30]
/// </summary>
public string? TransUnionScoreRangeTo { get => _transUnionScoreRangeTo; set => SetField(ref _transUnionScoreRangeTo, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co State [DISCLOSURE.X24]
/// </summary>
public StringEnumValue<State> TransUnionState { get => _transUnionState; set => SetField(ref _transUnionState, value); }
/// <summary>
/// Disclosure Cred Bureau 2 Co Website [DISCLOSURE.X639]
/// </summary>
public string? TransUnionWebsite { get => _transUnionWebsite; set => SetField(ref _transUnionWebsite, value); }
/// <summary>
/// Application URLAAlternateNames
/// </summary>
[AllowNull]
public IList<URLAAlternateName> URLAAlternateNames { get => GetField(ref _uRLAAlternateNames); set => SetField(ref _uRLAAlternateNames, value); }
/// <summary>
/// Application UserDefinedIncome
/// </summary>
public decimal? UserDefinedIncome { get => _userDefinedIncome; set => SetField(ref _userDefinedIncome, value); }
/// <summary>
/// Income Borr/Co-Borr Other Income 2 Descr [1818]
/// </summary>
public string? UserDefinedIncomeDescription { get => _userDefinedIncomeDescription; set => SetField(ref _userDefinedIncomeDescription, value); }
/// <summary>
/// VA Meets VA Credit Standards [1327]
/// </summary>
public StringEnumValue<YOrN> VACreditStandards { get => _vACreditStandards; set => SetField(ref _vACreditStandards, value); }
/// <summary>
/// VA Veteran Income Spouse Income Amt [1008]
/// </summary>
public decimal? VaSummarySpouseIncomeAmount { get => _vaSummarySpouseIncomeAmount; set => SetField(ref _vaSummarySpouseIncomeAmount, value); }
/// <summary>
/// Income Total Mo Gross Income [993]
/// </summary>
public decimal? VaSummaryTotalMonthlyGrossIncomeAmount { get => _vaSummaryTotalMonthlyGrossIncomeAmount; set => SetField(ref _vaSummaryTotalMonthlyGrossIncomeAmount, value); }
}
} | 49.509079 | 207 | 0.660473 | [
"MIT"
] | TimH-SL/EncompassRest | src/EncompassRest/Loans/Application.cs | 73,620 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace UnserSnackautomat.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.580645 | 151 | 0.583955 | [
"Unlicense"
] | Fiw7a/snackautomat | UnserSnackautomat/UnserSnackautomat/Properties/Settings.Designer.cs | 1,074 | C# |
namespace ForumSystem.Web.InputModels.Feedbacks
{
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using ForumSystem.Data.Models;
using ForumSystem.Web.Infrastructure.Mapping;
public class CreateFeedbackModel : IMapFrom<Feedback>
{
[Required]
[MaxLength(20)]
[Display(Name = "Title")]
[AllowHtml]
public string Title { get; set; }
[Required]
[AllowHtml]
[Display(Name = "Content")]
[DataType("tinymce_full")]
[UIHint("tinymce_full")]
public string Content { get; set; }
}
} | 25.625 | 57 | 0.613008 | [
"MIT"
] | hrist0stoichev/Telerik-Exams | MVC-Exam-2014/ForumSystem/Source/Web/ForumSystem.Web/InputModels/Feedbacks/CreateFeedbackModel.cs | 617 | C# |
using BlazorHero.CleanArchitecture.Shared.Settings;
using System.Threading.Tasks;
using BlazorHero.CleanArchitecture.Shared.Wrapper;
namespace BlazorHero.CleanArchitecture.Shared.Managers
{
public interface IPreferenceManager
{
Task SetPreference(IPreference preference);
Task<IPreference> GetPreference();
Task<IResult> ChangeLanguageAsync(string languageCode);
}
} | 27.066667 | 63 | 0.770936 | [
"MIT"
] | 10GeekJames/CleanArchitecture | src/Shared/Managers/IPreferenceManager.cs | 408 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
public static partial class RuntimeHelpers
{
// The special dll name to be used for DllImport of QCalls
internal const string QCall = "QCall";
[Intrinsic]
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle);
// GetObjectValue is intended to allow value classes to be manipulated as 'Object'
// but have aliasing behavior of a value class. The intent is that you would use
// this function just before an assignment to a variable of type 'Object'. If the
// value being assigned is a mutable value class, then a shallow copy is returned
// (because value classes have copy semantics), but otherwise the object itself
// is returned.
//
// Note: VB calls this method when they're about to assign to an Object
// or pass it as a parameter. The goal is to make sure that boxed
// value types work identical to unboxed value types - ie, they get
// cloned when you pass them around, and are always passed by value.
// Of course, reference types are not cloned.
//
[MethodImpl(MethodImplOptions.InternalCall)]
[return: NotNullIfNotNull("obj")]
public static extern object? GetObjectValue(object? obj);
// RunClassConstructor causes the class constructor for the given type to be triggered
// in the current domain. After this call returns, the class constructor is guaranteed to
// have at least been started by some thread. In the absence of class constructor
// deadlock conditions, the call is further guaranteed to have completed.
//
// This call will generate an exception if the specified class constructor threw an
// exception when it ran.
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _RunClassConstructor(RuntimeType type);
public static void RunClassConstructor(RuntimeTypeHandle type)
{
_RunClassConstructor(type.GetRuntimeType());
}
// RunModuleConstructor causes the module constructor for the given type to be triggered
// in the current domain. After this call returns, the module constructor is guaranteed to
// have at least been started by some thread. In the absence of module constructor
// deadlock conditions, the call is further guaranteed to have completed.
//
// This call will generate an exception if the specified module constructor threw an
// exception when it ran.
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module);
public static void RunModuleConstructor(ModuleHandle module)
{
_RunModuleConstructor(module.GetRuntimeModule());
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void _CompileMethod(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe void _PrepareMethod(IRuntimeMethodInfo method, IntPtr* pInstantiation, int cInstantiation);
public static void PrepareMethod(RuntimeMethodHandle method)
{
unsafe
{
_PrepareMethod(method.GetMethodInfo(), null, 0);
}
}
public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[]? instantiation)
{
unsafe
{
IntPtr[]? instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out int length);
fixed (IntPtr* pInstantiation = instantiationHandles)
{
_PrepareMethod(method.GetMethodInfo(), pInstantiation, length);
GC.KeepAlive(instantiation);
}
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void PrepareDelegate(Delegate d);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetHashCode(object? o);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern new bool Equals(object? o1, object? o2);
public static int OffsetToStringData
{
// This offset is baked in by string indexer intrinsic, so there is no harm
// in getting it baked in here as well.
[System.Runtime.Versioning.NonVersionable]
get =>
// Number of bytes from the address pointed to by a reference to
// a String to the first 16-bit character in the String. Skip
// over the MethodTable pointer, & String
// length. Of course, the String reference points to the memory
// after the sync block, so don't count that.
// This property allows C#'s fixed statement to work on Strings.
// On 64 bit platforms, this should be 12 (8+4) and on 32 bit 8 (4+4).
#if TARGET_64BIT
12;
#else // 32
8;
#endif // TARGET_64BIT
}
// This method ensures that there is sufficient stack to execute the average Framework function.
// If there is not enough stack, then it throws System.InsufficientExecutionStackException.
// Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack
// below.
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void EnsureSufficientExecutionStack();
// This method ensures that there is sufficient stack to execute the average Framework function.
// If there is not enough stack, then it return false.
// Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack
// below.
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern bool TryEnsureSufficientExecutionStack();
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern object GetUninitializedObjectInternal(Type type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object AllocateUninitializedClone(object obj);
/// <returns>true if given type is reference type or value type that contains references</returns>
[Intrinsic]
public static bool IsReferenceOrContainsReferences<T>()
{
// The body of this function will be replaced by the EE with unsafe code!!!
// See getILIntrinsicImplementationForRuntimeHelpers for how this happens.
throw new InvalidOperationException();
}
/// <returns>true if given type is bitwise equatable (memcmp can be used for equality checking)</returns>
/// <remarks>
/// Only use the result of this for Equals() comparison, not for CompareTo() comparison.
/// </remarks>
[Intrinsic]
internal static bool IsBitwiseEquatable<T>()
{
// The body of this function will be replaced by the EE with unsafe code!!!
// See getILIntrinsicImplementationForRuntimeHelpers for how this happens.
throw new InvalidOperationException();
}
[Intrinsic]
internal static bool EnumEquals<T>(T x, T y) where T : struct, Enum
{
// The body of this function will be replaced by the EE with unsafe code
// See getILIntrinsicImplementation for how this happens.
return x.Equals(y);
}
[Intrinsic]
internal static int EnumCompareTo<T>(T x, T y) where T : struct, Enum
{
// The body of this function will be replaced by the EE with unsafe code
// See getILIntrinsicImplementation for how this happens.
return x.CompareTo(y);
}
internal static ref byte GetRawData(this object obj) =>
ref Unsafe.As<RawData>(obj).Data;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe nuint GetRawObjectDataSize(object obj)
{
MethodTable* pMT = GetMethodTable(obj);
// See comment on RawArrayData for details
nuint rawSize = pMT->BaseSize - (nuint)(2 * sizeof(IntPtr));
if (pMT->HasComponentSize)
rawSize += (uint)Unsafe.As<RawArrayData>(obj).Length * (nuint)pMT->ComponentSize;
GC.KeepAlive(obj); // Keep MethodTable alive
return rawSize;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe ref byte GetRawArrayData(this Array array) =>
// See comment on RawArrayData for details
ref Unsafe.AddByteOffset(ref Unsafe.As<RawData>(array).Data, (nuint)GetMethodTable(array)->BaseSize - (nuint)(2 * sizeof(IntPtr)));
internal static unsafe ushort GetElementSize(this Array array)
{
Debug.Assert(ObjectHasComponentSize(array));
return GetMethodTable(array)->ComponentSize;
}
// Returns pointer to the multi-dimensional array bounds.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe ref int GetMultiDimensionalArrayBounds(Array array)
{
Debug.Assert(GetMultiDimensionalArrayRank(array) > 0);
// See comment on RawArrayData for details
return ref Unsafe.As<byte, int>(ref Unsafe.As<RawArrayData>(array).Data);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe int GetMultiDimensionalArrayRank(Array array)
{
int rank = GetMethodTable(array)->MultiDimensionalArrayRank;
GC.KeepAlive(array); // Keep MethodTable alive
return rank;
}
// Returns true iff the object has a component size;
// i.e., is variable length like System.String or Array.
// Callers are required to keep obj alive
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe bool ObjectHasComponentSize(object obj)
{
return GetMethodTable(obj)->HasComponentSize;
}
// Given an object reference, returns its MethodTable*.
//
// WARNING: The caller has to ensure that MethodTable* does not get unloaded. The most robust way
// to achieve this is by using GC.KeepAlive on the object that the MethodTable* was fetched from, e.g.:
//
// MethodTable* pMT = GetMethodTable(o);
//
// ... work with pMT ...
//
// GC.KeepAlive(o);
//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[Intrinsic]
internal static unsafe MethodTable* GetMethodTable(object obj)
{
// The body of this function will be replaced by the EE with unsafe code
// See getILIntrinsicImplementationForRuntimeHelpers for how this happens.
return (MethodTable *)Unsafe.Add(ref Unsafe.As<byte, IntPtr>(ref obj.GetRawData()), -1);
}
/// <summary>
/// Allocate memory that is associated with the <paramref name="type"/> and
/// will be freed if and when the <see cref="System.Type"/> is unloaded.
/// </summary>
/// <param name="type">Type associated with the allocated memory.</param>
/// <param name="size">Amount of memory in bytes to allocate.</param>
/// <returns>The allocated memory</returns>
public static IntPtr AllocateTypeAssociatedMemory(Type type, int size)
{
RuntimeType? rt = type as RuntimeType;
if (rt == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(type));
if (size < 0)
throw new ArgumentOutOfRangeException(nameof(size));
return AllocateTypeAssociatedMemoryInternal(new QCallTypeHandle(ref rt), (uint)size);
}
[DllImport(RuntimeHelpers.QCall)]
private static extern IntPtr AllocateTypeAssociatedMemoryInternal(QCallTypeHandle type, uint size);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern IntPtr AllocTailCallArgBuffer(int size, IntPtr gcDesc);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void FreeTailCallArgBuffer();
[MethodImpl(MethodImplOptions.InternalCall)]
private static unsafe extern TailCallTls* GetTailCallInfo(IntPtr retAddrSlot, IntPtr* retAddr);
}
// Helper class to assist with unsafe pinning of arbitrary objects.
// It's used by VM code.
internal class RawData
{
public byte Data;
}
// CLR arrays are laid out in memory as follows (multidimensional array bounds are optional):
// [ sync block || pMethodTable || num components || MD array bounds || array data .. ]
// ^ ^ ^ ^ returned reference
// | | \-- ref Unsafe.As<RawArrayData>(array).Data
// \-- array \-- ref Unsafe.As<RawData>(array).Data
// The BaseSize of an array includes all the fields before the array data,
// including the sync block and method table. The reference to RawData.Data
// points at the number of components, skipping over these two pointer-sized fields.
internal class RawArrayData
{
public uint Length; // Array._numComponents padded to IntPtr
#if TARGET_64BIT
public uint Padding;
#endif
public byte Data;
}
// Subset of src\vm\methodtable.h
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct MethodTable
{
[FieldOffset(0)]
public ushort ComponentSize;
[FieldOffset(0)]
private uint Flags;
[FieldOffset(4)]
public uint BaseSize;
[FieldOffset(0x0e)]
public ushort InterfaceCount;
[FieldOffset(ParentMethodTableOffset)]
public MethodTable* ParentMethodTable;
[FieldOffset(ElementTypeOffset)]
public void* ElementType;
[FieldOffset(InterfaceMapOffset)]
public MethodTable** InterfaceMap;
// WFLAGS_HIGH_ENUM
private const uint enum_flag_ContainsPointers = 0x01000000;
private const uint enum_flag_HasComponentSize = 0x80000000;
private const uint enum_flag_HasTypeEquivalence = 0x00004000;
// Types that require non-trivial interface cast have this bit set in the category
private const uint enum_flag_NonTrivialInterfaceCast = 0x00080000 // enum_flag_Category_Array
| 0x40000000 // enum_flag_ComObject
| 0x00400000;// enum_flag_ICastable;
private const int DebugClassNamePtr = // adjust for debug_m_szClassName
#if DEBUG
#if TARGET_64BIT
8
#else
4
#endif
#else
0
#endif
;
private const int ParentMethodTableOffset = 0x10 + DebugClassNamePtr;
#if TARGET_64BIT
private const int ElementTypeOffset = 0x30 + DebugClassNamePtr;
#else
private const int ElementTypeOffset = 0x20 + DebugClassNamePtr;
#endif
#if TARGET_64BIT
private const int InterfaceMapOffset = 0x38 + DebugClassNamePtr;
#else
private const int InterfaceMapOffset = 0x24 + DebugClassNamePtr;
#endif
public bool HasComponentSize
{
get
{
return (Flags & enum_flag_HasComponentSize) != 0;
}
}
public bool ContainsGCPointers
{
get
{
return (Flags & enum_flag_ContainsPointers) != 0;
}
}
public bool NonTrivialInterfaceCast
{
get
{
return (Flags & enum_flag_NonTrivialInterfaceCast) != 0;
}
}
public bool HasTypeEquivalence
{
get
{
return (Flags & enum_flag_HasTypeEquivalence) != 0;
}
}
public bool IsMultiDimensionalArray
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
Debug.Assert(HasComponentSize);
// See comment on RawArrayData for details
return BaseSize > (uint)(3 * sizeof(IntPtr));
}
}
// Returns rank of multi-dimensional array rank, 0 for sz arrays
public int MultiDimensionalArrayRank
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
Debug.Assert(HasComponentSize);
// See comment on RawArrayData for details
return (int)((BaseSize - (uint)(3 * sizeof(IntPtr))) / (uint)(2 * sizeof(int)));
}
}
}
// Helper structs used for tail calls via helper.
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct PortableTailCallFrame
{
public PortableTailCallFrame* Prev;
public IntPtr TailCallAwareReturnAddress;
public IntPtr NextCall;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct TailCallTls
{
public PortableTailCallFrame* Frame;
public IntPtr ArgBuffer;
private IntPtr _argBufferSize;
private IntPtr _argBufferGCDesc;
private fixed byte _argBufferInline[64];
}
}
| 40.681614 | 143 | 0.636299 | [
"MIT"
] | CometstarMH/runtime | src/coreclr/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs | 18,144 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Karenia.Rurikawa.Helpers {
/// <summary>
/// FlowSnake is a time-sortable unique ID generator based on Twitter Snowflake.
/// </summary>
[ModelBinder(typeof(FlowSnakeBinder))]
public struct FlowSnake : IEquatable<FlowSnake>, IComparable<FlowSnake>, IComparable<long> {
const int TIMESTAMP_BITS = 34;
const int WORKER_ID_BITS = 12;
const int SEQUENCE_BITS = 18;
public static readonly FlowSnake MaxValue = new FlowSnake(long.MaxValue);
public static readonly FlowSnake MinValue = new FlowSnake(0);
static readonly char[] alphabet = "0123456789abcdefghjkmnpqrstvwxyz".ToCharArray();
static readonly byte[] charToBase32 = new byte[] {
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 16, 17, 255, 18, 19, 255, 20,
21, 255, 22, 23, 24, 25, 26, 255, 27, 28, 29, 30, 31, 255, 255, 255, 255, 255, 255, 10, 11,
12, 13, 14, 15, 16, 17, 255, 18, 19, 255, 20, 21, 255, 22, 23, 24, 25, 26, 255, 27, 28, 29,
30, 31
};
static readonly ThreadLocal<int> workerId = new ThreadLocal<int>(() =>
// some kind of hash result of process and thread ids
(System.Diagnostics.Process.GetCurrentProcess().Id * 19260817)
+ Thread.CurrentThread.ManagedThreadId
);
static readonly ThreadLocal<long> lastGeneration = new ThreadLocal<long>(() => 0);
static readonly ThreadLocal<int> sequenceNumber = new ThreadLocal<int>(() => 0);
static Random prng = new Random();
static readonly DateTimeOffset UnixEpoch =
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public FlowSnake(long num) => Num = num;
public FlowSnake(long time, int worker, int seq) {
Num = ((time) << (WORKER_ID_BITS + SEQUENCE_BITS))
| (((long)worker & ((1 << WORKER_ID_BITS) - 1)) << SEQUENCE_BITS)
| ((long)seq & ((1 << SEQUENCE_BITS) - 1));
}
public long Num { get; }
public static FlowSnake Generate() {
var time = DateTimeOffset.Now.ToUnixTimeSeconds();
int seq;
if (time <= lastGeneration.Value) {
// because this value is thread-local, we don't need to worry about
// race conditions
seq = sequenceNumber.Value;
sequenceNumber.Value = seq + 1;
if (seq >= (1 << SEQUENCE_BITS)) {
throw new OverflowException("Sequence number overflow!");
}
} else {
seq = prng.Next((1 << SEQUENCE_BITS) - (1 << (SEQUENCE_BITS - 2)));
sequenceNumber.Value = seq + 1;
}
lastGeneration.Value = time;
var worker = workerId.Value;
return new FlowSnake(time, worker, seq);
}
public FlowSnake(string val, bool parseEmptyAsZero = false) {
if (parseEmptyAsZero && (val == null || val == "")) {
Num = 0;
return;
}
if (val.Length < 13) {
throw new ArgumentException(
$"Expected string length: at least 13, got: {val.Length}"
);
}
long num = 0;
int i = 0;
int j = 0;
while (j < 13 && i < val.Length) {
if (val[i] == '-') {
i++; continue;
}
byte ch = charToBase32[val[i]];
if (ch == 255)
throw new ArgumentException($"Unknown character when parsing FlowSnake");
num <<= 5;
num |= ch;
i++;
j++;
}
Num = num;
}
public string ToString(bool dash) {
var sb = new StringBuilder(14);
int bit0 = (int)(Num >> 60) & 31;
sb.Append(alphabet[bit0]);
for (int i = 11; i >= 0; i--) {
sb.Append(alphabet[(int)((Num >> (5 * i)) & 31)]);
}
if (dash) {
sb.Insert(7, '-');
}
return sb.ToString();
}
public override string ToString() {
return this.ToString(true);
}
public DateTimeOffset ExtractTime() =>
DateTimeOffset.FromUnixTimeSeconds(
Num >> (SEQUENCE_BITS + WORKER_ID_BITS)
);
public static implicit operator long(FlowSnake i) => i.Num;
#region Comparisons
public override bool Equals(object? obj) =>
obj is FlowSnake snake && Equals(snake);
public bool Equals(FlowSnake other) => Num == other.Num;
public override int GetHashCode() => HashCode.Combine(Num);
public int CompareTo([AllowNull] long other) => Num.CompareTo(other);
public int CompareTo([AllowNull] FlowSnake other) => Num.CompareTo(other.Num);
public static bool operator ==(FlowSnake left, FlowSnake right) =>
left.Equals(right);
public static bool operator !=(FlowSnake left, FlowSnake right) =>
!(left == right);
public static bool operator <(FlowSnake left, FlowSnake right) =>
left.CompareTo(right) < 0;
public static bool operator <=(FlowSnake left, FlowSnake right) =>
left.CompareTo(right) <= 0;
public static bool operator >(FlowSnake left, FlowSnake right) =>
left.CompareTo(right) > 0;
public static bool operator >=(FlowSnake left, FlowSnake right) =>
left.CompareTo(right) >= 0;
public static bool operator <(long left, FlowSnake right) =>
left.CompareTo(right) < 0;
public static bool operator <=(long left, FlowSnake right) =>
left.CompareTo(right) <= 0;
public static bool operator >(long left, FlowSnake right) =>
left.CompareTo(right) > 0;
public static bool operator >=(long left, FlowSnake right) =>
left.CompareTo(right) >= 0;
public static bool operator <(FlowSnake left, long right) =>
left.CompareTo(right) < 0;
public static bool operator <=(FlowSnake left, long right) =>
left.CompareTo(right) <= 0;
public static bool operator >(FlowSnake left, long right) =>
left.CompareTo(right) > 0;
public static bool operator >=(FlowSnake left, long right) =>
left.CompareTo(right) >= 0;
#endregion
}
public class FlowSnakeJsonConverter : JsonConverter<FlowSnake> {
private readonly bool writeAsString;
public FlowSnakeJsonConverter(bool writeAsString = true) {
this.writeAsString = writeAsString;
}
public override bool CanConvert(Type typeToConvert) =>
typeToConvert == typeof(FlowSnake);
public override FlowSnake Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options
) {
if (reader.TokenType == JsonTokenType.Number) {
var i = reader.GetInt64();
return new FlowSnake(i);
} else {
var s = reader.GetString();
return new FlowSnake(s, true);
}
}
public override void Write(
Utf8JsonWriter writer,
FlowSnake value,
JsonSerializerOptions options
) {
if (writeAsString) {
writer.WriteStringValue(value.ToString());
} else {
writer.WriteNumberValue(value.Num);
}
}
}
public class FlowSnakeBinder : IModelBinder {
public Task BindModelAsync(ModelBindingContext bindingContext) {
if (bindingContext == null) {
throw new ArgumentNullException(nameof(bindingContext));
}
var modelName = bindingContext.ModelName;
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None) {
return Task.CompletedTask;
}
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var val = valueProviderResult.FirstValue;
try {
var val_parsed = new FlowSnake(val);
bindingContext.Result = ModelBindingResult.Success(val_parsed);
return Task.CompletedTask;
} catch (ArgumentException e) {
bindingContext.ModelState.AddModelError(modelName, e.Message);
return Task.CompletedTask;
}
}
}
}
| 37.227092 | 103 | 0.553938 | [
"MIT"
] | BUAA-SE-Compiling/rurikawa | coordinator/Helpers/FlowSnakeId.cs | 9,344 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Text;
namespace CoreWCF.Dispatcher
{
internal class WebHttpDispatchOperationSelectorData
{
internal List<string> AllowedMethods { get; set; }
internal string AllowHeader
{
get
{
if (AllowedMethods != null)
{
int allowedHeadersCount = AllowedMethods.Count;
if (allowedHeadersCount > 0)
{
StringBuilder stringBuilder = new StringBuilder(AllowedMethods[0]);
for (int x = 1; x < allowedHeadersCount; x++)
{
stringBuilder.Append(", " + AllowedMethods[x]);
}
return stringBuilder.ToString();
}
}
return null;
}
}
}
}
| 29 | 91 | 0.493942 | [
"MIT"
] | JonathanHopeDMRC/CoreWCF | src/CoreWCF.WebHttp/src/CoreWCF/Dispatcher/WebHttpDispatchOperationSelectorData.cs | 1,075 | C# |
//
// Copyright 2019 Desert Software Solutions Inc.
// Refactored from ServiceKit.cs:
// https://github.com/DesertSoftware/Solutions
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace DesertSoftware.Solutions.Service
{
/// <summary>
/// Fluent service factory class
/// </summary>
public class ServiceFactory
{
const string GREETING = "A Desert Software solution <http://desertsoftware.com>";
/// <summary>
/// Runs or configures a service described in the specified configurator and command line arguments.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="args">The arguments.</param>
/// <param name="configurator">The configurator.</param>
/// <returns></returns>
static public int Run<T>(string[] args, Action<ServiceConfigurator<T>> configurator) {
var svcConfigurator = new ServiceConfigurator<T>();
var logger = Gel.Logger.Log("service"); // get the error logger in case we fault to ensure that we can log
// give the user a chance to configure this service
configurator(svcConfigurator);
if (svcConfigurator.ConsoleGreeting == null)
svcConfigurator.ConsoleGreeting = () => {
Console.WriteLine("{0} service {1}", Setup.serviceInstaller.DisplayName, typeof(T).ProductVersion());
Console.WriteLine(GREETING);
};
// now parse the command line
var state = RunState.ExecuteCommandLine<T>(args, svcConfigurator.ConsoleGreeting, Setup.serviceInstaller);
if (state.TimeToExit)
return 0;
// attempt to log an informational message to ensure logging is configured properly
if (svcConfigurator.ServiceGreeting == null) {
logger.Info("{1} service {0}", typeof(T).ProductVersion(), Setup.serviceInstaller.DisplayName);
logger.Info(GREETING);
} else
svcConfigurator.ServiceGreeting();
try {
// TODO: revisit this
if (svcConfigurator.ServiceInstance == null)
svcConfigurator.ServiceInstance = new Service<T>();
if (!state.RunAsService) {
var svc = svcConfigurator.ServiceInstance;
svc.Start(); // svc.Start(args);
Console.WriteLine();
Console.WriteLine("Service is running. Press enter to quit ... ");
Console.WriteLine();
Console.ReadLine();
svc.Stop();
} else
ServiceBase.Run(svcConfigurator.ServiceInstance);
} catch (Exception ex) {
logger.Fatal(ex);
if (!state.RunAsService) {
Console.WriteLine("Service is stopped. Press enter to exit ... ");
Console.WriteLine();
Console.ReadLine();
}
return -1;
}
return 0;
}
/// <summary>
/// The service configurator that is used in a ServiceFactory.Run operation to configure a service
/// </summary>
/// <typeparam name="T"></typeparam>
public class ServiceConfigurator<T>
{
/// <summary>
/// Sets the display name of the service. The name that is displayed in the service control manager.
/// </summary>
/// <value>
/// The display name.
/// </value>
public string DisplayName { set { Setup.serviceInstaller.DisplayName = value; } }
/// <summary>
/// Sets the name of the service. The name by which this service is started and stopped (eg. net start servicename)
/// </summary>
/// <value>
/// The name of the service.
/// </value>
public string ServiceName { set { Setup.serviceInstaller.ServiceName = value; } }
/// <summary>
/// Sets the description of the service as diplayed in the service control manager.
/// </summary>
/// <value>
/// The description.
/// </value>
public string Description { set { Setup.serviceInstaller.Description = value; } }
/// <summary>
/// Sets the account that the service will execute in.
/// </summary>
/// <value>
/// The account.
/// </value>
public ServiceAccount Account { set { Setup.serviceProcessInstaller.Account = value; } }
/// <summary>
/// Sets the username of a local or domain account.
/// </summary>
/// <value>
/// The username.
/// </value>
public string Username { set { Setup.serviceProcessInstaller.Username = value; } }
/// <summary>
/// Sets the password of the Username account.
/// </summary>
/// <value>
/// The password.
/// </value>
public string Password { set { Setup.serviceProcessInstaller.Password = value; } }
/// <summary>
/// Gets or sets the service greeting routine to be executed.
/// </summary>
/// <value>
/// The service greeting.
/// </value>
public Action ServiceGreeting { internal get; set; }
/// <summary>
/// Gets or sets the console greeting routine to be executed.
/// </summary>
/// <value>
/// The console greeting.
/// </value>
public Action ConsoleGreeting { internal get; set; }
/// <summary>
/// Gets or sets the service instance.
/// </summary>
/// <value>
/// The service instance.
/// </value>
internal Service<T> ServiceInstance { get; set; }
/// <summary>
/// Configures bindings to the service class such as starting and stopping.
/// </summary>
/// <param name="constructor">The constructor.</param>
public void Service(Action<IServiceConfiguration<T>> constructor) {
this.ServiceInstance = new Service<T>();
constructor(this.ServiceInstance);
}
}
/// <summary>
/// Service configuration options that are made available when the Service method is executed
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IServiceConfiguration<T>
{
/// <summary>
/// Specifies how to construct the T service class.
/// </summary>
/// <param name="constructor">The constructor.</param>
void ConstructUsing(Func<string, T> constructor);
/// <summary>
/// Specifies how the service class is started.
/// </summary>
/// <param name="doStart">The do start.</param>
void OnStart(Action<T> doStart);
/// <summary>
/// Specifies how the service class is stoppd.
/// </summary>
/// <param name="doStop">The do stop.</param>
void OnStop(Action<T> doStop);
}
/// <summary>
/// A service factory runnable class
/// </summary>
/// <typeparam name="T"></typeparam>
public class Service<T> : ServiceBase, IServiceConfiguration<T>
{
private Action<T> start;
private Action<T> stop;
private T instance;
private Func<string, T> constructor;
/// <summary>
/// Specifies how to constructs the T service class.
/// </summary>
/// <param name="constructor">The constructor.</param>
public void ConstructUsing(Func<string, T> constructor) {
this.constructor = constructor;
}
/// <summary>
/// Specifies how the service class is started.
/// </summary>
/// <param name="doStart">The do start.</param>
public void OnStart(Action<T> doStart) {
this.start = doStart;
}
/// <summary>
/// Specifies how the service class is stoppd.
/// </summary>
/// <param name="doStop">The do stop.</param>
public void OnStop(Action<T> doStop) {
this.stop = doStop;
}
/// <summary>
/// Starts this instance.
/// </summary>
public void Start() {
OnStart(new string[] { });
}
/// <summary>
/// Stops the executing service.
/// </summary>
public new void Stop() {
OnStop();
}
/// <summary>
/// When implemented in a derived class, executes when a Start command is sent to
/// the service by the Service Control Manager (SCM) or when the operating system
/// starts (for a service that starts automatically). Specifies actions to take
/// when the service starts.
/// </summary>
/// <param name="args">Data passed by the start command.</param>
protected override void OnStart(string[] args) {
if (this.instance == null) {
if (this.constructor != null)
this.instance = this.constructor("");
else
this.instance = Activator.CreateInstance<T>();
}
if (this.start != null)
this.start(this.instance);
else
base.OnStart(args);
}
/// <summary>
/// When implemented in a derived class, executes when a Stop command is sent to
/// the service by the Service Control Manager (SCM). Specifies actions to take
/// when a service stops running.
/// </summary>
protected override void OnStop() {
if (this.stop != null)
this.stop(this.instance);
else
base.OnStop();
}
}
private class RunState
{
static private RunState ExitNow { get { return new RunState { RunAsService = false, TimeToExit = true }; } }
static private RunState RunService { get { return new RunState { RunAsService = true, TimeToExit = false }; } }
static private RunState RunConsole { get { return new RunState { RunAsService = false, TimeToExit = false }; } }
/// <summary>
/// Executes the command line.
/// </summary>
/// <param name="args">The arguments.</param>
/// <param name="greeting">The greeting. eg. Data Collection service</param>
/// <param name="program">The program type.</param>
/// <returns></returns>
static public RunState ExecuteCommandLine<TService>(string[] args, Action greeting, ServiceInstaller setup) {
var logger = Gel.Logger.Log("service"); // get the error logger in case we fault to ensure that we can log
foreach (var arg in args) {
if (arg.StartsWith("/") || arg.StartsWith("-"))
switch (arg.ToLower()[1]) {
case '?':
if (greeting != null)
greeting();
Console.WriteLine("Usage:");
Console.WriteLine(" /i nstall[:service name] Install this service optionally named (service name)");
Console.WriteLine(" /u install[:service name] Uninstall this service optionally named (service name)");
Console.WriteLine(" /c onsole Run as a console application");
Console.WriteLine(" /d ebug Same as /c onsole");
Console.WriteLine(" /? Displays this help");
Console.WriteLine(" /h elp Same as /?");
return RunState.ExitNow;
case 'i': // install /i:"Name of this service"
if (!Privileges.HaveAdministratorPrivileges()) {
if (System.Environment.OSVersion.Version.Major >= 6) {
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
p.StartInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location;
// p.StartInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().Location; // Application.ExecutablePath;
p.StartInfo.Arguments = string.Join(" ", args);
p.StartInfo.UseShellExecute = true;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.RedirectStandardError = false;
p.StartInfo.Verb = "runas";
p.Start();
p.WaitForExit();
return RunState.ExitNow;
}
Console.Error.WriteLine("Access Denied. Administrator permissions are needed.");
Console.Error.WriteLine("Use 'run as administrator' to install this service.");
return RunState.ExitNow;
}
if (arg.Contains(':')) {
var s = arg.Substring(arg.IndexOf(':') + 1);
if (s.StartsWith("$")) {
setup.DisplayName = string.Format("{0} ({1})", setup.DisplayName, s.Replace("$", ""));
setup.ServiceName = string.Format("{0}{1}", setup.ServiceName, s);
} else {
setup.DisplayName = arg.Substring(arg.IndexOf(':') + 1);
setup.ServiceName = arg.Substring(arg.IndexOf(':') + 1);
}
}
try {
using (var installer = new AssemblyInstaller(typeof(TService).Assembly, null)) {
installer.UseNewContext = true;
installer.Install(new Dictionary<object, object>());
}
} catch (Exception ex) {
logger.Fatal(ex.Message);
}
return RunState.ExitNow;
case 'u': // uninstall /u:"Name of this service"
if (!Privileges.HaveAdministratorPrivileges()) {
if (System.Environment.OSVersion.Version.Major >= 6) {
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
// AppDomain.CurrentDomain.ApplicationIdentity.FullName
p.StartInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location;
// p.StartInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().Location; // Application.ExecutablePath;
p.StartInfo.Arguments = string.Join(" ", args);
p.StartInfo.UseShellExecute = true;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.RedirectStandardError = false;
p.StartInfo.Verb = "runas";
p.Start();
p.WaitForExit();
return RunState.ExitNow;
}
Console.Error.WriteLine("Access Denied. Administrator permissions are needed.");
Console.Error.WriteLine("Use 'run as administrator' to uninstall this service.");
return RunState.ExitNow;
}
if (arg.Contains(':')) {
var s = arg.Substring(arg.IndexOf(':') + 1);
if (s.StartsWith("$")) {
setup.DisplayName = string.Format("{0} ({1})", setup.DisplayName, s.Replace("$", ""));
setup.ServiceName = string.Format("{0}{1}", setup.ServiceName, s);
} else {
setup.DisplayName = arg.Substring(arg.IndexOf(':') + 1);
setup.ServiceName = arg.Substring(arg.IndexOf(':') + 1);
}
}
try {
using (var installer = new AssemblyInstaller(typeof(TService).Assembly, null)) {
installer.UseNewContext = true;
installer.Uninstall(new Dictionary<object, object>());
}
} catch (Exception ex) {
logger.Fatal(ex.Message);
}
return RunState.ExitNow;
case 'c': // console
case 'd': // debug -> to console
return RunState.RunConsole;
}
}
return Environment.UserInteractive ? RunState.RunConsole : RunState.RunService;
}
/// <summary>
/// Gets or sets a value indicating whether [time to exit].
/// </summary>
/// <value>
/// <c>true</c> if [time to exit]; otherwise, <c>false</c>.
/// </value>
public bool TimeToExit { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [run as service].
/// </summary>
/// <value>
/// <c>true</c> if [run as service]; otherwise, <c>false</c>.
/// </value>
public bool RunAsService { get; set; }
}
static private class Privileges
{
/// <summary>
/// Determines whether the executing context has administrator privileges.
/// </summary>
/// <returns></returns>
static public bool HaveAdministratorPrivileges() {
return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
}
}
}
}
| 45.329718 | 191 | 0.473322 | [
"Apache-2.0"
] | DesertSoftware/Solutions | Solutions.Service/ServiceFactory.cs | 20,899 | C# |
using System.Text.RegularExpressions;
namespace Toggl.Shared
{
public struct Email
{
//Taken from reference source: https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/EmailAddressAttribute.cs#L54
private const string pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
private static readonly Regex regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
private readonly string email;
public static Email Empty { get; } = new Email("");
public bool IsValid { get; }
public bool IsEmpty => string.IsNullOrEmpty(email);
private Email(string email)
{
this.email = email;
IsValid = CheckEmailStringValidity(email);
}
public override string ToString() => email;
public Email TrimmedEnd()
=> new Email(email.TrimEnd());
public static Email From(string email) => new Email(email);
public static bool CheckEmailStringValidity(string email)
=> email != null && regex.Match(email).Length > 0;
}
}
| 56.305556 | 948 | 0.601381 | [
"BSD-3-Clause"
] | moljac/mobileapp | Toggl.Shared/Email.cs | 2,029 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Jag.Embc.Interfaces.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq; using System.ComponentModel.DataAnnotations.Schema;
/// <summary>
/// msdyn_postconfig
/// </summary>
public partial class MicrosoftDynamicsCRMmsdynPostconfig
{
/// <summary>
/// Initializes a new instance of the
/// MicrosoftDynamicsCRMmsdynPostconfig class.
/// </summary>
public MicrosoftDynamicsCRMmsdynPostconfig()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// MicrosoftDynamicsCRMmsdynPostconfig class.
/// </summary>
public MicrosoftDynamicsCRMmsdynPostconfig(string msdynEntitydisplayname = default(string), string _modifiedonbehalfbyValue = default(string), int? importsequencenumber = default(int?), string msdynFollowingviewid2 = default(string), int? statecode = default(int?), int? msdynOtc = default(int?), string _modifiedbyValue = default(string), string _organizationidValue = default(string), string _createdonbehalfbyValue = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), string msdynEntityname = default(string), long? versionnumber = default(long?), string msdynStatus = default(string), int? timezoneruleversionnumber = default(int?), int? statuscode = default(int?), string _createdbyValue = default(string), int? utcconversiontimezonecode = default(int?), bool? msdynConfigurewall = default(bool?), System.DateTimeOffset? overriddencreatedon = default(System.DateTimeOffset?), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), string msdynPostconfigid = default(string), string msdynFollowingviewid = default(string), MicrosoftDynamicsCRMsystemuser createdby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser createdonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMorganization organizationid = default(MicrosoftDynamicsCRMorganization), IList<MicrosoftDynamicsCRMsyncerror> msdynPostconfigSyncErrors = default(IList<MicrosoftDynamicsCRMsyncerror>), IList<MicrosoftDynamicsCRMasyncoperation> msdynPostconfigAsyncOperations = default(IList<MicrosoftDynamicsCRMasyncoperation>), IList<MicrosoftDynamicsCRMmailboxtrackingfolder> msdynPostconfigMailboxTrackingFolders = default(IList<MicrosoftDynamicsCRMmailboxtrackingfolder>), IList<MicrosoftDynamicsCRMprocesssession> msdynPostconfigProcessSession = default(IList<MicrosoftDynamicsCRMprocesssession>), IList<MicrosoftDynamicsCRMbulkdeletefailure> msdynPostconfigBulkDeleteFailures = default(IList<MicrosoftDynamicsCRMbulkdeletefailure>), IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess> msdynPostconfigPrincipalObjectAttributeAccesses = default(IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess>), IList<MicrosoftDynamicsCRMmsdynPostruleconfig> msdynPostconfigMsdynPostruleconfig = default(IList<MicrosoftDynamicsCRMmsdynPostruleconfig>), IList<MicrosoftDynamicsCRMmsdynWallsavedquery> msdynPostconfigWallsavedquery = default(IList<MicrosoftDynamicsCRMmsdynWallsavedquery>))
{
MsdynEntitydisplayname = msdynEntitydisplayname;
this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue;
Importsequencenumber = importsequencenumber;
MsdynFollowingviewid2 = msdynFollowingviewid2;
Statecode = statecode;
MsdynOtc = msdynOtc;
this._modifiedbyValue = _modifiedbyValue;
this._organizationidValue = _organizationidValue;
this._createdonbehalfbyValue = _createdonbehalfbyValue;
Createdon = createdon;
MsdynEntityname = msdynEntityname;
Versionnumber = versionnumber;
MsdynStatus = msdynStatus;
Timezoneruleversionnumber = timezoneruleversionnumber;
Statuscode = statuscode;
this._createdbyValue = _createdbyValue;
Utcconversiontimezonecode = utcconversiontimezonecode;
MsdynConfigurewall = msdynConfigurewall;
Overriddencreatedon = overriddencreatedon;
Modifiedon = modifiedon;
MsdynPostconfigid = msdynPostconfigid;
MsdynFollowingviewid = msdynFollowingviewid;
Createdby = createdby;
Createdonbehalfby = createdonbehalfby;
Modifiedby = modifiedby;
Modifiedonbehalfby = modifiedonbehalfby;
Organizationid = organizationid;
MsdynPostconfigSyncErrors = msdynPostconfigSyncErrors;
MsdynPostconfigAsyncOperations = msdynPostconfigAsyncOperations;
MsdynPostconfigMailboxTrackingFolders = msdynPostconfigMailboxTrackingFolders;
MsdynPostconfigProcessSession = msdynPostconfigProcessSession;
MsdynPostconfigBulkDeleteFailures = msdynPostconfigBulkDeleteFailures;
MsdynPostconfigPrincipalObjectAttributeAccesses = msdynPostconfigPrincipalObjectAttributeAccesses;
MsdynPostconfigMsdynPostruleconfig = msdynPostconfigMsdynPostruleconfig;
MsdynPostconfigWallsavedquery = msdynPostconfigWallsavedquery;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_entitydisplayname")]
public string MsdynEntitydisplayname { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_modifiedonbehalfby_value")]
public string _modifiedonbehalfbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "importsequencenumber")]
public int? Importsequencenumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_followingviewid2")]
public string MsdynFollowingviewid2 { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "statecode")]
public int? Statecode { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_otc")]
public int? MsdynOtc { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_modifiedby_value")]
public string _modifiedbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_organizationid_value")]
public string _organizationidValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_createdonbehalfby_value")]
public string _createdonbehalfbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdon")]
public System.DateTimeOffset? Createdon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_entityname")]
public string MsdynEntityname { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "versionnumber")]
public long? Versionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_status")]
public string MsdynStatus { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "timezoneruleversionnumber")]
public int? Timezoneruleversionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "statuscode")]
public int? Statuscode { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_createdby_value")]
public string _createdbyValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "utcconversiontimezonecode")]
public int? Utcconversiontimezonecode { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_configurewall")]
public bool? MsdynConfigurewall { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "overriddencreatedon")]
public System.DateTimeOffset? Overriddencreatedon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedon")]
public System.DateTimeOffset? Modifiedon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_postconfigid")]
public string MsdynPostconfigid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_followingviewid")]
public string MsdynFollowingviewid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdby")]
public MicrosoftDynamicsCRMsystemuser Createdby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdonbehalfby")]
public MicrosoftDynamicsCRMsystemuser Createdonbehalfby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedby")]
public MicrosoftDynamicsCRMsystemuser Modifiedby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedonbehalfby")]
public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfby { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "organizationid")]
public MicrosoftDynamicsCRMorganization Organizationid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_postconfig_SyncErrors")]
[NotMapped] public IList<MicrosoftDynamicsCRMsyncerror> MsdynPostconfigSyncErrors { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_postconfig_AsyncOperations")]
[NotMapped] public IList<MicrosoftDynamicsCRMasyncoperation> MsdynPostconfigAsyncOperations { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_postconfig_MailboxTrackingFolders")]
[NotMapped] public IList<MicrosoftDynamicsCRMmailboxtrackingfolder> MsdynPostconfigMailboxTrackingFolders { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_postconfig_ProcessSession")]
[NotMapped] public IList<MicrosoftDynamicsCRMprocesssession> MsdynPostconfigProcessSession { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_postconfig_BulkDeleteFailures")]
[NotMapped] public IList<MicrosoftDynamicsCRMbulkdeletefailure> MsdynPostconfigBulkDeleteFailures { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_postconfig_PrincipalObjectAttributeAccesses")]
[NotMapped] public IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess> MsdynPostconfigPrincipalObjectAttributeAccesses { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_postconfig_msdyn_postruleconfig")]
[NotMapped] public IList<MicrosoftDynamicsCRMmsdynPostruleconfig> MsdynPostconfigMsdynPostruleconfig { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "msdyn_postconfig_wallsavedquery")]
[NotMapped] public IList<MicrosoftDynamicsCRMmsdynWallsavedquery> MsdynPostconfigWallsavedquery { get; set; }
}
}
| 47.952756 | 2,631 | 0.68358 | [
"Apache-2.0"
] | CodingVelocista/embc-ess | embc-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMmsdynPostconfig.cs | 12,180 | C# |
namespace SpyfallBot.Domain.EndGame
{
using System.Collections.Generic;
using SpyfallBot.Messaging;
using SpyfallBot.Persistence;
public sealed class EndGameCommandHandler : ICommandHandler<EndGameCommand>
{
private readonly IStore store;
public EndGameCommandHandler(IStore store)
{
this.store = store;
}
public IEnumerable<IEvent> Handle(EndGameCommand payload)
{
var state = this.store.Load();
if (state.CurrentGame == null)
{
throw new NoGameInProgressException();
}
yield return new GameEndedEvent();
}
}
}
| 23.655172 | 79 | 0.597668 | [
"CC0-1.0"
] | iaingalloway/SpyfallBot | src/SpyfallBot/Domain/EndGame/EndGameCommandHandler.cs | 688 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace FormatterWebSite
{
// A System.Security.Principal.SecurityIdentifier like type that works on xplat
public class RecursiveIdentifier : IValidatableObject
{
public RecursiveIdentifier(string identifier)
{
Value = identifier;
}
public string Value { get; }
public RecursiveIdentifier AccountIdentifier => new RecursiveIdentifier(Value);
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
return Enumerable.Empty<ValidationResult>();
}
}
} | 31.62963 | 111 | 0.711944 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Mvc/test/WebSites/FormatterWebSite/Models/RecursiveIdentifier.cs | 856 | C# |
// ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace DurableTask
{
/// <summary>
/// Configuration for various TaskHub settings
/// </summary>
public sealed class TaskHubDescription
{
/// <summary>
/// Maximum number of times the task orchestration dispatcher will try to
/// process an orchestration message before giving up
/// </summary>
public int MaxTaskOrchestrationDeliveryCount { get; set; }
/// <summary>
/// Maximum number of times the task activity dispatcher will try to
/// process an orchestration message before giving up
/// </summary>
public int MaxTaskActivityDeliveryCount { get; set; }
/// <summary>
/// Maximum number of times the tracking dispatcher will try to
/// process an orchestration message before giving up
/// </summary>
public int MaxTrackingDeliveryCount { get; set; }
/// <summary>
/// Creates a TaskHubDescription object with standard settings
/// </summary>
/// <returns></returns>
public static TaskHubDescription CreateDefaultDescription()
{
return new TaskHubDescription
{
MaxTaskActivityDeliveryCount = FrameworkConstants.MaxDeliveryCount,
MaxTaskOrchestrationDeliveryCount = FrameworkConstants.MaxDeliveryCount,
MaxTrackingDeliveryCount = FrameworkConstants.MaxDeliveryCount,
};
}
}
} | 42.792453 | 88 | 0.601411 | [
"Apache-2.0"
] | mathewc/durabletask | Framework/TaskHubDescription.cs | 2,270 | C# |
using Megaman5Randomizer.RandomizationStrategy;
using RomWriter;
using System;
using System.Collections.Generic;
using System.Text;
namespace Megaman5Randomizer
{
public class Randomizer
{
public int Seed {
get; set;
}
public Random RNG {
get; set;
}
List<IRandomizationStrategy> randomizers;
public void RandomizeRom(Config config, string path) {
InitRNG();
RomPatcher patcher = new RomPatcher(path);
randomizers = new List<IRandomizationStrategy>();
if (config.RandomizeEnemies) {
randomizers.Add(new NormalEnemyRandomizer());
}
if (config.RandomizeWeaponRewards) {
randomizers.Add(new WeaponGetRandomizer());
}
if(config.RandomizeVulnerability) {
randomizers.Add(new WeaknessRandomizer());
}
if(config.RandomizeBosses) {
randomizers.Add(new BossRandomizer());
}
RunRandomizers(patcher, config);
patcher.ApplyRomPatch();
}
void InitRNG() {
if(Seed <= 0) {
Seed = Guid.NewGuid().GetHashCode();
}
RNG = new Random(Seed);
}
void RunRandomizers(RomPatcher patcher, Config config) {
randomizers.ForEach(randomizer => {
randomizer.Randomize(RNG, patcher, config);
});
}
}
}
| 25.098361 | 64 | 0.54017 | [
"MIT"
] | dmarchand/mm5randomizer | mm5rando/Megaman5Randomizer/Randomizer.cs | 1,533 | C# |
using System;
using System.Runtime.Serialization;
namespace SatelliteService
{
public class SatelliteServiceException : Exception
{
public SatelliteServiceException()
{
}
public SatelliteServiceException(string message) : base(message)
{
}
public SatelliteServiceException(string message, Exception innerException) : base(message, innerException)
{
}
protected SatelliteServiceException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
} | 24.125 | 115 | 0.661485 | [
"Apache-2.0"
] | adoconnection/AspNetDeploy | SatelliteService/SatelliteServiceException.cs | 581 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Composable2")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Composable2")]
[assembly: System.Reflection.AssemblyTitleAttribute("Composable2")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 40.958333 | 80 | 0.648016 | [
"Apache-2.0"
] | beyondnetPeru/BeyondNet.MyNetSamples | delegates-events-lambda/Finished/Delegates/Composable2/obj/Debug/net5.0/Composable2.AssemblyInfo.cs | 983 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Xunit;
namespace Linq.Extras.Tests.XEnumerableTests
{
public class FlattenTests
{
[Fact]
public void Flatten_Throws_If_Source_Is_Null()
{
IEnumerable<Foo> source = null;
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
// ReSharper disable once AssignNullToNotNullAttribute
var ex = Assert.Throws<ArgumentNullException>(() => source.Flatten(f => f.Children, TreeTraversalMode.DepthFirst));
ex.ParamName.Should().Be("source");
}
[Fact]
public void Flatten_Throws_If_ChildrenSelector_Is_Null()
{
IEnumerable<Foo> source = Enumerable.Empty<Foo>().ForbidEnumeration();
Func<Foo, IEnumerable<Foo>> childrenSelector = null;
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
// ReSharper disable once AssignNullToNotNullAttribute
var ex = Assert.Throws<ArgumentNullException>(() => source.Flatten(childrenSelector, TreeTraversalMode.DepthFirst));
ex.ParamName.Should().Be("childrenSelector");
}
[Fact]
public void Flatten_Throws_If_ResultSelector_Is_Null()
{
var source = Enumerable.Empty<Foo>().ForbidEnumeration();
Func<Foo, int> resultSelector = null;
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
// ReSharper disable once AssignNullToNotNullAttribute
var ex = Assert.Throws<ArgumentNullException>(() => source.Flatten(f => f.Children, TreeTraversalMode.DepthFirst, resultSelector));
ex.ParamName.Should().Be("resultSelector");
}
[Fact]
public void Flatten_Throws_If_ResultSelector_With_Level_Is_Null()
{
var source = Enumerable.Empty<Foo>().ForbidEnumeration();
Func<Foo, int, int> resultSelector = null;
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
// ReSharper disable once AssignNullToNotNullAttribute
var ex = Assert.Throws<ArgumentNullException>(() => source.Flatten(f => f.Children, TreeTraversalMode.DepthFirst, resultSelector));
ex.ParamName.Should().Be("resultSelector");
}
[Fact]
public void Flatten_Throws_If_TraversalMode_Is_Invalid()
{
var source = Enumerable.Empty<Foo>().ForbidEnumeration();
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => source.Flatten(f => f.Children, (TreeTraversalMode)42));
ex.ParamName.Should().Be("traversalMode");
}
[Fact]
public void Flatten_Returns_Flat_Sequence_Of_Nodes_DepthFirst()
{
var source = GetFoos().ForbidMultipleEnumeration();
var result = source.Flatten(f => f.Children, TreeTraversalMode.DepthFirst);
var expected = new[] { 1, 2, 3, 4, 5, 6, 7 };
var actual = result.Select(f => f.Id);
actual.Should().Equal(expected);
}
[Fact]
public void Flatten_Returns_Flat_Sequence_Of_Nodes_BreadthFirst()
{
var source = GetFoos().ForbidMultipleEnumeration();
var result = source.Flatten(f => f.Children, TreeTraversalMode.BreadthFirst);
var expected = new[] { 1, 6, 2, 3, 7, 4, 5 };
var actual = result.Select(f => f.Id);
actual.Should().Equal(expected);
}
[Fact]
public void Flatten_With_ResultSelector_Returns_Flat_Sequence_DepthFirst()
{
var source = GetFoos().ForbidMultipleEnumeration();
var actual = source.Flatten(f => f.Children, TreeTraversalMode.DepthFirst, f => f.Id);
var expected = new[] { 1, 2, 3, 4, 5, 6, 7 };
actual.Should().Equal(expected);
}
[Fact]
public void Flatten_With_ResultSelector_Returns_Flat_Sequence_BreadthFirst()
{
var source = GetFoos().ForbidMultipleEnumeration();
var actual = source.Flatten(f => f.Children, TreeTraversalMode.BreadthFirst, f => f.Id);
var expected = new[] { 1, 6, 2, 3, 7, 4, 5 };
actual.Should().Equal(expected);
}
[Fact]
public void Flatten_With_ResultSelector_With_Level_Returns_Flat_Sequence_DepthFirst()
{
var source = GetFoos().ForbidMultipleEnumeration();
var actual = source.Flatten(f => f.Children, TreeTraversalMode.DepthFirst, (f, level) => new { f.Id, Level = level});
IEnumerable expected = new[]
{
new { Id = 1, Level = 0 },
new { Id = 2, Level = 1 },
new { Id = 3, Level = 1 },
new { Id = 4, Level = 2 },
new { Id = 5, Level = 2 },
new { Id = 6, Level = 0 },
new { Id = 7, Level = 1 },
};
actual.Should().Equal(expected);
}
[Fact]
public void Flatten_With_ResultSelector_With_Level_Returns_Flat_Sequence_BreadthFirst()
{
var source = GetFoos().ForbidMultipleEnumeration();
var actual = source.Flatten(f => f.Children, TreeTraversalMode.BreadthFirst, (f, level) => new { f.Id, Level = level });
IEnumerable expected = new[]
{
new { Id = 1, Level = 0 },
new { Id = 6, Level = 0 },
new { Id = 2, Level = 1 },
new { Id = 3, Level = 1 },
new { Id = 7, Level = 1 },
new { Id = 4, Level = 2 },
new { Id = 5, Level = 2 },
};
actual.Should().Equal(expected);
}
private static IEnumerable<Foo> GetFoos()
{
return new[]
{
new Foo
{
Id = 1,
Children = new[]
{
new Foo { Id = 2 },
new Foo
{
Id = 3,
Children = new[]
{
new Foo { Id = 4 },
new Foo { Id = 5 }
}
}
}
},
new Foo
{
Id = 6,
Children = new[]
{
new Foo { Id = 7 }
}
}
};
}
class Foo
{
public Foo() { Children = new Foo[0]; }
public int Id { get; set; }
public IList<Foo> Children { get; set; }
}
}
}
| 42.814607 | 143 | 0.480383 | [
"Apache-2.0"
] | lbragaglia/Linq.Extras | tests/Linq.Extras.Tests/XEnumerableTests/FlattenTests.cs | 7,623 | C# |
using Medallion.Threading.Oracle;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
namespace Medallion.Threading.Tests.Oracle
{
public class OracleDistributedSynchronizationProviderTest
{
[Test]
public void TestArgumentValidation()
{
Assert.Throws<ArgumentNullException>(() => new OracleDistributedSynchronizationProvider(default(string)!));
Assert.Throws<ArgumentNullException>(() => new OracleDistributedSynchronizationProvider(default(IDbConnection)!));
}
[Test]
public async Task BasicTest()
{
var provider = new OracleDistributedSynchronizationProvider(TestingOracleDb.DefaultConnectionString);
const string LockName = TargetFramework.Current + "ProviderBasicTest";
await using (await provider.AcquireLockAsync(LockName))
{
await using var handle = await provider.TryAcquireLockAsync(LockName);
Assert.IsNull(handle);
}
await using (await provider.AcquireReadLockAsync(LockName))
{
await using var readHandle = await provider.TryAcquireReadLockAsync(LockName);
Assert.IsNotNull(readHandle);
await using (var upgradeHandle = await provider.TryAcquireUpgradeableReadLockAsync(LockName))
{
Assert.IsNotNull(upgradeHandle);
Assert.IsFalse(await upgradeHandle!.TryUpgradeToWriteLockAsync());
}
await using var writeHandle = await provider.TryAcquireWriteLockAsync(LockName);
Assert.IsNull(writeHandle);
}
}
}
}
| 35.78 | 126 | 0.648407 | [
"MIT"
] | SammyEnigma/DistributedLock | DistributedLock.Tests/Tests/Oracle/OracleDistributedSynchronizationProviderTest.cs | 1,791 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kinesisvideo-2017-09-30.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.KinesisVideo.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.KinesisVideo.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListSignalingChannels operation
/// </summary>
public class ListSignalingChannelsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListSignalingChannelsResponse response = new ListSignalingChannelsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("ChannelInfoList", targetDepth))
{
var unmarshaller = new ListUnmarshaller<ChannelInfo, ChannelInfoUnmarshaller>(ChannelInfoUnmarshaller.Instance);
response.ChannelInfoList = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("NextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException"))
{
return new AccessDeniedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ClientLimitExceededException"))
{
return new ClientLimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidArgumentException"))
{
return new InvalidArgumentException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonKinesisVideoException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static ListSignalingChannelsResponseUnmarshaller _instance = new ListSignalingChannelsResponseUnmarshaller();
internal static ListSignalingChannelsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListSignalingChannelsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.913043 | 172 | 0.659511 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/KinesisVideo/Generated/Model/Internal/MarshallTransformations/ListSignalingChannelsResponseUnmarshaller.cs | 4,705 | C# |
using System.Collections.Generic;
using AppName.Web.Models;
namespace AppName.Web.Repositories
{
public interface IAirportRepository
{
List<Airport> GetAirports();
Airport GetAirport(string code);
void AddAirport(AirportInput airport);
}
} | 19.928571 | 46 | 0.702509 | [
"MIT"
] | ryanrodemoyer/AccrualCalculator | src/presentation/AccrualCalculator.Web/Repositories/Contracts/IAirportRepository.cs | 281 | C# |
namespace KvmSwitch.Tests.Hardware.DDC
{
using System;
using System.Collections.Generic;
using FluentAssertions;
using KvmSwitch.Hardware.DDC;
using Xunit;
public class DisplayCapabilitiesTest
{
[Fact]
public void Ctor_Does_Not_Throw_If_Capabilities_Are_Null()
{
#pragma warning disable CA1806 // Do not ignore method results
var action = new Action(() => new DisplayCapabilities(null));
#pragma warning restore CA1806 // Do not ignore method results
action.Should().NotThrow();
}
[Fact]
public void Ctor_Does_Not_Throw_If_Capabilities_Are_Empty()
{
var action = new Action(() =>
{
var displayCapabilities = new DisplayCapabilities(new List<CapabilityTag>());
});
action.Should().NotThrow();
}
[Fact]
public void Assigns_Model_In_Ctor()
{
var displayCapabilities = new DisplayCapabilities(new List<CapabilityTag>
{new CapabilityTag {Name = "model", Tags = {new CapabilityTag {Name = "test"}}}});
displayCapabilities.Model.Should().Be("test");
}
[Fact]
public void Assigns_Protocol_In_Ctor()
{
var displayCapabilities = new DisplayCapabilities(new List<CapabilityTag>
{new CapabilityTag {Name = "prot", Tags = {new CapabilityTag {Name = "test"}}}});
displayCapabilities.Protocol.Should().Be("test");
}
[Fact]
public void Assigns_Type_In_Ctor()
{
var displayCapabilities = new DisplayCapabilities(new List<CapabilityTag>
{new CapabilityTag {Name = "type", Tags = {new CapabilityTag {Name = "test"}}}});
displayCapabilities.Type.Should().Be("test");
}
[Fact]
public void Assigns_MccsVersion_In_Ctor()
{
var displayCapabilities = new DisplayCapabilities(new List<CapabilityTag>
{new CapabilityTag {Name = "mccs_ver", Tags = {new CapabilityTag {Name = "1.2"}}}});
displayCapabilities.MccsVersion.Major.Should().Be(1);
displayCapabilities.MccsVersion.Minor.Should().Be(2);
}
[Fact]
public void Ctor_Does_Not_Throw_On_Invalid_MccsVersion()
{
DisplayCapabilities displayCapabilities = null;
var action = new Action(() => displayCapabilities = new DisplayCapabilities(new List<CapabilityTag>
{new CapabilityTag {Name = "mccs_ver", Tags = {new CapabilityTag {Name = "alpha beta"}}}}));
action.Should().NotThrow();
displayCapabilities.MccsVersion.Should().Be(null);
}
[Fact]
public void Assigns_VirtualControlPanel_In_Ctor()
{
var vcpTag = new CapabilityTag { Name = "vcp" };
var displayCapabilities = new DisplayCapabilities(new List<CapabilityTag> { vcpTag });
displayCapabilities.VirtualControlPanel.Should().Be(vcpTag);
}
}
}
| 34.640449 | 111 | 0.604282 | [
"MIT"
] | Holger-H/KvmSwitch | tests/KvmSwitch.Tests/Hardware/DDC/DisplayCapabilitiesTest.cs | 3,085 | C# |
#region Copyright (C) 2005 Rob Blackwell & Active Web Solutions.
//
// L Sharp .NET, a powerful lisp-based scripting language for .NET.
// Copyright (C) 2005 Rob Blackwell & Active Web Solutions.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free
// Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
#endregion
using System;
namespace LSharp
{
/// <summary>
/// All special forms take a list of arguments and a lexical environment
/// </summary>
public delegate Object SpecialForm(Cons argument, Environment environment);
[AttributeUsage(AttributeTargets.Class)]
public sealed class SpecialFormAttribute : Attribute
{
}
}
| 36 | 77 | 0.727623 | [
"BSD-3-Clause"
] | leppie/IronScheme.Editor | LSharp/SpecialForm.cs | 1,296 | C# |
using UnityEngine;
using UnityEngine.UI;
public class Event_Text : MonoBehaviour
{
private void Start()
{
if (null == Event_EventManager._buttonClickedEvent)
{
Debug.LogError("Event_EventManager._buttonClickedEvent is null.");
return;
}
Event_EventManager._buttonClickedEvent.AddListener(UpdateText);
}
private void OnDestroy()
{
if (null == Event_EventManager._buttonClickedEvent)
{
Debug.LogError("Event_EventManager._buttonClickedEvent is null.");
return;
}
Event_EventManager._buttonClickedEvent.RemoveListener(UpdateText);
}
private void UpdateText()
{
Text textComponent = gameObject.GetComponent<Text>();
if (null == textComponent)
{
Debug.LogError("textComponent is null.");
}
textComponent.text = Random.Range(0, 100) + "";
}
}
| 24.307692 | 78 | 0.611814 | [
"Unlicense"
] | DominicFrei/UnityExamples | Assets/Event/Event_Text.cs | 950 | C# |
#Mon Feb 27 04:08:31 GMT 2017
lib/com.ibm.ws.cdi.1.2.jndi.1.0.0_1.0.16.jar=92dfcc5a7cca30141ee29aef92f9bc06
lib/features/com.ibm.websphere.appserver.cdi1.2-jndi1.0.mf=581a7e08d9ede0dadf1a20f7a73986b5
| 50 | 91 | 0.82 | [
"Apache-2.0"
] | jeffwdg/chansyapp | target/liberty/wlp/lib/features/checksums/com.ibm.websphere.appserver.cdi1.2-jndi1.0.cs | 200 | C# |
// Copyright (c) Andrew Arnott. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Nerdbank.Streams
{
using System;
using System.Buffers;
using System.CodeDom.Compiler;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft;
using Microsoft.VisualStudio.Threading;
/// <content>
/// Contains the <see cref="Channel"/> nested type.
/// </content>
public partial class MultiplexingStream
{
/// <summary>
/// An individual channel within a <see cref="Streams.MultiplexingStream"/>.
/// </summary>
[DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")]
public class Channel : IDisposableObservable, IDuplexPipe
{
/// <summary>
/// This task source completes when the channel has been accepted, rejected, or the offer is canceled.
/// </summary>
private readonly TaskCompletionSource<AcceptanceParameters> acceptanceSource = new TaskCompletionSource<AcceptanceParameters>(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>
/// The source for the <see cref="Completion"/> property.
/// </summary>
private readonly TaskCompletionSource<object?> completionSource = new TaskCompletionSource<object?>();
/// <summary>
/// The source for a token that will be canceled when this channel has completed.
/// </summary>
private readonly CancellationTokenSource disposalTokenSource = new CancellationTokenSource();
/// <summary>
/// The source for the <see cref="OptionsApplied"/> property. May be null if options were provided in ctor.
/// </summary>
private readonly TaskCompletionSource<object?>? optionsAppliedTaskSource;
/// <summary>
/// Tracks the end of any copying from the mxstream to this channel.
/// </summary>
private readonly AsyncManualResetEvent mxStreamIOWriterCompleted = new AsyncManualResetEvent();
/// <summary>
/// Gets a signal which indicates when the <see cref="RemoteWindowRemaining"/> is non-zero.
/// </summary>
private readonly AsyncManualResetEvent remoteWindowHasCapacity = new AsyncManualResetEvent(initialState: true);
/// <summary>
/// The party-qualified id of the channel.
/// </summary>
private readonly QualifiedChannelId channelId;
/// <summary>
/// The number of bytes transmitted from here but not yet acknowledged as processed from there,
/// and thus occupying some portion of the full <see cref="AcceptanceParameters.RemoteWindowSize"/>.
/// </summary>
/// <remarks>
/// All access to this field should be made within a lock on the <see cref="SyncObject"/> object.
/// </remarks>
private long remoteWindowFilled = 0;
/// <summary>
/// The number of bytes that may be transmitted before receiving acknowledgment that those bytes have been processed.
/// </summary>
/// <remarks>
/// This field is set to the value of <see cref="OfferParameters.RemoteWindowSize"/> if we accepted the channel,
/// or the value of <see cref="AcceptanceParameters.RemoteWindowSize"/> if we offered the channel.
/// </remarks>
private long? remoteWindowSize;
/// <summary>
/// The number of bytes that may be received and buffered for processing.
/// </summary>
/// <remarks>
/// This field is set to the value of <see cref="OfferParameters.RemoteWindowSize"/> if we offered the channel,
/// or the value of <see cref="AcceptanceParameters.RemoteWindowSize"/> if we accepted the channel.
/// </remarks>
private long? localWindowSize;
/// <summary>
/// Indicates whether the <see cref="Dispose"/> method has been called.
/// </summary>
private bool isDisposed;
/// <summary>
/// The <see cref="PipeReader"/> to use to get data to be transmitted over the <see cref="Streams.MultiplexingStream"/>.
/// </summary>
private PipeReader? mxStreamIOReader;
/// <summary>
/// A task that represents the completion of the <see cref="mxStreamIOReader"/>,
/// signifying the point where we will stop relaying data from the channel to the <see cref="MultiplexingStream"/> for transmission to the remote party.
/// </summary>
private Task? mxStreamIOReaderCompleted;
/// <summary>
/// The <see cref="PipeWriter"/> the underlying <see cref="Streams.MultiplexingStream"/> should use.
/// </summary>
private PipeWriter? mxStreamIOWriter;
/// <summary>
/// The I/O to expose on this channel if <see cref="ChannelOptions.ExistingPipe"/> was not specified;
/// otherwise it is the buffering pipe we use as an intermediary with the specified <see cref="ChannelOptions.ExistingPipe"/>.
/// </summary>
private IDuplexPipe? channelIO;
/// <summary>
/// The value of <see cref="ChannelOptions.ExistingPipe"/> as it was when we received it.
/// We don't use this field, but we set it for diagnostic purposes later.
/// </summary>
private IDuplexPipe? existingPipe;
/// <summary>
/// A value indicating whether this <see cref="Channel"/> was created or accepted with a non-null value for <see cref="ChannelOptions.ExistingPipe"/>.
/// </summary>
private bool? existingPipeGiven;
/// <summary>
/// Initializes a new instance of the <see cref="Channel"/> class.
/// </summary>
/// <param name="multiplexingStream">The owning <see cref="Streams.MultiplexingStream"/>.</param>
/// <param name="channelId">The party-qualified ID of the channel.</param>
/// <param name="offerParameters">The parameters of the channel from the offering party.</param>
/// <param name="channelOptions">The channel options. Should only be null if the channel is created in response to an offer that is not immediately accepted.</param>
internal Channel(MultiplexingStream multiplexingStream, QualifiedChannelId channelId, OfferParameters offerParameters, ChannelOptions? channelOptions = null)
{
Requires.NotNull(multiplexingStream, nameof(multiplexingStream));
Requires.NotNull(offerParameters, nameof(offerParameters));
this.MultiplexingStream = multiplexingStream;
this.channelId = channelId;
this.OfferParams = offerParameters;
switch (channelId.Source)
{
case ChannelSource.Local:
this.localWindowSize = offerParameters.RemoteWindowSize;
break;
case ChannelSource.Remote:
this.remoteWindowSize = offerParameters.RemoteWindowSize;
break;
case ChannelSource.Seeded:
this.remoteWindowSize = offerParameters.RemoteWindowSize;
this.localWindowSize = offerParameters.RemoteWindowSize;
break;
default:
throw new NotSupportedException();
}
if (channelOptions == null)
{
this.optionsAppliedTaskSource = new TaskCompletionSource<object?>();
}
else
{
this.ApplyChannelOptions(channelOptions);
}
}
/// <summary>
/// Gets the unique ID for this channel.
/// </summary>
/// <remarks>
/// This value is usually shared for an anonymous channel so the remote party
/// can accept it with <see cref="AcceptChannel(int, ChannelOptions)"/> or
/// reject it with <see cref="RejectChannel(int)"/>.
/// </remarks>
[Obsolete("Use " + nameof(QualifiedId) + " instead.")]
public int Id => checked((int)this.channelId.Id);
/// <summary>
/// Gets the unique ID for this channel.
/// </summary>
/// <remarks>
/// This value is usually shared for an anonymous channel so the remote party
/// can accept it with <see cref="AcceptChannel(int, ChannelOptions)"/> or
/// reject it with <see cref="RejectChannel(int)"/>.
/// </remarks>
public QualifiedChannelId QualifiedId => this.channelId;
/// <summary>
/// Gets the mechanism used for tracing activity related to this channel.
/// </summary>
/// <value>A non-null value, once <see cref="ApplyChannelOptions(ChannelOptions)"/> has been called.</value>
public TraceSource? TraceSource { get; private set; }
/// <inheritdoc />
public bool IsDisposed => this.isDisposed || this.Completion.IsCompleted;
/// <summary>
/// Gets the reader used to receive data over the channel.
/// </summary>
/// <exception cref="NotSupportedException">Thrown if the channel was created with a non-null value in <see cref="ChannelOptions.ExistingPipe"/>.</exception>
public PipeReader Input
{
get
{
// Before the user should ever have a chance to call this property (before we expose this Channel object)
// we should have received a ChannelOptions object from them and initialized these fields.
Assumes.True(this.existingPipeGiven.HasValue);
Assumes.NotNull(this.channelIO);
return this.existingPipeGiven.Value ? throw new NotSupportedException(Strings.NotSupportedWhenExistingPipeSpecified) : this.channelIO.Input;
}
}
/// <summary>
/// Gets the writer used to transmit data over the channel.
/// </summary>
/// <exception cref="NotSupportedException">Thrown if the channel was created with a non-null value in <see cref="ChannelOptions.ExistingPipe"/>.</exception>
public PipeWriter Output
{
get
{
// Before the user should ever have a chance to call this property (before we expose this Channel object)
// we should have received a ChannelOptions object from them and initialized these fields.
Assumes.True(this.existingPipeGiven.HasValue);
Assumes.NotNull(this.channelIO);
return this.existingPipeGiven.Value ? throw new NotSupportedException(Strings.NotSupportedWhenExistingPipeSpecified) : this.channelIO.Output;
}
}
/// <summary>
/// Gets a <see cref="Task"/> that completes when the channel is accepted, rejected, or canceled.
/// </summary>
/// <remarks>
/// If the channel is accepted, this task transitions to <see cref="TaskStatus.RanToCompletion"/> state.
/// If the channel offer is canceled, this task transitions to a <see cref="TaskStatus.Canceled"/> state.
/// If the channel offer is rejected, this task transitions to a <see cref="TaskStatus.Canceled"/> state.
/// </remarks>
public Task Acceptance => this.acceptanceSource.Task;
/// <summary>
/// Gets a <see cref="Task"/> that completes when the channel is disposed,
/// which occurs when <see cref="Dispose()"/> is invoked or when both sides
/// have indicated they are done writing to the channel.
/// </summary>
public Task Completion => this.completionSource.Task;
/// <summary>
/// Gets the underlying <see cref="Streams.MultiplexingStream"/> instance.
/// </summary>
public MultiplexingStream MultiplexingStream { get; }
/// <summary>
/// Gets a token that is canceled just before <see cref="Completion" /> has transitioned to its final state.
/// </summary>
internal CancellationToken DisposalToken => this.disposalTokenSource.Token;
internal OfferParameters OfferParams { get; }
internal string Name => this.OfferParams.Name;
internal bool IsAccepted => this.Acceptance.Status == TaskStatus.RanToCompletion;
internal bool IsRejectedOrCanceled => this.Acceptance.Status == TaskStatus.Canceled;
internal bool IsRemotelyTerminated { get; set; }
/// <summary>
/// Gets a <see cref="Task"/> that completes when options have been applied to this <see cref="Channel"/>.
/// </summary>
internal Task OptionsApplied => this.optionsAppliedTaskSource?.Task ?? Task.CompletedTask;
private string DebuggerDisplay => $"{this.QualifiedId.DebuggerDisplay} {this.Name ?? "(anonymous)"}";
/// <summary>
/// Gets an object that can be locked to make critical changes to this instance's fields.
/// </summary>
/// <remarks>
/// We reuse an object we already have to avoid having to create a new System.Object instance just to lock with.
/// </remarks>
private object SyncObject => this.acceptanceSource;
/// <summary>
/// Gets the number of bytes that may be transmitted over this channel given the
/// remaining space in the <see cref="remoteWindowSize"/>.
/// </summary>
private long RemoteWindowRemaining
{
get
{
lock (this.SyncObject)
{
Assumes.True(this.remoteWindowSize > 0);
return this.remoteWindowSize.Value - this.remoteWindowFilled;
}
}
}
/// <summary>
/// Gets a value indicating whether backpressure support is enabled.
/// </summary>
private bool BackpressureSupportEnabled => this.MultiplexingStream.protocolMajorVersion > 1;
/// <summary>
/// Closes this channel and releases all resources associated with it.
/// </summary>
/// <remarks>
/// Because this method may terminate the channel immediately and thus can cause previously queued content to not actually be received by the remote party,
/// consider this method a "break glass" way of terminating a channel. The preferred method is that both sides "complete writing" and let the channel dispose itself.
/// </remarks>
public void Dispose()
{
if (!this.IsDisposed)
{
// The code in this delegate needs to happen in several branches including possibly asynchronously.
// We carefully define it here with no closure so that the C# compiler generates a static field for the delegate
// thus avoiding any extra allocations from reusing code in this way.
Action<object?, object> finalDisposalAction = (exOrAntecedent, state) =>
{
var self = (Channel)state;
self.disposalTokenSource.Cancel();
self.completionSource.TrySetResult(null);
self.MultiplexingStream.OnChannelDisposed(self);
};
this.acceptanceSource.TrySetCanceled();
this.optionsAppliedTaskSource?.TrySetCanceled();
PipeWriter? mxStreamIOWriter;
lock (this.SyncObject)
{
this.isDisposed = true;
mxStreamIOWriter = this.mxStreamIOWriter;
}
// Complete writing so that the mxstream cannot write to this channel any more.
// We must also cancel a pending flush since no one is guaranteed to be reading this any more
// and we don't want to deadlock on a full buffer in a disposed channel's pipe.
mxStreamIOWriter?.Complete();
mxStreamIOWriter?.CancelPendingFlush();
this.mxStreamIOWriterCompleted.Set();
if (this.channelIO != null)
{
// We're using our own Pipe to relay user messages, so we can shutdown writing and allow for our reader to propagate what was already written
// before actually shutting down.
this.channelIO.Output.Complete();
}
else
{
// We don't own the user's PipeWriter to complete it (so they can't write anything more to this channel).
// We can't know whether there is or will be more bytes written to the user's PipeWriter,
// but we need to terminate our reader for their writer as part of reclaiming resources.
// We want to complete reading immediately and cancel any pending read.
this.mxStreamIOReader?.Complete();
this.mxStreamIOReader?.CancelPendingRead();
}
// Unblock the reader that might be waiting on this.
this.remoteWindowHasCapacity.Set();
// As a minor perf optimization, avoid allocating a continuation task if the antecedent is already completed.
if (this.mxStreamIOReaderCompleted?.IsCompleted ?? true)
{
finalDisposalAction(null, this);
}
else
{
this.mxStreamIOReaderCompleted!.ContinueWith(finalDisposalAction!, this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default).Forget();
}
}
}
internal async Task OnChannelTerminatedAsync()
{
if (this.IsDisposed)
{
return;
}
try
{
// We Complete the writer because only the writing (logical) thread should complete it
// to avoid race conditions, and Channel.Dispose can be called from any thread.
var writer = this.GetReceivedMessagePipeWriter();
await writer.CompleteAsync().ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
// We fell victim to a race condition. It's OK to just swallow it because the writer was never created, so it needn't be completed.
}
}
internal async ValueTask OnContentAsync(FrameHeader header, ReadOnlySequence<byte> payload, CancellationToken cancellationToken)
{
PipeWriter writer = this.GetReceivedMessagePipeWriter();
foreach (var segment in payload)
{
try
{
var memory = writer.GetMemory(segment.Length);
segment.CopyTo(memory);
writer.Advance(segment.Length);
}
catch (InvalidOperationException)
{
// Someone completed the writer.
return;
}
}
if (!payload.IsEmpty && this.MultiplexingStream.TraceSource.Switch.ShouldTrace(TraceEventType.Verbose))
{
this.MultiplexingStream.TraceSource.TraceData(TraceEventType.Verbose, (int)TraceEventId.FrameReceivedPayload, payload);
}
ValueTask<FlushResult> flushResult = writer.FlushAsync(cancellationToken);
if (this.BackpressureSupportEnabled)
{
if (!flushResult.IsCompleted)
{
// The incoming data has overrun the size of the write buffer inside the PipeWriter.
// This should never happen if we created the Pipe because we specify the Pause threshold to exceed the window size.
// If it happens, it should be because someone specified an ExistingPipe with an inappropriately sized buffer in its PipeWriter.
Assumes.True(this.existingPipeGiven == true); // Make sure this isn't an internal error
this.Fault(new InvalidOperationException(Strings.ExistingPipeOutputHasPauseThresholdSetTooLow));
}
}
else
{
await flushResult.ConfigureAwait(false);
}
if (flushResult.IsCanceled)
{
// This happens when the channel is disposed (while or before flushing).
Assumes.True(this.IsDisposed);
await writer.CompleteAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Called by the <see cref="MultiplexingStream"/> when when it will not be writing any more data to the channel.
/// </summary>
internal void OnContentWritingCompleted()
{
this.DisposeSelfOnFailure(Task.Run(async delegate
{
if (!this.IsDisposed)
{
try
{
var writer = this.GetReceivedMessagePipeWriter();
await writer.CompleteAsync().ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
if (this.mxStreamIOWriter != null)
{
await this.mxStreamIOWriter.CompleteAsync().ConfigureAwait(false);
}
}
}
else
{
if (this.mxStreamIOWriter != null)
{
await this.mxStreamIOWriter.CompleteAsync().ConfigureAwait(false);
}
}
this.mxStreamIOWriterCompleted.Set();
}));
}
/// <summary>
/// Accepts an offer made by the remote party.
/// </summary>
/// <param name="channelOptions">The options to apply to the channel.</param>
/// <returns>A value indicating whether the offer was accepted. It may fail if the channel was already closed or the offer rescinded.</returns>
internal bool TryAcceptOffer(ChannelOptions channelOptions)
{
lock (this.SyncObject)
{
// If the local window size has already been determined, we have to keep that since it can't be expanded once the Pipe is created.
// Otherwise use what the ChannelOptions asked for, so long as it is no smaller than the default channel size, since we can't make it smaller either.
this.localWindowSize ??= channelOptions.ChannelReceivingWindowSize is long windowSize ? Math.Max(windowSize, this.MultiplexingStream.DefaultChannelReceivingWindowSize) : this.MultiplexingStream.DefaultChannelReceivingWindowSize;
}
var acceptanceParameters = new AcceptanceParameters(this.localWindowSize.Value);
if (this.acceptanceSource.TrySetResult(acceptanceParameters))
{
if (this.QualifiedId.Source != ChannelSource.Seeded)
{
var payload = this.MultiplexingStream.formatter.Serialize(acceptanceParameters);
this.MultiplexingStream.SendFrame(
new FrameHeader
{
Code = ControlCode.OfferAccepted,
ChannelId = this.QualifiedId,
},
payload,
CancellationToken.None);
}
try
{
this.ApplyChannelOptions(channelOptions);
return true;
}
catch (ObjectDisposedException)
{
// A (harmless) race condition was hit.
// Swallow it and return false below.
}
}
return false;
}
/// <summary>
/// Occurs when the remote party has accepted our offer of this channel.
/// </summary>
/// <param name="acceptanceParameters">The channel parameters provided by the accepting party.</param>
/// <returns>A value indicating whether the acceptance went through; <c>false</c> if the channel is already accepted, rejected or offer rescinded.</returns>
internal bool OnAccepted(AcceptanceParameters acceptanceParameters)
{
lock (this.SyncObject)
{
if (this.acceptanceSource.TrySetResult(acceptanceParameters))
{
this.remoteWindowSize = acceptanceParameters.RemoteWindowSize;
return true;
}
return false;
}
}
/// <summary>
/// Invoked when the remote party acknowledges bytes we previously transmitted as processed,
/// thereby allowing us to consider that data removed from the remote party's "window"
/// and thus enables us to send more data to them.
/// </summary>
/// <param name="bytesProcessed">The number of bytes processed by the remote party.</param>
internal void OnContentProcessed(long bytesProcessed)
{
Requires.Range(bytesProcessed >= 0, nameof(bytesProcessed), "A non-negative number is required.");
lock (this.SyncObject)
{
Assumes.True(bytesProcessed <= this.remoteWindowFilled);
this.remoteWindowFilled -= bytesProcessed;
if (this.remoteWindowFilled < this.remoteWindowSize)
{
this.remoteWindowHasCapacity.Set();
}
}
}
/// <summary>
/// Gets the pipe writer to use when a message is received for this channel, so that the channel owner will notice and read it.
/// </summary>
/// <returns>A <see cref="PipeWriter"/>.</returns>
private PipeWriter GetReceivedMessagePipeWriter()
{
lock (this.SyncObject)
{
Verify.NotDisposed(this);
PipeWriter? result = this.mxStreamIOWriter;
if (result == null)
{
this.InitializeOwnPipes();
result = this.mxStreamIOWriter!;
}
return result;
}
}
/// <summary>
/// Apply channel options to this channel, including setting up or linking to an user-supplied pipe writer/reader pair.
/// </summary>
/// <param name="channelOptions">The channel options to apply.</param>
private void ApplyChannelOptions(ChannelOptions channelOptions)
{
Requires.NotNull(channelOptions, nameof(channelOptions));
Assumes.Null(this.TraceSource); // We've already applied options
try
{
this.TraceSource = channelOptions.TraceSource
?? this.MultiplexingStream.DefaultChannelTraceSourceFactory?.Invoke(this.QualifiedId, this.Name)
?? new TraceSource($"{nameof(Streams.MultiplexingStream)}.{nameof(Channel)} {this.QualifiedId} ({this.Name})", SourceLevels.Critical);
lock (this.SyncObject)
{
Verify.NotDisposed(this);
this.InitializeOwnPipes();
if (channelOptions.ExistingPipe is object)
{
Assumes.NotNull(this.channelIO);
this.existingPipe = channelOptions.ExistingPipe;
this.existingPipeGiven = true;
// We always want to write ALL received data to the user's ExistingPipe, rather than truncating it on disposal, so don't use a cancellation token in that direction.
this.DisposeSelfOnFailure(this.channelIO.Input.LinkToAsync(channelOptions.ExistingPipe.Output));
// Upon disposal, we no longer want to continue reading from the user's ExistingPipe into our buffer since we won't be propagating it any further, so use our DisposalToken.
this.DisposeSelfOnFailure(channelOptions.ExistingPipe.Input.LinkToAsync(this.channelIO.Output, this.DisposalToken));
}
else
{
this.existingPipeGiven = false;
}
}
this.mxStreamIOReaderCompleted = this.ProcessOutboundTransmissionsAsync();
this.DisposeSelfOnFailure(this.mxStreamIOReaderCompleted);
this.DisposeSelfOnFailure(this.AutoCloseOnPipesClosureAsync());
}
catch (Exception ex)
{
this.optionsAppliedTaskSource?.TrySetException(ex);
throw;
}
finally
{
this.optionsAppliedTaskSource?.TrySetResult(null);
}
}
/// <summary>
/// Set up our own (buffering) Pipes if they have not been set up yet.
/// </summary>
private void InitializeOwnPipes()
{
lock (this.SyncObject)
{
Verify.NotDisposed(this);
if (this.mxStreamIOReader is null)
{
if (this.localWindowSize is null)
{
// If an offer came in along with data before we accepted the channel, we have to set up the pipe
// before we know what the preferred local window size is. We can't change it after the fact, so just use the default.
this.localWindowSize = this.MultiplexingStream.DefaultChannelReceivingWindowSize;
}
var writerRelay = new Pipe();
var readerRelay = this.BackpressureSupportEnabled
? new Pipe(new PipeOptions(pauseWriterThreshold: this.localWindowSize.Value + 1)) // +1 prevents pause when remote window is exactly filled
: new Pipe();
this.mxStreamIOReader = writerRelay.Reader;
this.mxStreamIOWriter = readerRelay.Writer;
this.channelIO = new DuplexPipe(this.BackpressureSupportEnabled ? new WindowPipeReader(this, readerRelay.Reader) : readerRelay.Reader, writerRelay.Writer);
}
}
}
/// <summary>
/// Relays data that the local channel owner wants to send to the remote party.
/// </summary>
private async Task ProcessOutboundTransmissionsAsync()
{
try
{
// Don't transmit data on the channel until the remote party has accepted it.
// This is not just a courtesy: it ensure we don't transmit data from the offering party before the offer frame itself.
// Likewise: it may help prevent transmitting data from the accepting party before the acceptance frame itself.
await this.Acceptance.ConfigureAwait(false);
while (!this.Completion.IsCompleted)
{
if (!this.remoteWindowHasCapacity.IsSet && this.TraceSource!.Switch.ShouldTrace(TraceEventType.Verbose))
{
this.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Remote window is full. Waiting for remote party to process data before sending more.");
}
await this.remoteWindowHasCapacity.WaitAsync().ConfigureAwait(false);
if (this.IsRemotelyTerminated)
{
if (this.TraceSource!.Switch.ShouldTrace(TraceEventType.Verbose))
{
this.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Transmission on channel {0} \"{1}\" terminated the remote party terminated the channel.", this.QualifiedId, this.Name);
}
break;
}
ReadResult result;
try
{
result = await this.mxStreamIOReader!.ReadAsync().ConfigureAwait(false);
}
catch (InvalidOperationException ex)
{
// Someone completed the reader. The channel was probably disposed.
if (this.TraceSource!.Switch.ShouldTrace(TraceEventType.Verbose))
{
this.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Transmission terminated because the reader threw: {0}", ex);
}
break;
}
if (result.IsCanceled)
{
// We've been asked to cancel. Presumably the channel has been disposed.
if (this.TraceSource!.Switch.ShouldTrace(TraceEventType.Verbose))
{
this.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Transmission terminated because the read was canceled.");
}
break;
}
// We'll send whatever we've got, up to the maximum size of the frame or available window size.
// Anything in excess of that we'll pick up next time the loop runs.
long bytesToSend = Math.Min(result.Buffer.Length, FramePayloadMaxLength);
if (this.BackpressureSupportEnabled)
{
bytesToSend = Math.Min(this.RemoteWindowRemaining, bytesToSend);
}
var bufferToRelay = result.Buffer.Slice(0, bytesToSend);
this.OnTransmittingBytes(bufferToRelay.Length);
bool isCompleted = result.IsCompleted && result.Buffer.Length == bufferToRelay.Length;
if (this.TraceSource!.Switch.ShouldTrace(TraceEventType.Verbose))
{
this.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "{0} of {1} bytes will be transmitted.", bufferToRelay.Length, result.Buffer.Length);
}
if (bufferToRelay.Length > 0)
{
FrameHeader header = new FrameHeader
{
Code = ControlCode.Content,
ChannelId = this.QualifiedId,
};
await this.MultiplexingStream.SendFrameAsync(header, bufferToRelay, CancellationToken.None).ConfigureAwait(false);
}
try
{
// Let the pipe know exactly how much we read, which might be less than we were given.
this.mxStreamIOReader.AdvanceTo(bufferToRelay.End);
// We mustn't accidentally access the memory that may have been recycled now that we called AdvanceTo.
bufferToRelay = default;
result.ScrubAfterAdvanceTo();
}
catch (InvalidOperationException ex)
{
// Someone completed the reader. The channel was probably disposed.
if (this.TraceSource.Switch.ShouldTrace(TraceEventType.Verbose))
{
this.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Transmission terminated because the reader threw: {0}", ex);
}
break;
}
if (isCompleted)
{
if (this.TraceSource.Switch.ShouldTrace(TraceEventType.Verbose))
{
this.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Transmission terminated because the writer completed.");
}
break;
}
}
await this.mxStreamIOReader!.CompleteAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
await this.mxStreamIOReader!.CompleteAsync(ex).ConfigureAwait(false);
throw;
}
finally
{
this.MultiplexingStream.OnChannelWritingCompleted(this);
}
}
/// <summary>
/// Invoked when we transmit data to the remote party
/// so we can track how much data we're sending them so we don't overrun their receiving buffer.
/// </summary>
/// <param name="transmittedBytes">The number of bytes being transmitted.</param>
private void OnTransmittingBytes(long transmittedBytes)
{
if (this.BackpressureSupportEnabled)
{
Requires.Range(transmittedBytes >= 0, nameof(transmittedBytes), "A non-negative number is required.");
lock (this.SyncObject)
{
Requires.Range(this.remoteWindowFilled + transmittedBytes <= this.remoteWindowSize, nameof(transmittedBytes), "The value exceeds the space remaining in the window size.");
this.remoteWindowFilled += transmittedBytes;
if (this.remoteWindowFilled == this.remoteWindowSize)
{
this.remoteWindowHasCapacity.Reset();
}
}
}
}
private void LocalContentExamined(long bytesExamined)
{
Requires.Range(bytesExamined >= 0, nameof(bytesExamined));
if (bytesExamined == 0 || this.IsDisposed)
{
return;
}
if (this.TraceSource!.Switch.ShouldTrace(TraceEventType.Verbose))
{
this.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Acknowledging processing of {0} bytes.", bytesExamined);
}
this.MultiplexingStream.SendFrame(
new FrameHeader
{
Code = ControlCode.ContentProcessed,
ChannelId = this.QualifiedId,
},
this.MultiplexingStream.formatter.SerializeContentProcessed(bytesExamined),
CancellationToken.None);
}
private async Task AutoCloseOnPipesClosureAsync()
{
Assumes.NotNull(this.mxStreamIOReaderCompleted);
await Task.WhenAll(this.mxStreamIOWriterCompleted.WaitAsync(), this.mxStreamIOReaderCompleted).ConfigureAwait(false);
if (this.TraceSource!.Switch.ShouldTrace(TraceEventType.Information))
{
this.TraceSource.TraceEvent(TraceEventType.Information, (int)TraceEventId.ChannelAutoClosing, "Channel {0} \"{1}\" self-closing because both reader and writer are complete.", this.QualifiedId, this.Name);
}
this.Dispose();
}
private void Fault(Exception exception)
{
if (this.TraceSource?.Switch.ShouldTrace(TraceEventType.Critical) ?? false)
{
this.TraceSource!.TraceEvent(TraceEventType.Critical, (int)TraceEventId.FatalError, "Channel Closing self due to exception: {0}", exception);
}
this.mxStreamIOReader?.Complete(exception);
this.Dispose();
}
private void DisposeSelfOnFailure(Task task)
{
Requires.NotNull(task, nameof(task));
if (task.IsCompleted)
{
if (task.IsFaulted)
{
this.Fault(task.Exception!.InnerException ?? task.Exception);
}
}
else
{
task.ContinueWith(
(t, s) => ((Channel)s!).Fault(t.Exception!.InnerException ?? t.Exception),
this,
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.Default).Forget();
}
}
[DataContract]
internal class OfferParameters
{
/// <summary>
/// Initializes a new instance of the <see cref="OfferParameters"/> class.
/// </summary>
/// <param name="name">The name of the channel.</param>
/// <param name="remoteWindowSize">
/// The maximum number of bytes that may be transmitted and not yet acknowledged as processed by the remote party.
/// When based on <see cref="PipeOptions.PauseWriterThreshold"/>, this value should be -1 of that value in order
/// to avoid the actual pause that would be fatal to the read loop of the multiplexing stream.
/// </param>
internal OfferParameters(string name, long? remoteWindowSize)
{
this.Name = name ?? throw new ArgumentNullException(nameof(name));
this.RemoteWindowSize = remoteWindowSize;
}
/// <summary>
/// Gets the name of the channel.
/// </summary>
[DataMember]
internal string Name { get; }
/// <summary>
/// Gets the maximum number of bytes that may be transmitted and not yet acknowledged as processed by the remote party.
/// </summary>
[DataMember]
internal long? RemoteWindowSize { get; }
}
[DataContract]
internal class AcceptanceParameters
{
/// <summary>
/// Initializes a new instance of the <see cref="AcceptanceParameters"/> class.
/// </summary>
/// <param name="remoteWindowSize">
/// The maximum number of bytes that may be transmitted and not yet acknowledged as processed by the remote party.
/// When based on <see cref="PipeOptions.PauseWriterThreshold"/>, this value should be -1 of that value in order
/// to avoid the actual pause that would be fatal to the read loop of the multiplexing stream.
/// </param>
internal AcceptanceParameters(long? remoteWindowSize) => this.RemoteWindowSize = remoteWindowSize;
/// <summary>
/// Gets the maximum number of bytes that may be transmitted and not yet acknowledged as processed by the remote party.
/// </summary>
[DataMember]
internal long? RemoteWindowSize { get; }
}
private class WindowPipeReader : PipeReader
{
private readonly Channel owner;
private readonly PipeReader inner;
private ReadResult lastReadResult;
private long bytesProcessed;
private SequencePosition lastExaminedPosition;
internal WindowPipeReader(Channel owner, PipeReader inner)
{
this.owner = owner;
this.inner = inner;
}
public override void AdvanceTo(SequencePosition consumed)
{
long consumedBytes = this.Consumed(consumed, consumed);
this.inner.AdvanceTo(consumed);
this.owner.LocalContentExamined(consumedBytes);
}
public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
{
long consumedBytes = this.Consumed(consumed, examined);
this.inner.AdvanceTo(consumed, examined);
this.owner.LocalContentExamined(consumedBytes);
}
public override void CancelPendingRead() => this.inner.CancelPendingRead();
public override void Complete(Exception? exception = null) => this.inner.Complete(exception);
public override async ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default)
{
return this.lastReadResult = await this.inner.ReadAsync(cancellationToken).ConfigureAwait(false);
}
public override bool TryRead(out ReadResult readResult)
{
bool result = this.inner.TryRead(out readResult);
this.lastReadResult = readResult;
return result;
}
public override ValueTask CompleteAsync(Exception? exception = null) => this.inner.CompleteAsync(exception);
public override Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default) => this.inner.CopyToAsync(destination, cancellationToken);
public override Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default) => this.inner.CopyToAsync(destination, cancellationToken);
[Obsolete]
public override void OnWriterCompleted(Action<Exception?, object?> callback, object? state) => this.inner.OnWriterCompleted(callback, state);
private long Consumed(SequencePosition consumed, SequencePosition examined)
{
var lastExamined = this.lastExaminedPosition;
if (lastExamined.Equals(default))
{
lastExamined = this.lastReadResult.Buffer.Start;
}
// If the entirety of the buffer was examined for the first time, just use the buffer length as a perf optimization.
// Otherwise, slice the buffer from last examined to new examined to get the number of freshly examined bytes.
long bytesJustProcessed =
lastExamined.Equals(this.lastReadResult.Buffer.Start) && this.lastReadResult.Buffer.End.Equals(examined) ? this.lastReadResult.Buffer.Length :
this.lastReadResult.Buffer.Slice(lastExamined, examined).Length;
this.bytesProcessed += bytesJustProcessed;
// Only send the 'more bytes please' message if we've consumed at least a max frame's worth of data
// or if our reader indicates that more data is required before it will examine any more.
// Or in some cases of very small receiving windows, when the entire window is empty.
long result = 0;
if (this.bytesProcessed >= FramePayloadMaxLength || this.bytesProcessed == this.owner.localWindowSize)
{
result = this.bytesProcessed;
this.bytesProcessed = 0;
}
// Only store the examined position if it is ahead of the consumed position.
// Otherwise we'd store a position in an array that may be recycled.
this.lastExaminedPosition = consumed.Equals(examined) ? default : examined;
return result;
}
}
}
}
}
| 49.600779 | 248 | 0.538143 | [
"MIT"
] | AArnott/Nerdbank.Streams | src/Nerdbank.Streams/MultiplexingStream.Channel.cs | 50,942 | C# |
// Copyright (c) 2019, WebsitePanel-Support.net.
// Distributed by websitepanel-support.net
// Build and fixed by Key4ce - IT Professionals
// https://www.key4ce.com
//
// Original source:
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.ComponentModel;
using System.Resources;
namespace WebsitePanel.WebDav.Core.Attributes.Resources
{
public class LocalizedDescriptionAttribute : DescriptionAttribute
{
private readonly string _resourceKey;
private readonly ResourceManager _resource;
public LocalizedDescriptionAttribute(Type resourceType, string resourceKey)
{
_resource = new ResourceManager(resourceType);
_resourceKey = resourceKey;
}
public override string Description
{
get
{
string displayName = _resource.GetString(_resourceKey);
return string.IsNullOrEmpty(displayName)
? string.Format("[[{0}]]", _resourceKey)
: displayName;
}
}
}
}
| 42.859375 | 84 | 0.68611 | [
"BSD-3-Clause"
] | Key4ce/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebDav.Core/Attributes/Resources/LocalizedDescriptionAttribute.cs | 2,743 | C# |
/*
* Copyright (c) Adam Chapweske
*
* Licensed under MIT (https://github.com/achapweske/silvernote/blob/master/LICENSE)
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DOM.SVG
{
public interface SVGAnimatedPathData
{
ISVGPathSegList PathSegList { get; }
ISVGPathSegList NormalizedPathSegList { get; }
ISVGPathSegList AnimatedPathSegList { get; }
ISVGPathSegList AnimatedNormalizedPathSegList { get; }
}
}
| 23.090909 | 84 | 0.71063 | [
"MIT"
] | achapweske/silvernote | SilverNote.DOM/SVG/SVGAnimatedPathData.cs | 510 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace FCGagarin.PL.Admin.Models.ManageViewModels
{
public class RemoveLoginViewModel
{
public string LoginProvider { get; set; }
public string ProviderKey { get; set; }
}
}
| 23.266667 | 52 | 0.739255 | [
"MIT"
] | logical8/FCGagarin | FCGagarin.PL.Admin/Models/ManageViewModels/RemoveLoginViewModel.cs | 351 | C# |
using Neo.AST.Expressions;
using Neo.Frontend.Lexer;
namespace Neo.AST.Statements {
public sealed class ReturnNode : StatementNode {
public ReturnNode(SourcePosition position, ExpressionNode value) : base(position) {
Value = value;
}
public ExpressionNode Value { get; }
public override void Accept(IASTVisitor visitor) {
visitor.VisitReturn(this);
}
}
} | 26.875 | 91 | 0.648837 | [
"MIT"
] | sci4me/Neo-old | src/main/AST/Statements/ReturnNode.cs | 432 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.TestCommon;
using Moq;
namespace System.Web.Mvc.Test
{
public class MultiServiceResolverTest
{
[Fact]
public void ConstructorWithNullThunkArgumentThrows()
{
// Act & Assert
Assert.ThrowsArgumentNull(
delegate { new MultiServiceResolver<TestProvider>(null); },
"itemsThunk");
}
[Fact]
public void CurrentPrependsFromResolver()
{
// Arrange
IEnumerable<TestProvider> providersFromServiceLocation = GetProvidersFromService();
IEnumerable<TestProvider> providersFromItemsThunk = GetProvidersFromItemsThunk();
IEnumerable<TestProvider> expectedProviders = providersFromServiceLocation.Concat(providersFromItemsThunk);
Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();
resolver.Setup(r => r.GetServices(typeof(TestProvider)))
.Returns(providersFromServiceLocation);
MultiServiceResolver<TestProvider> multiResolver = new MultiServiceResolver<TestProvider>(() => providersFromItemsThunk, resolver.Object);
// Act
IEnumerable<TestProvider> returnedProviders = multiResolver.Current;
// Assert
Assert.Equal(expectedProviders.ToList(), returnedProviders.ToList());
}
[Fact]
public void CurrentCachesResolverResult()
{
// Arrange
IEnumerable<TestProvider> providersFromServiceLocation = GetProvidersFromService();
IEnumerable<TestProvider> providersFromItemsThunk = GetProvidersFromItemsThunk();
IEnumerable<TestProvider> expectedProviders = providersFromServiceLocation.Concat(providersFromItemsThunk);
Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();
resolver.Setup(r => r.GetServices(typeof(TestProvider)))
.Returns(providersFromServiceLocation);
MultiServiceResolver<TestProvider> multiResolver = new MultiServiceResolver<TestProvider>(() => providersFromItemsThunk, resolver.Object);
// Act
IEnumerable<TestProvider> returnedProviders = multiResolver.Current;
IEnumerable<TestProvider> cachedProviders = multiResolver.Current;
// Assert
Assert.Equal(expectedProviders.ToList(), returnedProviders.ToList());
Assert.Equal(expectedProviders.ToList(), cachedProviders.ToList());
resolver.Verify(r => r.GetServices(typeof(TestProvider)), Times.Exactly(1));
}
[Fact]
public void CurrentReturnsCurrentItemsWhenResolverReturnsNoInstances()
{
// Arrange
IEnumerable<TestProvider> providersFromItemsThunk = GetProvidersFromItemsThunk();
MultiServiceResolver<TestProvider> resolver = new MultiServiceResolver<TestProvider>(() => providersFromItemsThunk);
// Act
IEnumerable<TestProvider> returnedProviders = resolver.Current;
// Assert
Assert.Equal(providersFromItemsThunk.ToList(), returnedProviders.ToList());
}
[Fact]
public void CurrentDoesNotQueryResolverAfterNoInstancesAreReturned()
{
// Arrange
IEnumerable<TestProvider> providersFromItemsThunk = GetProvidersFromItemsThunk();
Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();
resolver.Setup(r => r.GetServices(typeof(TestProvider)))
.Returns(new TestProvider[0]);
MultiServiceResolver<TestProvider> multiResolver = new MultiServiceResolver<TestProvider>(() => providersFromItemsThunk, resolver.Object);
// Act
IEnumerable<TestProvider> returnedProviders = multiResolver.Current;
IEnumerable<TestProvider> cachedProviders = multiResolver.Current;
// Assert
Assert.Equal(providersFromItemsThunk.ToList(), returnedProviders.ToList());
Assert.Equal(providersFromItemsThunk.ToList(), cachedProviders.ToList());
resolver.Verify(r => r.GetServices(typeof(TestProvider)), Times.Exactly(1));
}
[Fact]
public void CurrentPropagatesExceptionWhenResolverThrowsNonActivationException()
{
// Arrange
Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>(MockBehavior.Strict);
MultiServiceResolver<TestProvider> multiResolver = new MultiServiceResolver<TestProvider>(() => null, resolver.Object);
// Act & Assert
Assert.Throws<MockException>(
() => multiResolver.Current,
"IDependencyResolver.GetServices(System.Web.Mvc.Test.MultiServiceResolverTest+TestProvider) invocation failed with mock behavior Strict." + Environment.NewLine
+ "All invocations on the mock must have a corresponding setup."
);
}
private class TestProvider
{
}
private IEnumerable<TestProvider> GetProvidersFromService()
{
return new TestProvider[]
{
new TestProvider(),
new TestProvider()
};
}
private IEnumerable<TestProvider> GetProvidersFromItemsThunk()
{
return new TestProvider[]
{
new TestProvider(),
new TestProvider()
};
}
}
}
| 41.311594 | 175 | 0.64936 | [
"Apache-2.0"
] | charliefr/aspnetwebstack | test/System.Web.Mvc.Test/Test/MultiServiceResolverTest.cs | 5,703 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.Assertions;
namespace SuperTiled2Unity.Editor
{
[CanEditMultipleObjects]
[CustomEditor(typeof(TmxAssetImporter))]
class TmxAssetImporterEditor : TiledAssetImporterEditor<TmxAssetImporter>
{
private SerializedProperty m_TilesAsObjects;
private readonly GUIContent m_TilesAsObjectsContent = new GUIContent("Tiles as Objects", "Place each tile as separate game object. Uses more resources but gives you more control. This is ignored for Isometric maps that are forced to use game objects.");
private SerializedProperty m_SortingMode;
private readonly GUIContent m_SortingModeContent = new GUIContent("Layer/Object Sorting", "Choose the sorting order scheme applied to imported layers and objects.");
private SerializedProperty m_CustomImporterClassName;
private string[] m_CustomImporterNames;
private string[] m_CustomImporterTypes;
private int m_SelectedCustomImporter;
private bool m_ShowAutoImporters;
protected override string EditorLabel
{
get { return "Tiled Map Importer (.tmx files)"; }
}
protected override string EditorDefinition
{
get { return "This imports Tiled map files (*.tmx) and creates a prefab of your map to be added to your scenes."; }
}
public override void OnEnable()
{
CacheSerializedProperites();
EnumerateCustomImporterClasses();
base.OnEnable();
}
protected override void InternalOnInspectorGUI()
{
EditorGUILayout.LabelField("Tiled Map Importer Settings", EditorStyles.boldLabel);
ShowTiledAssetGui();
EditorGUILayout.PropertyField(m_TilesAsObjects, m_TilesAsObjectsContent);
EditorGUI.EndDisabledGroup();
m_SortingMode.intValue = (int)(SortingMode)EditorGUILayout.EnumPopup(m_SortingModeContent, (SortingMode)m_SortingMode.intValue);
if (m_SortingMode.intValue == (int)SortingMode.CustomSortAxis)
{
EditorGUILayout.HelpBox("Tip: Custom Sort Axis may require you to set a Transparency Sort Axis for cameras in your project Graphics settings.", MessageType.Info);
}
EditorGUILayout.Space();
ShowCustomImporterGui();
InternalApplyRevertGUI();
}
protected override void ResetValues()
{
base.ResetValues();
CacheSerializedProperites();
}
private void CacheSerializedProperites()
{
m_TilesAsObjects = serializedObject.FindProperty("m_TilesAsObjects");
Assert.IsNotNull(m_TilesAsObjects);
m_SortingMode = serializedObject.FindProperty("m_SortingMode");
Assert.IsNotNull(m_SortingMode);
m_CustomImporterClassName = serializedObject.FindProperty("m_CustomImporterClassName");
Assert.IsNotNull(m_CustomImporterClassName);
}
private void EnumerateCustomImporterClasses()
{
var importerNames = new List<string>();
var importerTypes = new List<string>();
// Enumerate all CustomTmxImporter classes that *do not* have the auto importer attribute on them
var customTypes = AppDomain.CurrentDomain.GetAllDerivedTypes<CustomTmxImporter>().
Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof(CustomTmxImporter))).
Where(t => t.GetCustomAttributes(typeof(AutoCustomTmxImporterAttribute), true).Length == 0).
OrderBy(t => t.GetDisplayName());
foreach (var t in customTypes)
{
importerNames.Add(t.GetDisplayName());
importerTypes.Add(t.FullName);
}
importerNames.Insert(0, "None");
importerTypes.Insert(0, string.Empty);
m_CustomImporterNames = importerNames.ToArray();
m_CustomImporterTypes = importerTypes.ToArray();
m_SelectedCustomImporter = importerTypes.IndexOf(m_CustomImporterClassName.stringValue);
if (m_SelectedCustomImporter == -1)
{
m_SelectedCustomImporter = 0;
m_CustomImporterClassName.stringValue = string.Empty;
}
}
private void ShowCustomImporterGui()
{
// Show the user-selected custom importer
EditorGUILayout.LabelField("Custom Importer Settings", EditorStyles.boldLabel);
var selected = EditorGUILayout.Popup("Custom Importer", m_SelectedCustomImporter, m_CustomImporterNames);
if (selected != m_SelectedCustomImporter)
{
m_SelectedCustomImporter = selected;
m_CustomImporterClassName.stringValue = m_CustomImporterTypes.ElementAtOrDefault(selected);
}
EditorGUILayout.HelpBox("Custom Importers are an advanced feature that require scripting. Create a class inherited from CustomTmxImporter and select it from the list above.", MessageType.None);
// List all the automatically applied custom importers
using (new GuiScopedIndent())
{
var importers = AutoCustomTmxImporterAttribute.GetOrderedAutoImportersTypes();
var title = string.Format("Auto Importers ({0})", importers.Count());
var tip = "This custom importers will be automatically applied to your import process.";
var content = new GUIContent(title, tip);
m_ShowAutoImporters = EditorGUILayout.Foldout(m_ShowAutoImporters, content);
if (m_ShowAutoImporters)
{
foreach (var t in importers)
{
EditorGUILayout.LabelField(t.GetDisplayName());
}
EditorGUILayout.HelpBox("Auto Importers are custom importers that run on automatically on every exported Tiled map. Order is controlled by the AutoCustomTmxImporterAttribute.", MessageType.None);
}
}
}
}
}
| 41.569536 | 261 | 0.647762 | [
"MIT"
] | Alkanov/SuperTiled2Unity | SuperTiled2Unity/Assets/SuperTiled2Unity/Scripts/Editor/Importers/TmxAssetImporterEditor.cs | 6,279 | C# |
using System;
using System.Linq;
using FluentAssertions;
using FsCheck.Xunit;
using Xunit;
namespace Toggl.Foundation.Tests
{
public sealed class DurationFieldInfoTests
{
public abstract class BaseDurationFieldInfoTest
{
protected DurationFieldInfo Field;
public BaseDurationFieldInfoTest()
{
Field = DurationFieldInfo.Empty;
}
protected void inputData(string digitsString)
{
var digits = digitsString.ToCharArray().Select(digit => digit - '0').ToArray();
inputDigits(digits);
}
protected void inputDigits(params int[] digits)
{
foreach (var digit in digits)
{
Field = Field.Push(digit);
}
}
protected void popNTimes(int n)
{
for (int i = 0; i < n; i++)
{
Field = Field.Pop();
}
}
}
public sealed class TheFromTimeSpanMethod : BaseDurationFieldInfoTest
{
[Property]
public void ClampsTheValueBetweenZeroAndTheMaxValue(TimeSpan input)
{
var output = DurationFieldInfo.FromTimeSpan(input).ToTimeSpan();
output.Should().BeGreaterOrEqualTo(TimeSpan.Zero);
output.Should().BeLessOrEqualTo(TimeSpan.FromHours(999));
}
[Theory, LogIfTooSlow]
[InlineData(0, 0)]
[InlineData(0, 1)]
[InlineData(1, 0)]
[InlineData(12, 30)]
[InlineData(0, 30)]
[InlineData(123, 1)]
public void ConvertsTheTimeSpanCorrectly(int hours, int minutes)
{
var timeSpan = TimeSpan.FromHours(hours).Add(TimeSpan.FromMinutes(minutes));
var durationField = DurationFieldInfo.FromTimeSpan(timeSpan);
durationField.Hours.Should().Be(hours);
durationField.Minutes.Should().Be(minutes);
}
}
public sealed class ThePushMethod : BaseDurationFieldInfoTest
{
[Theory, LogIfTooSlow]
[InlineData("", 0, 0)]
[InlineData("1", 0, 1)]
[InlineData("12", 0, 12)]
[InlineData("123", 1, 23)]
[InlineData("1234", 12, 34)]
[InlineData("12345", 123, 45)]
[InlineData("99999", 999, 99)]
[InlineData("87", 0, 87)]
public void InterpretsTheDigitsInCorrectOrder(string inputSequence, int expectedHours, int expectedMinutes)
{
inputData(inputSequence);
Field.Hours.Should().Be(expectedHours);
Field.Minutes.Should().Be(expectedMinutes);
}
[Theory, LogIfTooSlow]
[InlineData("123456", 123, 45)]
[InlineData("1234567", 123, 45)]
[InlineData("12345678", 123, 45)]
[InlineData("123456789", 123, 45)]
public void IgnoresMoreThanFiveInputDigits(string inputSequence, int expectedHours, int expectedMinutes)
{
inputData(inputSequence);
Field.Hours.Should().Be(expectedHours);
Field.Minutes.Should().Be(expectedMinutes);
}
}
public sealed class ThePopMethod : BaseDurationFieldInfoTest
{
[Theory, LogIfTooSlow]
[InlineData("19", 1, 0, 1)]
[InlineData("127", 1, 0, 12)]
[InlineData("650", 1, 0, 65)]
[InlineData("1234", 2, 0, 12)]
[InlineData("12345", 2, 1, 23)]
[InlineData("99999", 3, 0, 99)]
[InlineData("87", 2, 0, 0)]
public void RemovesTheDigitsWhichWereAddedTheLast(string inputSequence, int popCount, int expectedHours, int expectedMinutes)
{
inputData(inputSequence);
popNTimes(popCount);
Field.Hours.Should().Be(expectedHours);
Field.Minutes.Should().Be(expectedMinutes);
}
[Theory, LogIfTooSlow]
[InlineData("")]
[InlineData("12345")]
[InlineData("661")]
public void StopsPoppingWhenEmpty(string inputSequence)
{
inputData(inputSequence);
popNTimes(inputSequence.Length + 3);
Field.Hours.Should().Be(0);
Field.Minutes.Should().Be(0);
}
}
public sealed class TheToStringMethod : BaseDurationFieldInfoTest
{
[Theory, LogIfTooSlow]
[InlineData("", "00:00")]
[InlineData("0", "00:00")]
[InlineData("00", "00:00")]
[InlineData("000", "00:00")]
[InlineData("0000", "00:00")]
[InlineData("00000", "00:00")]
[InlineData("000000", "00:00")]
public void IgnoresLeadingZeros(string inputSequence, string expectedOutput)
{
inputData(inputSequence);
var output = Field.ToString();
output.Should().Be(expectedOutput);
}
[Theory, LogIfTooSlow]
[InlineData("60", "00:60")]
[InlineData("181", "01:81")]
[InlineData("99999", "999:99")]
public void DoesNotCarryMinutesToHoursWhenTheNumberOfMinutesIsMoreThanFiftyNine(string inputSequence, string expectedOutput)
{
inputData(inputSequence);
var output = Field.ToString();
output.Should().Be(expectedOutput);
}
[Theory, LogIfTooSlow]
[InlineData("1", "00:01")]
[InlineData("2", "00:02")]
[InlineData("12", "00:12")]
[InlineData("89", "00:89")]
[InlineData("45", "00:45")]
[InlineData("90", "00:90")]
public void ShowsTwoLeadingZerosWhenThereAreZeroHours(string inputSequence, string expectedOutput)
{
inputData(inputSequence);
var output = Field.ToString();
output.Should().Be(expectedOutput);
}
[Theory, LogIfTooSlow]
[InlineData("100", "01:00")]
[InlineData("200", "02:00")]
[InlineData("120", "01:20")]
[InlineData("950", "09:50")]
public void ShowsALeadingZerosWhenThereIsASingleDigitHour(string inputSequence, string expectedOutput)
{
inputData(inputSequence);
var output = Field.ToString();
output.Should().Be(expectedOutput);
}
[Theory, LogIfTooSlow]
[InlineData("1200", "12:00")]
[InlineData("4201", "42:01")]
[InlineData("1234", "12:34")]
[InlineData("9999", "99:99")]
public void DoesNotShowALeadingZeroWhenTheDurationIsFourDigitsLong(string inputSequence, string expectedOutput)
{
inputData(inputSequence);
var output = Field.ToString();
output.Should().Be(expectedOutput);
}
[Theory, LogIfTooSlow]
[InlineData("10000", "100:00")]
[InlineData("12345", "123:45")]
[InlineData("99999", "999:99")]
public void ShowsFiveCharactersWhenTheNumberOfHoursIsMoreThanNinetyNine(string inputSequence, string expectedOutput)
{
inputData(inputSequence);
var output = Field.ToString();
output.Should().Be(expectedOutput);
}
}
public sealed class TheToTimeSpanMethod : BaseDurationFieldInfoTest
{
[Theory, LogIfTooSlow]
[InlineData("99861")]
[InlineData("99901")]
[InlineData("99999")]
public void ClampsDurationToMaximumTime(string inputSequence)
{
inputData(inputSequence);
var output = Field.ToTimeSpan();
output.Should().Be(TimeSpan.FromHours(999));
}
[Theory, LogIfTooSlow]
[InlineData("12", 12)]
[InlineData("123", 1 * 60 + 23)]
[InlineData("1177", 11 * 60 + 77)]
[InlineData("789", 7 * 60 + 89)]
public void CorrectlyCalculatesTheDuration(string inputSequence, double totalMinutes)
{
inputData(inputSequence);
var output = Field.ToTimeSpan();
output.TotalMinutes.Should().Be(totalMinutes);
}
}
public sealed class TheEmptyStaticProperty
{
[Fact, LogIfTooSlow]
public void MinutesAndHoursAreZero()
{
var field = DurationFieldInfo.Empty;
field.Hours.Should().Be(0);
field.Minutes.Should().Be(0);
}
[Fact, LogIfTooSlow]
public void SerializesIntoZerosOnly()
{
DurationFieldInfo.Empty.ToString().Should().Be("00:00");
}
[Fact, LogIfTooSlow]
public void ConvertsIntoZeroTimeSpan()
{
DurationFieldInfo.Empty.ToTimeSpan().Should().Be(TimeSpan.Zero);
}
}
}
}
| 33.150877 | 137 | 0.519581 | [
"BSD-3-Clause"
] | AzureMentor/mobileapp | Toggl.Foundation.Tests/DurationFieldInfoTests.cs | 9,450 | C# |
using UnityEngine;
using System.Collections;
public interface IProjectileWeapon {
Transform ProjectileSpawn { get; set; }
void CastProjectile();
}
| 10.933333 | 43 | 0.719512 | [
"Unlicense"
] | S00156670/TheForeverCave | Assets/Scripts/IProjectileWeapon.cs | 166 | C# |
namespace WebAssembly.Instructions
{
/// <summary>
/// Sign-agnostic shift left.
/// </summary>
public class Int32ShiftLeft : ValueTwoToOneInstruction
{
/// <summary>
/// Always <see cref="OpCode.Int32ShiftLeft"/>.
/// </summary>
public sealed override OpCode OpCode => OpCode.Int32ShiftLeft;
private protected sealed override ValueType ValueType => ValueType.Int32;
private protected sealed override System.Reflection.Emit.OpCode EmittedOpCode =>
System.Reflection.Emit.OpCodes.Shl;
/// <summary>
/// Creates a new <see cref="Int32ShiftLeft"/> instance.
/// </summary>
public Int32ShiftLeft()
{
}
}
} | 29.48 | 88 | 0.610583 | [
"Apache-2.0"
] | MuhammadTayyab1/dotnet-webassembly | WebAssembly/Instructions/Int32ShiftLeft.cs | 737 | C# |
using System;
using System.Globalization;
using FluentAssertions;
using Sentry.Tests.Helpers;
using Xunit;
namespace Sentry.Tests
{
public class SessionTests
{
[Fact]
public void Serialization_Session_Success()
{
// Arrange
var session = new Session(
SentryId.Parse("75302ac48a024bde9a3b3734a82e36c8"),
"bar",
DateTimeOffset.Parse("2020-01-01T00:00:00+00:00", CultureInfo.InvariantCulture),
"release123",
"env123",
"192.168.0.1",
"Google Chrome"
);
session.ReportError();
session.ReportError();
session.ReportError();
session.End(SessionEndStatus.Crashed);
var sessionUpdate = new SessionUpdate(
session,
true,
DateTimeOffset.Parse("2020-01-02T00:00:00+00:00", CultureInfo.InvariantCulture),
5
);
// Act
var json = sessionUpdate.ToJsonString();
// Assert
json.Should().Be(
"{" +
"\"sid\":\"75302ac48a024bde9a3b3734a82e36c8\"," +
"\"did\":\"bar\"," +
"\"init\":true," +
"\"started\":\"2020-01-01T00:00:00+00:00\"," +
"\"timestamp\":\"2020-01-02T00:00:00+00:00\"," +
"\"seq\":5," +
"\"duration\":86400," +
"\"errors\":3," +
"\"status\":\"crashed\"," +
"\"attrs\":{" +
"\"release\":\"release123\"," +
"\"environment\":\"env123\"," +
"\"ip_address\":\"192.168.0.1\"," +
"\"user_agent\":\"Google Chrome\"" +
"}" +
"}"
);
}
[Fact]
public void CreateUpdate_IncrementsSequenceNumber()
{
// Arrange
var session = new Session(
SentryId.Parse("75302ac48a024bde9a3b3734a82e36c8"),
"bar",
DateTimeOffset.Parse("2020-01-01T00:00:00+00:00", CultureInfo.InvariantCulture),
"release123",
"env123",
"192.168.0.1",
"Google Chrome"
);
// Act
var sessionUpdate1 = session.CreateUpdate(true);
var sessionUpdate2 = session.CreateUpdate(false);
var sessionUpdate3 = session.CreateUpdate(false);
// Assert
sessionUpdate1.SequenceNumber.Should().Be(0);
sessionUpdate2.SequenceNumber.Should().Be(1);
sessionUpdate3.SequenceNumber.Should().Be(2);
}
}
}
| 31.134831 | 96 | 0.464814 | [
"MIT"
] | ajbeaven/sentry-dotnet | test/Sentry.Tests/SessionTests.cs | 2,773 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Media.Capture;
using Windows.Storage;
using System.Windows;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
namespace ScreenRecorderSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
enum RecordingStatus
{
stopped,
recording,
failed,
sucessful
} ;
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
MediaCapture _mediaCapture = null;
RecordingStatus _recordingStatus = RecordingStatus.stopped;
public MainPage()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private void StartRecordButton_Click_1(object sender, RoutedEventArgs e)
{
StartRecording();
}
private async void StartRecording()
{
try
{
// Get instance of the ScreenCapture object
var screenCapture = Windows.Media.Capture.ScreenCapture.GetForCurrentView();
// Set the MediaCaptureInitializationSettings to use the ScreenCapture as the
// audio and video source.
var mcis = new Windows.Media.Capture.MediaCaptureInitializationSettings();
mcis.VideoSource = screenCapture.VideoSource;
mcis.AudioSource = screenCapture.AudioSource;
mcis.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.AudioAndVideo;
// Initialize the MediaCapture with the initialization settings.
_mediaCapture = new MediaCapture();
await _mediaCapture.InitializeAsync(mcis);
// Set the MediaCapture to a variable in App.xaml.cs to handle suspension.
(App.Current as App).MediaCapture = _mediaCapture;
// Hook up events for the Failed, RecordingLimitationExceeded, and SourceSuspensionChanged events
_mediaCapture.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler(RecordingFailed);
_mediaCapture.RecordLimitationExceeded +=
new Windows.Media.Capture.RecordLimitationExceededEventHandler(RecordingReachedLimit);
screenCapture.SourceSuspensionChanged +=
new Windows.Foundation.TypedEventHandler<ScreenCapture, SourceSuspensionChangedEventArgs>(SourceSuspensionChanged);
// Create a file to record to.
var videoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("recording.mp4", CreationCollisionOption.ReplaceExisting);
// Create an encoding profile to use.
var profile = Windows.Media.MediaProperties.MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.HD1080p);
// Start recording
var start_action = _mediaCapture.StartRecordToStorageFileAsync(profile, videoFile);
start_action.Completed += CompletedStart;
// Set a tracking variable for recording state in App.xaml.cs
(App.Current as App).IsRecording = true;
}
catch (Exception ex)
{
NotifyUser("StartRecord Exception: " + ex.Message, NotifyType.ErrorMessage);
}
}
private void StopRecordButton_Click_1(object sender, RoutedEventArgs e)
{
StopRecording();
}
private void StopRecording()
{
try
{
//Stop Screen Recorder
var stop_action = _mediaCapture.StopRecordAsync();
stop_action.Completed += CompletedStop;
// Set a tracking variable for recording state in App.xaml.cs
(App.Current as App).IsRecording = false;
}
catch (Exception ex)
{
NotifyUser("StopRecord Exception: " + ex.Message, NotifyType.ErrorMessage);
}
}
public void RecordingFailed(Windows.Media.Capture.MediaCapture currentCaptureObject, MediaCaptureFailedEventArgs currentFailure)
{
_recordingStatus = RecordingStatus.failed;
NotifyUser("RecordFailed Event raised. ", NotifyType.ErrorMessage);
}
public void RecordingReachedLimit(Windows.Media.Capture.MediaCapture currentCaptureObject)
{
_recordingStatus = RecordingStatus.failed;
NotifyUser("RecordLimitationExceeded event raised.", NotifyType.ErrorMessage);
}
private void SourceSuspensionChanged(ScreenCapture sender, SourceSuspensionChangedEventArgs args)
{
NotifyUser("SourceSuspensionChanged Event. Args: IsAudioSuspended:" +
args.IsAudioSuspended.ToString() +
" IsVideoSuspended:" +
args.IsVideoSuspended.ToString(),
NotifyType.ErrorMessage);
}
public void CompletedStart(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
{
if (asyncStatus == AsyncStatus.Completed)
{
_recordingStatus = RecordingStatus.recording;
}
}
public async void CompletedStop(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
{
if (asyncStatus == AsyncStatus.Completed)
{
if (_recordingStatus == RecordingStatus.recording)
{
_recordingStatus = RecordingStatus.sucessful;
var file = await ApplicationData.Current.LocalFolder.GetFileAsync("recording.mp4");
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
mediaElement.SetSource(stream, "");
mediaElement.Play();
});
_recordingStatus = RecordingStatus.stopped;
}
if (_recordingStatus == RecordingStatus.failed)
{
// Recording has failed somewhere. Set the recording status to stopped.
_recordingStatus = RecordingStatus.stopped;
}
}
}
public void Render()
{
if (_recordingStatus == RecordingStatus.recording)
{
/* render and udpate contents that needs to be recorded */
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
// Always dispose of the MediaCapture device before your app is suspended.
_mediaCapture.Dispose();
}
private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
{
var position = e.GetCurrentPoint(_canvas).Position;
position.Y = (position.Y < 0) ? 0 : position.Y;
_circle.SetValue(Canvas.LeftProperty, position.X);
_circle.SetValue(Canvas.TopProperty, position.Y);
}
public void NotifyUser(string strMessage, NotifyType type)
{
if (StatusBlock != null)
{
switch (type)
{
case NotifyType.StatusMessage:
StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
break;
case NotifyType.ErrorMessage:
StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
break;
}
StatusBlock.Text = strMessage;
// Collapse the StatusBlock if it has no text to conserve real estate.
if (StatusBlock.Text != String.Empty)
{
StatusBorder.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
else
{
StatusBorder.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
}
public enum NotifyType
{
StatusMessage,
ErrorMessage
};
}
}
| 37.680162 | 151 | 0.590523 | [
"MIT"
] | Ranin26/msdn-code-gallery-microsoft | Official Windows Platform Sample/Windows Phone 8.1 samples/111541-Windows Phone 8.1 samples/ScreenRecorderQuickstart/C#/MainPage.xaml.cs | 9,307 | C# |
using Sandbox;
using System;
using System.Collections.Generic;
[Library( "ent_car_ferrari", Title = "Ferrari", Spawnable = true )]
public partial class FerrariEntity : Prop, IUse
{
[ConVar.Replicated( "debug_car" )]
public static bool debug_car { get; set; } = false;
private FerrariWheel frontLeft;
private FerrariWheel frontRight;
private FerrariWheel backLeft;
private FerrariWheel backRight;
private float frontLeftDistance;
private float frontRightDistance;
private float backLeftDistance;
private float backRightDistance;
private bool frontWheelsOnGround;
private bool backWheelsOnGround;
private float accelerateDirection;
[Net] private float WheelSpeed { get; set; }
[Net] private float TurnDirection { get; set; }
[Net] private float AccelerationTilt { get; set; }
[Net] private float TurnLean { get; set; }
[Net]
public float MovementSpeed { get; private set; }
private struct InputState
{
public float throttle;
public float turning;
public float breaking;
public bool airControl;
public void Reset()
{
throttle = 0;
turning = 0;
breaking = 0;
airControl = false;
}
}
private InputState currentInput;
public FerrariEntity()
{
frontLeft = new FerrariWheel( this );
frontRight = new FerrariWheel( this );
backLeft = new FerrariWheel( this );
backRight = new FerrariWheel( this );
}
private Player driver;
private ModelEntity chassis_axle_rear;
private ModelEntity chassis_axle_front;
private ModelEntity wheel0;
private ModelEntity wheel1;
private ModelEntity wheel2;
private ModelEntity wheel3;
private readonly List<ModelEntity> clientModels = new();
public override void Spawn()
{
base.Spawn();
var mdl = "models/cars/Ferrari/ferrari";
SetModel( mdl );
SetupPhysicsFromModel( PhysicsMotionType.Dynamic, false );
SetInteractsExclude( CollisionLayer.Player );
var trigger = new ModelEntity
{
Parent = this,
Position = Position,
Rotation = Rotation,
EnableTouch = true,
CollisionGroup = CollisionGroup.Trigger,
Transmit = TransmitType.Never
};
trigger.SetModel( mdl );
trigger.SetupPhysicsFromModel( PhysicsMotionType.Keyframed, false );
}
public override void ClientSpawn()
{
base.ClientSpawn();
{
chassis_axle_front = new ModelEntity();
chassis_axle_front.SetModel( "entities/modular_vehicle/chassis_axle_front.vmdl" );
chassis_axle_front.Transform = Transform;
chassis_axle_front.Parent = this;
chassis_axle_front.LocalPosition = new Vector3( 2.1f, 0, 0.60f ) * 33.0f;
clientModels.Add( chassis_axle_front );
{
wheel0 = new ModelEntity();
wheel0.SetModel( "models/cars/Ferrari/ferrari_wheel" );
wheel0.SetParent( chassis_axle_front, "Wheel_Steer_R", new Transform( Vector3.OneX * (-0.6f * 40), Rotation.From( 0, 180, 0 ) ) );
clientModels.Add( wheel0 );
}
{
wheel1 = new ModelEntity();
wheel1.SetModel( "models/cars/Ferrari/ferrari_wheel" );
wheel1.SetParent( chassis_axle_front, "Wheel_Steer_L", new Transform( Vector3.OneX * (0.6f * 40), Rotation.From( 0, 0, 0 ) ) );
clientModels.Add( wheel1 );
}
{
var chassis_steering = new ModelEntity();
chassis_steering.SetModel( "entities/modular_vehicle/chassis_steering.vmdl" );
chassis_steering.SetParent( chassis_axle_front, "Axle_front_Center", new Transform( Vector3.Zero, Rotation.From( -90, 180, 0 ) ) );
clientModels.Add( chassis_steering );
}
}
{
chassis_axle_rear = new ModelEntity();
chassis_axle_rear.SetModel( "entities/modular_vehicle/chassis_axle_rear.vmdl" );
chassis_axle_rear.Transform = Transform;
chassis_axle_rear.Parent = this;
chassis_axle_rear.LocalPosition = new Vector3( -2.64f, 0, 0.59f ) * 34.0f;
clientModels.Add( chassis_axle_rear );
{
var chassis_transmission = new ModelEntity();
chassis_transmission.SetModel( "entities/modular_vehicle/chassis_transmission.vmdl" );
chassis_transmission.SetParent( chassis_axle_rear, "Axle_Rear_Center", new Transform( Vector3.Zero, Rotation.From( -90, 180, 0 ) ) );
clientModels.Add( chassis_transmission );
}
{
wheel2 = new ModelEntity();
wheel2.SetModel( "models/cars/Ferrari/ferrari_wheel" );
wheel2.SetParent( chassis_axle_rear, "Axle_Rear_Center", new Transform( Vector3.Left * (1.2f * 40), Rotation.From( 0, 90, 0 ) ) );
clientModels.Add( wheel2 );
}
{
wheel3 = new ModelEntity();
wheel3.SetModel( "models/cars/Ferrari/ferrari_wheel" );
wheel3.SetParent( chassis_axle_rear, "Axle_Rear_Center", new Transform( Vector3.Right * (1.2f * 40), Rotation.From( 0, -90, 0 ) ) );
clientModels.Add( wheel3 );
}
}
}
private void RemoveDriver( SandboxPlayer player )
{
driver = null;
player.Vehicle = null;
player.VehicleController = null;
player.VehicleCamera = null;
player.Tags.Remove( "driving" );
ResetInput();
}
protected override void OnDestroy()
{
base.OnDestroy();
if ( driver is SandboxPlayer player )
{
RemoveDriver( player );
}
foreach ( var model in clientModels )
{
model?.Delete();
}
clientModels.Clear();
}
public void ResetInput()
{
currentInput.Reset();
}
[Event.Tick.Server]
protected void Tick()
{
if ( driver is SandboxPlayer player )
{
if ( player.LifeState != LifeState.Alive || player.Vehicle != this )
{
RemoveDriver( player );
}
}
}
public override void Simulate( Client owner )
{
if ( owner == null ) return;
if ( !IsServer ) return;
using ( Prediction.Off() )
{
currentInput.Reset();
if ( Input.Pressed( InputButton.Use ) )
{
if ( owner.Pawn is SandboxPlayer player )
{
RemoveDriver( player );
return;
}
}
currentInput.throttle = (Input.Down( InputButton.Forward ) ? 1 : 0) + (Input.Down( InputButton.Back ) ? -1 : 0);
currentInput.turning = (Input.Down( InputButton.Left ) ? 1 : 0) + (Input.Down( InputButton.Right ) ? -1 : 0);
currentInput.breaking = (Input.Down( InputButton.Jump ) ? 1 : 0);
currentInput.airControl = Input.Down( InputButton.Duck );
}
}
[Event.Physics.PreStep]
public void OnPrePhysicsStep()
{
if ( !IsServer )
return;
var body = PhysicsBody;
if ( !body.IsValid() )
return;
var dt = Time.Delta;
body.DragEnabled = false;
body.LinearDamping = 0;
body.AngularDamping = (backWheelsOnGround && frontWheelsOnGround) ? 0 : 0.5f;
body.GravityScale = (backWheelsOnGround && frontWheelsOnGround) ? 0 : 1;
var rotation = body.Rotation;
accelerateDirection = currentInput.throttle.Clamp( -1, 1 ) * (1.0f - currentInput.breaking);
TurnDirection = TurnDirection.LerpTo( currentInput.turning.Clamp( -1, 1 ), 1.0f - MathF.Pow( 0.0075f, dt ) );
float targetTilt = 0;
float targetLean = 0;
var localVelocity = rotation.Inverse * body.Velocity;
if ( backWheelsOnGround || frontWheelsOnGround )
{
var forwardSpeed = MathF.Abs( localVelocity.x );
var speedFraction = MathF.Min( forwardSpeed / 500.0f, 1 );
targetTilt = accelerateDirection.Clamp( -1.0f, 1.0f );
targetLean = speedFraction * TurnDirection;
}
AccelerationTilt = AccelerationTilt.LerpTo( targetTilt, 1.0f - MathF.Pow( 0.01f, dt ) );
TurnLean = TurnLean.LerpTo( targetLean, 1.0f - MathF.Pow( 0.01f, dt ) );
if ( backWheelsOnGround )
{
var forwardSpeed = MathF.Abs( localVelocity.x );
var speedFactor = 1.0f - (forwardSpeed / 5000.0f).Clamp( 0.0f, 1.0f );
var acceleration = speedFactor * (accelerateDirection < 0.0f ? 500.0f : 1000.0f) * accelerateDirection * dt;
body.Velocity += rotation * new Vector3( acceleration, 0, 0 );
}
RaycastWheels( rotation, true, out frontWheelsOnGround, out backWheelsOnGround, dt );
var onGround = frontWheelsOnGround || backWheelsOnGround;
if ( frontWheelsOnGround && backWheelsOnGround )
{
body.Velocity += PhysicsWorld.Gravity * dt;
}
if ( onGround )
{
float forwardDamping = 0.2f;
body.Velocity = VelocityDamping( body.Velocity, rotation, new Vector3( forwardDamping.LerpTo( 0.99f, currentInput.breaking ), 1.0f, 0.0f ), dt );
localVelocity = rotation.Inverse * body.Velocity;
WheelSpeed = localVelocity.x;
var turnAmount = frontWheelsOnGround ? (MathF.Sign( localVelocity.x ) * 25.0f * CalculateTurnFactor( TurnDirection, MathF.Abs( localVelocity.x ) ) * dt) : 0.0f;
body.AngularVelocity += rotation * new Vector3( 0, 0, turnAmount );
body.AngularVelocity = VelocityDamping( body.AngularVelocity, rotation, new Vector3( 0, 0, 0.999f ), dt );
}
localVelocity = rotation.Inverse * body.Velocity;
MovementSpeed = localVelocity.x;
}
private static float CalculateTurnFactor( float direction, float speed )
{
var turnFactor = MathF.Min( speed / 500.0f, 1 );
var yawSpeedFactor = 1.0f - (speed / 1000.0f).Clamp( 0, 0.5f );
return direction * turnFactor * yawSpeedFactor;
}
private static Vector3 VelocityDamping( Vector3 velocity, Rotation rotation, Vector3 damping, float dt )
{
var localVelocity = rotation.Inverse * velocity;
var dampingPow = new Vector3( MathF.Pow( 1.0f - damping.x, dt ), MathF.Pow( 1.0f - damping.y, dt ), MathF.Pow( 1.0f - damping.z, dt ) );
return rotation * (localVelocity * dampingPow);
}
private void RaycastWheels( Rotation rotation, bool doPhysics, out bool frontWheels, out bool backWheels, float dt )
{
float forward = 90;
float right = 50;
var frontLeftPos = rotation.Forward * forward + rotation.Right * right + rotation.Up * 20;
var frontRightPos = rotation.Forward * forward - rotation.Right * right + rotation.Up * 20;
var backLeftPos = -rotation.Forward * forward + rotation.Right * right + rotation.Up * 20;
var backRightPos = -rotation.Forward * forward - rotation.Right * right + rotation.Up * 20;
var tiltAmount = AccelerationTilt * 2.5f;
var leanAmount = TurnLean * 2.5f;
float length = 30.0f;
frontWheels =
frontLeft.Raycast( length + tiltAmount - leanAmount, doPhysics, frontLeftPos * Scale, ref frontLeftDistance, dt ) |
frontRight.Raycast( length + tiltAmount + leanAmount, doPhysics, frontRightPos * Scale, ref frontRightDistance, dt );
backWheels =
backLeft.Raycast( length - tiltAmount - leanAmount, doPhysics, backLeftPos * Scale, ref backLeftDistance, dt ) |
backRight.Raycast( length - tiltAmount + leanAmount, doPhysics, backRightPos * Scale, ref backRightDistance, dt );
}
float wheelAngle = 0.0f;
float wheelRevolute = 0.0f;
[Event.Frame]
public void OnFrame()
{
wheelAngle = wheelAngle.LerpTo( CalculateTurnFactor( TurnDirection, Math.Abs( WheelSpeed ) ), 1.0f - MathF.Pow( 0.01f, Time.Delta ) );
wheelRevolute += (WheelSpeed / (14.0f * Scale)).RadianToDegree() * Time.Delta;
var wheelRotRight = Rotation.From( -wheelAngle * 70, 180, -wheelRevolute );
var wheelRotLeft = Rotation.From( wheelAngle * 70, 0, wheelRevolute );
var wheelRotBackRight = Rotation.From( 0, 90, -wheelRevolute );
var wheelRotBackLeft = Rotation.From( 0, -90, wheelRevolute );
RaycastWheels( Rotation, false, out _, out _, Time.Delta );
float frontOffset = 20.0f - Math.Min( frontLeftDistance, frontRightDistance );
float backOffset = 20.0f - Math.Min( backLeftDistance, backRightDistance );
chassis_axle_front.SetBoneTransform( "Axle_front_Center", new Transform( Vector3.Up * frontOffset ), false );
chassis_axle_rear.SetBoneTransform( "Axle_Rear_Center", new Transform( Vector3.Up * backOffset ), false );
wheel0.LocalRotation = wheelRotRight;
wheel1.LocalRotation = wheelRotLeft;
wheel2.LocalRotation = wheelRotBackRight;
wheel3.LocalRotation = wheelRotBackLeft;
}
public bool OnUse( Entity user )
{
if ( user is SandboxPlayer player && player.Vehicle == null )
{
player.Vehicle = this;
player.VehicleController = new FerrariController();
player.VehicleCamera = new FerrariCamera();
player.Tags.Add( "driving" );
driver = player;
}
return true;
}
public bool IsUsable( Entity user )
{
return driver == null;
}
public override void StartTouch( Entity other )
{
base.StartTouch( other );
if ( !IsServer )
return;
var body = PhysicsBody;
if ( !body.IsValid() )
return;
if ( other != driver && other is Player player )
{
var speed = body.Velocity.Length;
var forceOrigin = Position + Rotation.Down * Rand.Float( 20, 30 );
var velocity = (player.Position - forceOrigin).Normal * speed;
var angularVelocity = body.AngularVelocity;
OnPhysicsCollision( new CollisionEventData
{
Entity = player,
Pos = player.Position + Vector3.Up * 50,
Velocity = velocity,
PreVelocity = velocity,
PostVelocity = velocity,
PreAngularVelocity = angularVelocity,
Speed = speed,
} );
}
}
protected override void OnPhysicsCollision( CollisionEventData eventData )
{
if ( !IsServer )
return;
var propData = GetModelPropData();
var minImpactSpeed = propData.MinImpactDamageSpeed;
if ( minImpactSpeed <= 0.0f ) minImpactSpeed = 500;
var impactDmg = propData.ImpactDamage;
if ( impactDmg <= 0.0f ) impactDmg = 10;
var speed = eventData.Speed;
if ( speed > minImpactSpeed )
{
if ( eventData.Entity.IsValid() && eventData.Entity != this )
{
var damage = speed / minImpactSpeed * impactDmg * 1.2f;
eventData.Entity.TakeDamage( DamageInfo.Generic( damage )
.WithFlag( DamageFlags.PhysicsImpact )
.WithAttacker( driver != null ? driver : this, driver != null ? this : null )
.WithPosition( eventData.Pos )
.WithForce( eventData.PreVelocity ) );
}
}
if ( eventData.Entity is SandboxPlayer player && player.Vehicle == null )
{
if ( player.LifeState == LifeState.Dead )
{
Particles.Create( "particles/impact.flesh.bloodpuff-big.vpcf", eventData.Pos );
Particles.Create( "particles/impact.flesh-big.vpcf", eventData.Pos );
PlaySound( "kersplat" );
}
}
}
}
| 30.260965 | 163 | 0.699109 | [
"MIT"
] | rayzoxisback/xnbox | code/entities/cars/Ferrari/FerrariEntity.cs | 13,799 | C# |
using Lyra.Core.Accounts;
using Lyra.Core.API;
using Lyra.Core.Blocks;
using Lyra.Core.Cryptography;
using Lyra.Exchange;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lyra.Core.Utils;
namespace Lyra.Core.Exchange
{
public class DealEngine
{
private IMongoCollection<ExchangeAccount> _exchangeAccounts;
private IMongoCollection<ExchangeOrder> _queue;
private IMongoCollection<ExchangeOrder> _finished;
private LyraConfig _config;
public event EventHandler OnNewOrder;
public DealEngine(
IMongoCollection<ExchangeAccount> exchangeAccounts,
IMongoCollection<ExchangeOrder> queue,
IMongoCollection<ExchangeOrder> finished
)
{
_config = Neo.Settings.Default.LyraNode;
_exchangeAccounts = exchangeAccounts;
_queue = queue;
_finished = finished;
}
public async Task<ExchangeAccount> GetExchangeAccount(string accountID, bool refreshBalance = false)
{
var findResult = await _exchangeAccounts.FindAsync(a => a.AssociatedToAccountId == accountID);
var acct = await findResult.FirstOrDefaultAsync();
if (!refreshBalance)
return acct;
if (acct != null)
{
// create wallet and update balance
var memStor = new AccountInMemoryStorage();
var acctWallet = new ExchangeAccountWallet(memStor, _config.Lyra.NetworkId);
acctWallet.AccountName = "tmpAcct";
await acctWallet.RestoreAccountAsync("", acct.PrivateKey);
acctWallet.OpenAccount("", acctWallet.AccountName);
for (int i = 0; i < 300; i++)
{
var result = await acctWallet.Sync(null);
if (result == APIResultCodes.Success)
break;
}
{
var transb = acctWallet.GetLatestBlock();
if (transb != null)
{
if (acct.Balance == null)
acct.Balance = new Dictionary<string, decimal>();
else
acct.Balance.Clear();
foreach (var b in transb.Balances)
{
acct.Balance.Add(b.Key, b.Value);
}
_exchangeAccounts.ReplaceOne(a => a.AssociatedToAccountId == accountID, acct);
}
}
}
return acct;
}
public async Task<decimal> GetExchangeAccountBalance(string accountID, string tokenName)
{
var findResult = await _exchangeAccounts.FindAsync(a => a.AssociatedToAccountId == accountID);
var acct = await findResult.FirstOrDefaultAsync();
if (acct == null)
return 0;
if (!acct.Balance.ContainsKey(tokenName))
return 0;
return acct.Balance[tokenName];
}
public async Task<ExchangeAccount> AddExchangeAccount(string assocaitedAccountId)
{
var findResult = await _exchangeAccounts.FindAsync(a => a.AssociatedToAccountId == assocaitedAccountId);
var findAccount = await findResult.FirstOrDefaultAsync();
if (findAccount != null)
{
return findAccount;
}
var walletPrivateKey = Signatures.GenerateWallet().privateKey;
var walletAccountId = Signatures.GetAccountIdFromPrivateKey(walletPrivateKey);
var account = new ExchangeAccount()
{
AssociatedToAccountId = assocaitedAccountId,
AccountId = walletAccountId,
PrivateKey = walletPrivateKey
};
await _exchangeAccounts.InsertOneAsync(account);
return account;
}
public async Task<CancelKey> AddOrderAsync(ExchangeAccount acct, TokenTradeOrder order)
{
order.CreatedTime = DateTime.Now;
var item = new ExchangeOrder()
{
ExchangeAccountId = acct.Id,
Order = order,
CanDeal = true,
State = DealState.Placed,
ClientIP = null
};
await _queue.InsertOneAsync(item);
OnNewOrder?.Invoke(this, new EventArgs());
var key = new CancelKey()
{
State = OrderState.Placed,
Key = item.Id.ToString(),
Order = order
};
return key;
}
public async Task RemoveOrderAsync(string key)
{
var finds = await _queue.FindAsync(a => a.Id == key);
var order = await finds.FirstOrDefaultAsync();
if (order != null)
{
await _queue.DeleteOneAsync(a => a.Id == order.Id);
await SendMarket(order.Order.TokenName);
await ExchangeAccountLiquidation(order.Order.AccountID);
}
}
public async Task<bool> MakeDealAsync()
{
// has new order. do trade
var changedTokens = new List<string>();
var changedAccount = new List<string>();
var placed = await GetNewlyPlacedOrdersAsync();
for (int i = 0; i < placed.Length; i++)
{
var curOrder = placed[i];
if (!changedTokens.Contains(curOrder.Order.TokenName))
changedTokens.Add(curOrder.Order.TokenName);
(bool IsSuccess, decimal balance) mtrans, ctrans;
var matchedOrders = await LookforExecution(curOrder);
if (matchedOrders.Count() > 0)
{
foreach (var matchedOrder in matchedOrders)
{
var tradedAmount = Math.Min(matchedOrder.Order.Amount, curOrder.Order.Amount);
// lets sync exchange wallet first to prevent any error from happening
//Wallet mwallet, cwallet;
//try
//{
//}
// taker profit first
if (curOrder.Order.BuySellType == OrderType.Buy)
{
var tradedPrice = Math.Min(matchedOrder.Order.Price, curOrder.Order.Price);
var lyraAmount = tradedAmount * tradedPrice;
mtrans = await SendFromExchangeAccountToAnotherAsync(matchedOrder.ExchangeAccountId,
curOrder.ExchangeAccountId, matchedOrder.Order.TokenName,
tradedAmount);
ctrans = await SendFromExchangeAccountToAnotherAsync(curOrder.ExchangeAccountId,
matchedOrder.ExchangeAccountId, LyraGlobal.OFFICIALTICKERCODE,
lyraAmount);
//// transfer back the result to user wallet
//var tb1 = await SendFromExchangeAccountBackToUserAsync(curOrder.ExchangeAccountId, matchedOrder.Order.TokenName, tradedAmount);
//var tb2 = await SendFromExchangeAccountBackToUserAsync(matchedOrder.ExchangeAccountId, LyraGlobal.LYRA_TICKER_CODE, lyraAmount);
//Trace.Assert(tb1.IsSuccess && tb2.IsSuccess);
}
else // currentOrder sell
{
var tradedPrice = Math.Max(matchedOrder.Order.Price, curOrder.Order.Price);
var lyraAmount = tradedAmount * tradedPrice;
mtrans = await SendFromExchangeAccountToAnotherAsync(matchedOrder.ExchangeAccountId,
curOrder.ExchangeAccountId, LyraGlobal.OFFICIALTICKERCODE,
lyraAmount);
ctrans = await SendFromExchangeAccountToAnotherAsync(curOrder.ExchangeAccountId,
matchedOrder.ExchangeAccountId, matchedOrder.Order.TokenName,
tradedAmount);
//// transfer back to user
//var tb1 = await SendFromExchangeAccountBackToUserAsync(curOrder.ExchangeAccountId, LyraGlobal.LYRA_TICKER_CODE, lyraAmount);
//var tb2 = await SendFromExchangeAccountBackToUserAsync(matchedOrder.ExchangeAccountId, matchedOrder.Order.TokenName, tradedAmount);
//Trace.Assert(tb1.IsSuccess && tb2.IsSuccess);
}
if (!mtrans.IsSuccess || !ctrans.IsSuccess)
{
throw new Exception("Exchange Deal Engin Fatal Error");
}
// three conditions
if (matchedOrder.Order.Amount < curOrder.Order.Amount)
{
//matched -> archive, cur -> partial
matchedOrder.State = DealState.Executed;
await _queue.DeleteOneAsync(Builders<ExchangeOrder>.Filter.Eq(o => o.Id, matchedOrder.Id));
await _finished.InsertOneAsync(matchedOrder);
curOrder.State = DealState.PartialExecuted;
curOrder.Order.Amount -= matchedOrder.Order.Amount;
if (!changedAccount.Contains(matchedOrder.Order.AccountID))
changedAccount.Add(matchedOrder.Order.AccountID);
if (!changedAccount.Contains(curOrder.Order.AccountID))
changedAccount.Add(curOrder.Order.AccountID);
continue;
}
else if (matchedOrder.Order.Amount == curOrder.Order.Amount)
{
// matched -> archive, cur -> archive
matchedOrder.State = DealState.Executed;
await _queue.DeleteOneAsync(Builders<ExchangeOrder>.Filter.Eq(o => o.Id, matchedOrder.Id));
await _finished.InsertOneAsync(matchedOrder);
curOrder.State = DealState.Executed;
await _queue.DeleteOneAsync(Builders<ExchangeOrder>.Filter.Eq(o => o.Id, curOrder.Id));
await _finished.InsertOneAsync(curOrder);
if (!changedAccount.Contains(matchedOrder.Order.AccountID))
changedAccount.Add(matchedOrder.Order.AccountID);
if (!changedAccount.Contains(curOrder.Order.AccountID))
changedAccount.Add(curOrder.Order.AccountID);
break;
}
else // matchedOrder.Order.Amount > curOrder.Order.Amount
{
// matched -> partial, cur -> archive
matchedOrder.State = DealState.PartialExecuted;
matchedOrder.Order.Amount -= curOrder.Order.Amount;
await _queue.ReplaceOneAsync(Builders<ExchangeOrder>.Filter.Eq(o => o.Id, matchedOrder.Id), matchedOrder);
curOrder.State = DealState.Executed;
await _queue.DeleteOneAsync(Builders<ExchangeOrder>.Filter.Eq(o => o.Id, curOrder.Id));
await _finished.InsertOneAsync(curOrder);
if (!changedAccount.Contains(matchedOrder.Order.AccountID))
changedAccount.Add(matchedOrder.Order.AccountID);
if (!changedAccount.Contains(curOrder.Order.AccountID))
changedAccount.Add(curOrder.Order.AccountID);
break;
}
}
}
// all matched. update database
// change state from placed to queued, update amount also.
var update = Builders<ExchangeOrder>.Update.Set(o => o.Order.Amount, curOrder.Order.Amount);
if (curOrder.State == DealState.Placed)
update = update.Set(s => s.State, DealState.Queued);
if (curOrder.State == DealState.Placed || curOrder.State == DealState.PartialExecuted)
await _queue.UpdateOneAsync(Builders<ExchangeOrder>.Filter.Eq(o => o.Id, curOrder.Id), update);
}
foreach (var tokenName in changedTokens)
{
// the update the client
await SendMarket(tokenName);
}
foreach (var account in changedAccount)
{
// client must refresh by itself
//NotifyService.Notify(account, Core.API.NotifySource.Dex, "Deal", "", "");
await ExchangeAccountLiquidation(account);
}
return true;
}
private async Task ExchangeAccountLiquidation(string associatedAccountId)
{
var ordersFind = await _queue.FindAsync(a => a.Order.AccountID == associatedAccountId);
if (await ordersFind.AnyAsync())
return;
var fromResult = await _exchangeAccounts.FindAsync(a => a.AssociatedToAccountId == associatedAccountId);
var fromAcct = await fromResult.FirstOrDefaultAsync();
if (fromAcct != null)
{
var fromWallet = await GetExchangeAccountWallet(fromAcct.PrivateKey);
{
var transb = fromWallet.GetLatestBlock();
if (transb != null)
{
int sendCount = 0;
foreach (var kvp in transb.Balances)
{
if (kvp.Value > 0 && kvp.Key != LyraGlobal.OFFICIALTICKERCODE)
{
var ret = await fromWallet.Send(kvp.Value, associatedAccountId, kvp.Key, true);
Trace.Assert(ret.ResultCode == APIResultCodes.Success);
sendCount++;
}
}
sendCount++;
if (transb.Balances[LyraGlobal.OFFICIALTICKERCODE] - sendCount * ExchangingBlock.FEE > 0)
{
var ret2 = await fromWallet.Send(transb.Balances[LyraGlobal.OFFICIALTICKERCODE] - sendCount * ExchangingBlock.FEE, associatedAccountId, LyraGlobal.OFFICIALTICKERCODE, true);
Trace.Assert(ret2.ResultCode == APIResultCodes.Success);
}
}
}
}
}
private async Task<(bool IsSuccess, decimal balance)> SendFromExchangeAccountToAnotherAsync(string fromId, string toId, string tokenName, decimal amount)
{
var fromResult = await _exchangeAccounts.FindAsync(a => a.Id == fromId);
var fromAcct = await fromResult.FirstOrDefaultAsync();
var toResult = await _exchangeAccounts.FindAsync(a => a.Id == toId);
var toAcct = await toResult.FirstOrDefaultAsync();
var fromWallet = await GetExchangeAccountWallet(fromAcct.PrivateKey);
var transb = fromWallet.GetLatestBlock();
if (transb != null && transb.Balances[tokenName] >= amount)
{
var bLast = transb.Balances[tokenName] - amount;
var ret = await fromWallet.Send(amount, toAcct.AccountId, tokenName, true);
return (ret.ResultCode == APIResultCodes.Success, bLast);
}
else
{
return (false, 0);
}
}
private async Task<(bool IsSuccess, decimal balance)> SendFromExchangeAccountBackToUserAsync(string fromId, string tokenName, decimal amount)
{
var fromResult = await _exchangeAccounts.FindAsync(a => a.Id == fromId);
var fromAcct = await fromResult.FirstOrDefaultAsync();
var fromWallet = await GetExchangeAccountWallet(fromAcct.PrivateKey);
var transb = fromWallet.GetLatestBlock();
if (transb != null && transb.Balances[tokenName] >= amount)
{
var bLast = transb.Balances[tokenName] - amount;
var ret = await fromWallet.Send(amount, fromAcct.AssociatedToAccountId, tokenName, true);
return (ret.ResultCode == APIResultCodes.Success, bLast);
}
else
{
return (false, 0);
}
}
private async Task<Wallet> GetExchangeAccountWallet(string privateKey)
{
// create wallet and update balance
var memStor = new AccountInMemoryStorage();
var fromWallet = new Wallet(memStor, _config.Lyra.NetworkId);
fromWallet.AccountName = "tmpAcct";
await fromWallet.RestoreAccountAsync("", privateKey);
fromWallet.OpenAccount("", fromWallet.AccountName);
APIResultCodes result = APIResultCodes.UnknownError;
for (int i = 0; i < 300; i++)
{
result = await fromWallet.Sync(null);
if (result == APIResultCodes.Success)
break;
}
Trace.Assert(result == APIResultCodes.Success);
return fromWallet;
}
public async Task<ExchangeOrder[]> GetNewlyPlacedOrdersAsync()
{
var finds = await _queue.FindAsync(a => a.State == DealState.Placed);
var fl = await finds.ToListAsync();
return fl.OrderBy(a => a.Order.CreatedTime).ToArray();
}
public async Task<ExchangeOrder[]> GetQueuedOrdersAsync()
{
var finds = await _queue.FindAsync(a => a.CanDeal);
var fl = await finds.ToListAsync();
return fl.OrderBy(a => a.Order.CreatedTime).ToArray();
}
public async Task<IOrderedEnumerable<ExchangeOrder>> LookforExecution(ExchangeOrder order)
{
//var builder = Builders<ExchangeOrder>.Filter;
//var filter = builder.Eq("Order.TokenName", order.Order.TokenName)
// & builder.Ne("State", DealState.Placed);
//if (order.Order.BuySellType == OrderType.Buy)
//{
// filter &= builder.Eq("Order.BuySellType", OrderType.Sell);
// filter &= builder.Lte("Order.Price", order.Order.Price);
//}
//else
//{
// filter &= builder.Eq("Order.BuySellType", OrderType.Buy);
// filter &= builder.Gte("Order.Price", order.Order.Price);
//}
IAsyncCursor<ExchangeOrder> found;
if (order.Order.BuySellType == OrderType.Buy)
{
found = await _queue.FindAsync(a => a.Order.TokenName == order.Order.TokenName
&& a.State != DealState.Placed
&& a.Order.BuySellType == OrderType.Sell
&& a.Order.Price <= order.Order.Price);
}
else
{
found = await _queue.FindAsync(a => a.Order.TokenName == order.Order.TokenName
&& a.State != DealState.Placed
&& a.Order.BuySellType == OrderType.Buy
&& a.Order.Price >= order.Order.Price);
}
var matches0 = await found.ToListAsync();
if (order.Order.BuySellType == OrderType.Buy)
{
var matches = matches0.OrderBy(a => a.Order.Price);
return matches;
}
else
{
var matches = matches0.OrderByDescending(a => a.Order.Price);
return matches;
}
}
public async Task<List<ExchangeOrder>> GetActiveOrders(string tokenName)
{
return await _queue.Find(a => a.CanDeal && a.Order.TokenName == tokenName).ToListAsync();
}
public async Task SendMarket(string tokenName)
{
var excOrders = (await GetActiveOrders(tokenName)).OrderByDescending(a => a.Order.Price);
var sellOrders = excOrders.Where(a => a.Order.BuySellType == OrderType.Sell)
.GroupBy(a => a.Order.Price)
.Select(a => new KeyValuePair<Decimal, Decimal>(a.Key, a.Sum(x => x.Order.Amount))).ToList();
var buyOrders = excOrders.Where(a => a.Order.BuySellType == OrderType.Buy)
.GroupBy(a => a.Order.Price)
.Select(a => new KeyValuePair<Decimal, Decimal>(a.Key, a.Sum(x => x.Order.Amount))).ToList();
var orders = new Dictionary<string, List<KeyValuePair<Decimal, Decimal>>>();
orders.Add("SellOrders", sellOrders);
orders.Add("BuyOrders", buyOrders);
//NotifyService.Notify("", Core.API.NotifySource.Dex, "Orders", tokenName, JsonConvert.SerializeObject(orders));
}
public async Task<List<ExchangeOrder>> GetOrdersForAccount(string accountId)
{
return await _queue.Find(a => a.Order.AccountID == accountId).ToListAsync();
}
}
}
| 45.182377 | 201 | 0.53372 | [
"MIT"
] | wizd/WizardDAG | Core/Lyra.Core/Exchange/DealEngine.cs | 22,051 | C# |
namespace MvcForum.Web.ViewModels.Registration
{
using System.ComponentModel.DataAnnotations;
using Application;
public class ForgotPasswordViewModel
{
[ForumMvcResourceDisplayName("Members.Label.EmailAddressBlank")]
[EmailAddress]
[Required]
public string EmailAddress { get; set; }
}
} | 26.230769 | 72 | 0.697947 | [
"MIT"
] | YodasMyDad/mvcforum | MVCForum.Website/ViewModels/Registration/ForgotPasswordViewModel.cs | 343 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the servicecatalog-2015-12-10.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ServiceCatalog.Model
{
/// <summary>
/// Container for the parameters to the AssociatePrincipalWithPortfolio operation.
/// Associates the specified principal ARN with the specified portfolio.
/// </summary>
public partial class AssociatePrincipalWithPortfolioRequest : AmazonServiceCatalogRequest
{
private string _acceptLanguage;
private string _portfolioId;
private string _principalARN;
private PrincipalType _principalType;
/// <summary>
/// Gets and sets the property AcceptLanguage.
/// <para>
/// The language code.
/// </para>
/// <ul> <li>
/// <para>
/// <code>en</code> - English (default)
/// </para>
/// </li> <li>
/// <para>
/// <code>jp</code> - Japanese
/// </para>
/// </li> <li>
/// <para>
/// <code>zh</code> - Chinese
/// </para>
/// </li> </ul>
/// </summary>
[AWSProperty(Max=100)]
public string AcceptLanguage
{
get { return this._acceptLanguage; }
set { this._acceptLanguage = value; }
}
// Check to see if AcceptLanguage property is set
internal bool IsSetAcceptLanguage()
{
return this._acceptLanguage != null;
}
/// <summary>
/// Gets and sets the property PortfolioId.
/// <para>
/// The portfolio identifier.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=100)]
public string PortfolioId
{
get { return this._portfolioId; }
set { this._portfolioId = value; }
}
// Check to see if PortfolioId property is set
internal bool IsSetPortfolioId()
{
return this._portfolioId != null;
}
/// <summary>
/// Gets and sets the property PrincipalARN.
/// <para>
/// The ARN of the principal (IAM user, role, or group).
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=1000)]
public string PrincipalARN
{
get { return this._principalARN; }
set { this._principalARN = value; }
}
// Check to see if PrincipalARN property is set
internal bool IsSetPrincipalARN()
{
return this._principalARN != null;
}
/// <summary>
/// Gets and sets the property PrincipalType.
/// <para>
/// The principal type. The supported value is <code>IAM</code>.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public PrincipalType PrincipalType
{
get { return this._principalType; }
set { this._principalType = value; }
}
// Check to see if PrincipalType property is set
internal bool IsSetPrincipalType()
{
return this._principalType != null;
}
}
} | 31.030303 | 113 | 0.556641 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ServiceCatalog/Generated/Model/AssociatePrincipalWithPortfolioRequest.cs | 4,096 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace MornLib.Mono {
[RequireComponent(typeof(RectTransform))]
public class AnimationLayoutMono : MonoBehaviour {
[SerializeField] private Dir _dir;
[SerializeField] private int _spacing;
[SerializeField] private bool _ignoreTimeScale = true;
[SerializeField] private List<RectTransform> _list = new List<RectTransform>();
private const float _movement = 20;
private void Update() {
var offsetPos = Vector2.zero;
var isUpDown = _dir == Dir.Up || _dir == Dir.Down;
var dirVector = DirToVector(_dir);
foreach(var rect in _list) {
var curPos = (Vector2) rect.anchoredPosition;
var dif = isUpDown ? offsetPos.y - curPos.y : offsetPos.x - curPos.x;
var deltaTime = _ignoreTimeScale ? Time.unscaledDeltaTime : Time.deltaTime;
var aimPos = curPos + (isUpDown ? Vector2.up : Vector2.right) * (dif * Mathf.Min(1,deltaTime* _movement));
rect.anchoredPosition = aimPos;
offsetPos += dirVector * ((isUpDown ? rect.rect.size.y : rect.rect.size.x) + _spacing);
}
}
private static Vector2 DirToVector(Dir dir) {
switch(dir) {
case Dir.Up: return Vector2.up;
case Dir.Left: return Vector2.left;
case Dir.Right: return Vector2.right;
case Dir.Down: return Vector2.down;
default: throw new ArgumentOutOfRangeException();
}
}
private void OnTransformChildrenChanged() {
_list.Clear();
for(var i = transform.childCount - 1;i >= 0;i--) {
if(transform.GetChild(i).TryGetComponent<RectTransform>(out var rect)) {
_list.Add(rect);
}
}
}
private enum Dir {
Up
,Left
,Right
,Down
}
}
} | 42.142857 | 122 | 0.556416 | [
"Unlicense"
] | matsufriends/MornLib | Mono/AnimationLayoutMono.cs | 2,067 | C# |
//Problem 5. Workdays
//Write a method that calculates the number of workdays between today and given date, passed as parameter.
//Consider that workdays are all days from Monday to Friday except a fixed list of public holidays specified preliminary as array.
using System;
using System.Linq;
class Workdays
{
static void Main()
{
Console.WriteLine("Please enter date in format DD/MM/YYYY:");
DateTime date = DateTime.Parse(Console.ReadLine());
DateTime today = DateTime.Now;
if (today > date)
{
Console.WriteLine("The number of workdays between today and {0:dd/MM/yyyy} is {1}", date, CalcWorkdays(date, today));
}
else
{
Console.WriteLine("The number of workdays between today and {0:dd/MM/yyyy} is {1}", date, CalcWorkdays(today, date));
}
}
private static int CalcWorkdays(DateTime from, DateTime to)
{
int businessDays = 0;
for (DateTime i = from.AddDays(1); i <= to; i = i.AddDays(1))
{
if (i.DayOfWeek != DayOfWeek.Saturday
&& i.DayOfWeek != DayOfWeek.Sunday
&& !IsHoliday(i))
businessDays++;
}
return businessDays;
}
private static bool IsHoliday(DateTime date)
{
DateTime[] holidays = new DateTime[]
{ new DateTime(2015,01,01),
new DateTime(2015,03,02),
new DateTime(2015,03,03),
new DateTime(2015,04,10),
new DateTime(2015,04,11),
new DateTime(2015,04,12),
new DateTime(2015,04,13),
new DateTime(2015,05,01),
new DateTime(2015,05,06),
new DateTime(2015,09,21),
new DateTime(2015,09,22),
new DateTime(2015,09,21),
new DateTime(2015,09,21),
new DateTime(2015,12,24),
new DateTime(2015,12,25),
new DateTime(2015,12,26),
new DateTime(2015,12,31)};
return holidays.Contains(date);
}
}
| 30.597015 | 130 | 0.572195 | [
"MIT"
] | zvet80/TelerikAcademy | 02.C#2/05.ClassesAndObjects/05.Workdays/Workdays.cs | 2,052 | C# |
using System;
using System.Linq;
namespace Slides
{
class Program
{
static void Main()
{
// read dimensions
string[] line = Console.ReadLine().Split(' ');
int cuboidWidth = int.Parse(line[0]);
int cuboidHeigth = int.Parse(line[1]);
int cuboidDepth = int.Parse(line[2]);
// read cuboid
string[, ,] cuboid = new string[cuboidWidth, cuboidHeigth, cuboidDepth];
for (int h = 0; h < cuboidHeigth; h++)
{
string[] row = Console.ReadLine().Split('|');
for (int d = 0; d < cuboidDepth; d++)
{
string[] cubes = row[d].Trim().Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
for (int w = 0; w < cuboidWidth; w++)
{
string cube = cubes[w];
cuboid[w, h, d] = cube;
}
}
}
// read ball
line = Console.ReadLine().Split(' ');
int ballWidth = 0;
int ballHeight = 0;
int ballDepth = 0;
// execute ball falling
int nextWidth = int.Parse(line[0]);
int nextHeight = 0;
int nextDepth = int.Parse(line[1]);
bool canDropo = true;
string currentCube = "";
while (canDropo)
{
if (nextHeight == cuboidHeigth)
{
break;
}
if (0 > nextWidth || nextWidth > cuboidWidth - 1 ||
0 > nextDepth || nextDepth > cuboidDepth - 1)
{
canDropo = false;
break;
}
ballWidth = nextWidth;
ballHeight = nextHeight;
ballDepth = nextDepth;
// read current cube
currentCube = cuboid[nextWidth, nextHeight, nextDepth];
// execute current cube commnad
// S X; T 1 1; B; E
char command = currentCube[0];
switch (command)
{
case 'B': canDropo = false; break;
case 'E': nextHeight++; break;
case 'T': // "T 1 1"
int[] coord = currentCube.Substring(2).Split(' ')
.Select(x => int.Parse(x)).ToArray();
nextWidth = coord[0];
nextDepth = coord[1];
break;
case 'S': // S L; R; F; B; FL FL..
nextHeight++;
string dir = currentCube.Substring(2);
switch (dir)
{
case "L": nextWidth--; break;
case "R": nextWidth++; break;
case "F": nextDepth--; break;
case "B": nextDepth++; break;
case "FL": nextWidth--; nextDepth--; break;
case "FR": nextWidth++; nextDepth--; break;
case "BL": nextWidth--; nextDepth++; break;
case "BR": nextWidth++; nextDepth++; break;
}
break;
}
}
// output
Console.WriteLine(canDropo ? "Yes" : "No");
Console.WriteLine("{0} {1} {2}", ballWidth, ballHeight, ballDepth);
}
}
} | 36.069307 | 121 | 0.39171 | [
"MIT"
] | AYankova/CSharp | Exams2012/03.Slides/Program.cs | 3,645 | C# |
using Address.Contract.DTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Address.Contract.Mappers
{
/// <summary>
/// Maps between the entity and the dto.
/// </summary>
public static class AddressMapper
{
/// <summary>
/// Maps an entity to a dto.
/// </summary>
/// <param name="address">Persistence address.</param>
/// <returns>AddressDTO.</returns>
public static AddressDTO EntityToDTO(Persistence.Model.Address address)
{
if (address == null) return null;
AddressDTO addressDTO = new AddressDTO
{
Id = address.Id,
Latitude = address.Latitude,
Longitude = address.Longitude,
Number = address.Number,
Street = address.Street,
Country = CountryMapper.EntityToDTO(address.Country)
};
return addressDTO;
}
/// <summary>
/// Maps a dto to an entity.
/// </summary>
/// <param name="addressDTO">DTO address.</param>
/// <param name="address">Persistence address.</param>
/// <returns>Address.</returns>
public static Persistence.Model.Address DTOToEntity(AddressDTO addressDTO, Persistence.Model.Address address)
{
if (addressDTO == null) return null;
if (address == null) address = new Persistence.Model.Address();
address.Id = addressDTO.Id;
address.Latitude = addressDTO.Latitude;
address.Longitude = addressDTO.Longitude;
address.Number = addressDTO.Number;
address.Street = addressDTO.Street;
return address;
}
/// <summary>
/// Maps a collection of entities to dtos.
/// </summary>
/// <param name="addresses">List of entity addresses.</param>
/// <returns>List of AddressDTO.</returns>
public static List<AddressDTO> EntitiesToDTOs(List<Persistence.Model.Address> addresses)
{
if (addresses == null) return null;
List<AddressDTO> addressesDTO = new List<AddressDTO>();
foreach (var address in addresses)
{
addressesDTO.Add(EntityToDTO(address));
}
return addressesDTO;
}
/// <summary>
/// Maps a collection of dtos to entities.
/// </summary>
/// <param name="addressesDTO">List of DTO addresses.</param>
/// <returns>List of addresses.</returns>
public static List<Persistence.Model.Address> DTOsToEntities(List<AddressDTO> addressesDTO)
{
if (addressesDTO == null) return null;
List<Persistence.Model.Address> addresses = new List<Persistence.Model.Address>();
foreach (var addressDTO in addressesDTO)
{
addresses.Add(DTOToEntity(addressDTO, null));
}
return addresses;
}
}
}
| 33.397849 | 117 | 0.569221 | [
"MIT"
] | LuisSanchez/WebApi-Core-3.0-Boilerplate | Address.Contract/Mappers/AddressMapper.cs | 3,108 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BDSA2019.Lecture09.Models;
using BDSA2019.Lecture09.Web.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
using static BDSA2019.Lecture09.Models.Response;
namespace BDSA2019.Lecture09.Web.Tests.Controllers
{
public class SuperheroesControllerTests
{
[Fact]
public async Task Get_returns_result_from_repository()
{
var superheroes = new List<SuperheroListDTO>();
var repository = new Mock<ISuperheroRepository>();
repository.Setup(m => m.ReadAsync()).ReturnsAsync(superheroes);
var logger = new Mock<ILogger<SuperheroesController>>();
var controller = new SuperheroesController(repository.Object, logger.Object);
var result = await controller.Get();
Assert.Equal(superheroes, result.Value);
}
[Fact]
public async Task Get_id_returns_result_from_repository()
{
var superhero = new SuperheroDetailsDTO();
var repository = new Mock<ISuperheroRepository>();
repository.Setup(m => m.ReadAsync(42)).ReturnsAsync(superhero);
var logger = new Mock<ILogger<SuperheroesController>>();
var controller = new SuperheroesController(repository.Object, logger.Object);
var result = await controller.Get(42);
Assert.Equal(superhero, result.Value);
}
[Fact]
public async Task Get_id_given_repository_returns_null_returns_NotFound()
{
var superhero = new SuperheroDetailsDTO();
var repository = new Mock<ISuperheroRepository>();
repository.Setup(m => m.ReadAsync(42)).ReturnsAsync(default(SuperheroDetailsDTO));
var logger = new Mock<ILogger<SuperheroesController>>();
var controller = new SuperheroesController(repository.Object, logger.Object);
var result = await controller.Get(42);
Assert.IsType<NotFoundResult>(result.Result);
}
[Fact]
public async Task Post_returns_CreatedAtAction_with_id()
{
var superhero = new SuperheroCreateDTO();
var repository = new Mock<ISuperheroRepository>();
repository.Setup(s => s.CreateAsync(superhero)).ReturnsAsync((Created, 42));
var logger = new Mock<ILogger<SuperheroesController>>();
var controller = new SuperheroesController(repository.Object, logger.Object);
var actual = await controller.Post(superhero);
Assert.Equal("Get", actual.ActionName);
Assert.Equal(42, actual.RouteValues["id"]);
}
[Theory]
[InlineData(Updated, typeof(NoContentResult))]
[InlineData(NotFound, typeof(NotFoundResult))]
public async Task Put_given_repository_returns_response_returns_returnType(Response response, Type returnType)
{
var superhero = new SuperheroUpdateDTO { Id = 12 };
var repository = new Mock<ISuperheroRepository>();
repository.Setup(s => s.UpdateAsync(superhero)).ReturnsAsync(response);
var logger = new Mock<ILogger<SuperheroesController>>();
var controller = new SuperheroesController(repository.Object, logger.Object);
var actual = await controller.Put(12, superhero);
Assert.IsType(returnType, actual);
}
[Theory]
[InlineData(Deleted, typeof(NoContentResult))]
[InlineData(NotFound, typeof(NotFoundResult))]
public async Task Delete_given_repository_returns_response_returns_returnType(Response response, Type returnType)
{
var repository = new Mock<ISuperheroRepository>();
repository.Setup(s => s.DeleteAsync(42)).ReturnsAsync(response);
var logger = new Mock<ILogger<SuperheroesController>>();
var controller = new SuperheroesController(repository.Object, logger.Object);
var actual = await controller.Delete(42);
Assert.IsType(returnType, actual);
}
}
}
| 35.542373 | 121 | 0.654268 | [
"MIT"
] | ondfisk/BDSA2019 | BDSA2019.Lecture09/BDSA2019.Lecture09.Web.Tests/Controllers/SuperheroesControllerTests.cs | 4,194 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Selection;
namespace AlphaBIM
{
class LocCot : ISelectionFilter
{
public bool AllowElement(Element elem)
{
// Cách 2: để lọc đối tượng: Dùng CategoryId
int categoryId = elem.Category.Id.IntegerValue;
int structuralColumnId = (int)BuiltInCategory.OST_StructuralColumns;
if (categoryId == structuralColumnId)
{
return true;
}
else
{
return false;
}
}
public bool AllowReference(Reference reference, XYZ position)
{
return true;
}
}
}
| 23.228571 | 80 | 0.578106 | [
"MIT"
] | alphabim/Revit-API-Basic-Course | Lesson04_SelectionFiltering/LocCot.cs | 828 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using SamuraiApp.Data;
using System;
namespace SamuraiApp.Data.Migrations
{
[DbContext(typeof(SamuraiContext))]
[Migration("20190912135139_relationships")]
partial class relationships
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.1-rtm-125")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("SamuraiApp.Domain.Battle", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("EndDate");
b.Property<string>("Name");
b.Property<DateTime>("StartDate");
b.HasKey("Id");
b.ToTable("Battles");
});
modelBuilder.Entity("SamuraiApp.Domain.Quote", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("SamuraiId");
b.Property<string>("Text");
b.HasKey("Id");
b.HasIndex("SamuraiId");
b.ToTable("Quotes");
});
modelBuilder.Entity("SamuraiApp.Domain.Samurai", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Samurais");
});
modelBuilder.Entity("SamuraiApp.Domain.SamuraiBattle", b =>
{
b.Property<int>("SamuraiId");
b.Property<int>("BattleId");
b.HasKey("SamuraiId", "BattleId");
b.HasIndex("BattleId");
b.ToTable("SamuraiBattle");
});
modelBuilder.Entity("SamuraiApp.Domain.SecretIdentity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("RealName");
b.Property<int>("SamuraiId");
b.HasKey("Id");
b.HasIndex("SamuraiId")
.IsUnique();
b.ToTable("SecretIdentity");
});
modelBuilder.Entity("SamuraiApp.Domain.Quote", b =>
{
b.HasOne("SamuraiApp.Domain.Samurai", "Samurai")
.WithMany("Quotes")
.HasForeignKey("SamuraiId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SamuraiApp.Domain.SamuraiBattle", b =>
{
b.HasOne("SamuraiApp.Domain.Battle", "Battle")
.WithMany("SamuraiBattles")
.HasForeignKey("BattleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SamuraiApp.Domain.Samurai", "Samurai")
.WithMany("SamuraiBattles")
.HasForeignKey("SamuraiId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SamuraiApp.Domain.SecretIdentity", b =>
{
b.HasOne("SamuraiApp.Domain.Samurai")
.WithOne("SecretIdentity")
.HasForeignKey("SamuraiApp.Domain.SecretIdentity", "SamuraiId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 32.053846 | 117 | 0.487881 | [
"MIT"
] | davikawasaki/csharp-ef2-core-pluralsight | SamuraiAppEFCoreGettingStarted/SamuraiApp.Data/Migrations/20190912135139_relationships.Designer.cs | 4,169 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.Windows.Shell;
using System.Windows.Threading;
using System.Xml;
using GalaSoft.MvvmLight.Messaging;
using log4net;
using log4net.Config;
using MahApps.Metro;
using Mono.Options;
using Noterium.Code.Commands;
using Noterium.Code.Messages;
using Noterium.Core;
using Noterium.Core.DataCarriers;
using Noterium.Core.Helpers;
using Noterium.ViewModels;
using Noterium.Views.Dialogs;
namespace Noterium
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
private static ILog _log;
private DispatcherTimer _activityTimer;
private Library _currentLibrary;
private Point _inactiveMousePosition = new Point(0, 0);
private MainWindow _mainWindow;
private bool _mainWindowLoaded;
public App()
{
var currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
_log.Error(e.ExceptionObject);
}
public void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (_log != null)
{
_log.Error(e.Exception.Message, e.Exception);
return;
}
Hub.Instance.AppSettings.LogFatal(e.Exception.ToString());
}
private void App_OnStartup(object sender, StartupEventArgs e)
{
Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
string libraryName;
InitCommandArgs(out libraryName);
RegisterCustomAccents();
try
{
Hub.Instance.AppSettings.Init();
}
catch (InvalidConfigurationFileException)
{
var result = MessageBox.Show("The configuration file seems to be corrupt. Do you want me to recreate it with default settings for you?", "Corrupt configuration file", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
Hub.Instance.AppSettings.Save();
}
else
{
Current.Shutdown();
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), ex.Message);
Current.Shutdown();
return;
}
var library = GetLibrary(libraryName);
if (library == null)
{
Current.Shutdown(1);
return;
}
Current.DispatcherUnhandledException += CurrentDispatcherUnhandledException;
LoadLibrary(library);
InputManager.Current.PreProcessInput += OnActivity;
Current.Deactivated += OnDeactivated;
}
private void InitCommandArgs(out string libraryName)
{
libraryName = null;
string library = null;
var shouldShowHelp = false;
var options = new OptionSet
{
{"l|library=", "The name of a library to load", l => library = l},
{"h|help", "show this message and exit", h => shouldShowHelp = h != null}
};
var args = Environment.GetCommandLineArgs();
List<string> extra;
try
{
// parse the command line
extra = options.Parse(args);
}
catch (OptionException e)
{
// output some error message
Console.Write("noterium: ");
Console.WriteLine(e.Message);
Console.WriteLine("Try `noterium --help' for more information.");
Current.Shutdown(0);
return;
}
if (shouldShowHelp)
{
Console.WriteLine("Usage: noterium.exe [OPTIONS]");
Console.WriteLine();
Console.WriteLine("Options:");
options.WriteOptionDescriptions(Console.Out);
Current.Shutdown(0);
return;
}
libraryName = library;
}
private static void RegisterCustomAccents()
{
ThemeManager.AddAccent("VSDark", new Uri("pack://application:,,,/Resources/VSDark.xaml"));
ThemeManager.AddAccent("VSLight", new Uri("pack://application:,,,/Resources/VSLight.xaml"));
}
private static Library GetLibrary(string libraryName)
{
Library library = null;
if (!Hub.Instance.AppSettings.Librarys.Any())
{
var selector = new StorageSelector();
selector.ShowDialog();
}
else
{
var libName = libraryName ?? Hub.Instance.AppSettings.DefaultLibrary ?? string.Empty;
library = Hub.Instance.AppSettings.Librarys.FirstOrDefault(l => l.Name.Equals(libName));
}
return library ?? Hub.Instance.AppSettings.Librarys.FirstOrDefault();
}
private void LoadLibrary(Library library)
{
_currentLibrary = library;
ViewModelLocator.Cleanup();
Hub.Instance.Init(library);
InitLog4Net();
SetAppTheme();
Hub.Instance.Settings.PropertyChanged += SettingsPropertyChanged;
_activityTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMinutes(Hub.Instance.Settings.AutoLockMainWindowAfter),
IsEnabled = true
};
_activityTimer.Tick += OnInactivity;
var loading = new LoadingWindow();
SetTheme(loading);
loading.Loaded += LoadingLoaded;
loading.SetMessage("Initializing core");
loading.Show();
}
private void LoadingLoaded(object sender, RoutedEventArgs e)
{
var t = new Thread(Load);
t.Start(sender);
}
private void Load(object sender)
{
var loading = (LoadingWindow) sender;
_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
_log.Info("Application started");
Hub.Instance.Storage.DataStore.InitCache(s => { Current.Dispatcher.Invoke(() => { loading.SetMessage(s); }); });
// TODO: i18n
loading.SetMessage("Loading models");
ViewModelLocator.Instance.NotebookMenu.Loaded = true;
ViewModelLocator.Instance.NoteMenu.Loaded = true;
ViewModelLocator.Instance.NoteView.Loaded = true;
ViewModelLocator.Instance.Main.Loaded = true;
ViewModelLocator.Instance.Librarys.Loaded = true;
ViewModelLocator.Instance.Settings.Loaded = true;
ViewModelLocator.Instance.BackupManager.Loaded = true;
loading.SetMessage("Loading main window");
Current.Dispatcher.Invoke(ShowMainWindow);
Current.Dispatcher.Invoke(() => { loading.Close(); });
}
private static void CurrentDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (_log != null)
{
_log.Fatal(e.Exception.Message, e.Exception);
}
else
{
var message = e.Exception.FlattenException();
Hub.Instance.AppSettings.LogFatal(message);
}
}
private void ShowMainWindow()
{
_mainWindow = new MainWindow();
Messenger.Default.Register<ChangeLibrary>(this, DoChangeLibrary);
_mainWindow.Title = _currentLibrary.Name + " - " + Noterium.Properties.Resources.Title;
_mainWindow.Model = ViewModelLocator.Instance.Main;
_mainWindow.Width = _currentLibrary.WindowSize.Width;
_mainWindow.Height = _currentLibrary.WindowSize.Height;
_mainWindow.WindowState = _currentLibrary.WindowState;
_mainWindow.Model.LockCommand = new SimpleCommand(Lock);
Current.MainWindow = _mainWindow;
SetTheme(_mainWindow);
_mainWindow.Show();
if (Hub.Instance.EncryptionManager.SecureNotesEnabled) _mainWindow.Lock(true);
_mainWindowLoaded = true;
SetJumpList();
Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
private void SetJumpList()
{
var jumpList = new JumpList();
jumpList.ShowFrequentCategory = true;
foreach (var l in Hub.Instance.AppSettings.Librarys)
{
var task = new JumpTask
{
Title = l.Name,
Arguments = "-l " + l.Name,
Description = Noterium.Properties.Resources.JumpList_LoadLibraryTitle + l.Name,
CustomCategory = Noterium.Properties.Resources.JumpList_LibrarysCategoryName,
IconResourcePath = Assembly.GetEntryAssembly().CodeBase,
ApplicationPath = Assembly.GetEntryAssembly().CodeBase
};
jumpList.JumpItems.Add(task);
}
JumpList.SetJumpList(Current, jumpList);
}
private void DoChangeLibrary(ChangeLibrary obj)
{
var library = obj.Library;
if (_currentLibrary != null && library.Name.Equals(_currentLibrary.Name, StringComparison.OrdinalIgnoreCase))
return;
Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
_mainWindow.Model.NoteMenuContext.SelectedNote = null;
_mainWindow.Close();
_mainWindowLoaded = false;
LoadLibrary(library);
}
private void SettingsPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "AutoLockMainWindowAfter")
{
if (Hub.Instance.Settings.AutoLockMainWindowAfter == 0)
{
_activityTimer.Stop();
_activityTimer.IsEnabled = false;
return;
}
if (!_activityTimer.IsEnabled)
_activityTimer.IsEnabled = true;
_activityTimer.Stop();
_activityTimer.Interval = TimeSpan.FromMinutes(Hub.Instance.Settings.AutoLockMainWindowAfter);
_activityTimer.Start();
}
}
private void OnInactivity(object sender, EventArgs e)
{
if (!Hub.Instance.EncryptionManager.SecureNotesEnabled)
return;
// remember mouse position
_inactiveMousePosition = Mouse.GetPosition(_mainWindow.MainGrid);
Lock();
}
private void OnActivity(object sender, PreProcessInputEventArgs e)
{
if (_activityTimer == null || _mainWindow == null)
return;
var inputEventArgs = e.StagingItem.Input;
if (inputEventArgs is MouseEventArgs || inputEventArgs is KeyboardEventArgs)
{
var mouseEventArgs = e.StagingItem.Input as MouseEventArgs;
// no button is pressed and the position is still the same as the application became inactive
if (mouseEventArgs?.LeftButton == MouseButtonState.Released &&
mouseEventArgs.RightButton == MouseButtonState.Released &&
mouseEventArgs.MiddleButton == MouseButtonState.Released &&
mouseEventArgs.XButton1 == MouseButtonState.Released &&
mouseEventArgs.XButton2 == MouseButtonState.Released &&
_inactiveMousePosition == mouseEventArgs.GetPosition(_mainWindow.MainGrid))
return;
_activityTimer.Stop();
_activityTimer.Start();
}
}
private void SetAppTheme()
{
var theme = ThemeManager.GetAppTheme(Hub.Instance.Settings.Theme);
var accent = ThemeManager.GetAccent(Hub.Instance.Settings.Accent);
ThemeManager.ChangeAppStyle(Current, accent, theme);
}
public static void SetTheme(Window w)
{
var theme = ThemeManager.GetAppTheme(Hub.Instance.Settings.Theme);
var accent = ThemeManager.GetAccent(Hub.Instance.Settings.Accent);
if (w != null)
ThemeManager.ChangeAppStyle(w, accent, theme);
}
private static void InitLog4Net()
{
var logXml = Noterium.Properties.Resources.LogXml;
var logPath = Hub.Instance.Storage.DataStore.RootFolder + "\\log";
if (!Directory.Exists(logPath))
Directory.CreateDirectory(logPath);
logXml = logXml.Replace("{LOGPATH}", logPath);
var doc = new XmlDocument();
doc.LoadXml(logXml);
XmlConfigurator.Configure(doc.DocumentElement);
}
private void OnDeactivated(object sender, EventArgs eventArgs)
{
if (!_mainWindowLoaded)
return;
//if (Hub.Instance.EncryptionManager.SecureNotesEnabled)
//{
// if (Hub.Instance.Settings.AutoLockMainWindowAfter == 0)
// Lock();
//}
}
private void Lock(object param)
{
Lock();
}
private void Lock()
{
_mainWindow.Lock();
}
}
} | 33.511905 | 233 | 0.569734 | [
"MIT"
] | ekblom/noterium | src/Noterium/App.xaml.cs | 14,077 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using TicketCode.Core.Data;
namespace TicketCode.WebHost.Migrations
{
[DbContext(typeof(TcDbContext))]
partial class TcDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.5")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("TicketCode.Core.Models.TcAccounts", b =>
{
b.Property<long>("id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<bool>("bDisable")
.HasColumnType("tinyint(1)");
b.Property<string>("sAppId")
.IsRequired()
.HasColumnType("varchar(50) CHARACTER SET utf8mb4")
.HasMaxLength(50);
b.Property<string>("sAppName")
.IsRequired()
.HasColumnType("varchar(50) CHARACTER SET utf8mb4")
.HasMaxLength(50);
b.Property<string>("sAppSecret")
.IsRequired()
.HasColumnType("varchar(50) CHARACTER SET utf8mb4")
.HasMaxLength(50);
b.Property<DateTime>("tCreateTime")
.HasColumnType("datetime(6)");
b.HasKey("id");
b.HasIndex("sAppId")
.IsUnique();
b.ToTable("TcAccounts");
});
modelBuilder.Entity("TicketCode.Core.Models.TcConsume", b =>
{
b.Property<long>("id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<long>("iAccountId")
.HasColumnType("bigint");
b.Property<long>("iFullCode")
.HasColumnType("bigint");
b.Property<long>("iGroupId")
.HasColumnType("bigint");
b.Property<long>("iRequestLineId")
.HasColumnType("bigint");
b.Property<DateTime>("tConsumeTime")
.HasColumnType("datetime(6)");
b.HasKey("id");
b.HasIndex("iAccountId");
b.HasIndex("iFullCode");
b.HasIndex("iGroupId");
b.HasIndex("iRequestLineId")
.IsUnique();
b.ToTable("TcConsume");
});
modelBuilder.Entity("TicketCode.Core.Models.TcGroupInAccount", b =>
{
b.Property<long>("id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<long>("iAccountId")
.HasColumnType("bigint");
b.Property<long>("iGroupId")
.HasColumnType("bigint");
b.HasKey("id");
b.HasIndex("iAccountId");
b.HasIndex("iGroupId");
b.ToTable("TcGroupInAccount");
});
modelBuilder.Entity("TicketCode.Core.Models.TcGroups", b =>
{
b.Property<long>("id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<bool>("bDelete")
.HasColumnType("tinyint(1)");
b.Property<bool>("bDisable")
.HasColumnType("tinyint(1)");
b.Property<long>("iCurrAvaNumber")
.HasColumnType("bigint");
b.Property<long>("iIncrNumber")
.HasColumnType("bigint");
b.Property<int>("iLength")
.HasColumnType("int");
b.Property<long>("iMinNumber")
.HasColumnType("bigint");
b.Property<int>("iPrefixCode")
.HasColumnType("int");
b.Property<long>("iUsedNumber")
.HasColumnType("bigint");
b.Property<string>("sName")
.IsRequired()
.HasColumnType("varchar(10) CHARACTER SET utf8mb4")
.HasMaxLength(10);
b.Property<DateTime>("tCreateTime")
.HasColumnType("datetime(6)");
b.Property<DateTime?>("tUpdateTime")
.HasColumnType("datetime(6)");
b.HasKey("id");
b.ToTable("TcGroups");
});
modelBuilder.Entity("TicketCode.Core.Models.TcRequestLines", b =>
{
b.Property<long>("id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<bool>("bConsume")
.HasColumnType("tinyint(1)");
b.Property<long>("iCode")
.HasColumnType("bigint");
b.Property<long>("iFullCode")
.HasColumnType("bigint");
b.Property<long>("iRequestId")
.HasColumnType("bigint");
b.Property<DateTime?>("tConsumeTime")
.HasColumnType("datetime(6)");
b.HasKey("id");
b.HasIndex("iFullCode");
b.HasIndex("iRequestId");
b.ToTable("TcRequestLines");
});
modelBuilder.Entity("TicketCode.Core.Models.TcRequsets", b =>
{
b.Property<long>("id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<long>("iAccountId")
.HasColumnType("bigint");
b.Property<long>("iGroupId")
.HasColumnType("bigint");
b.Property<int>("iNumber")
.HasColumnType("int");
b.Property<string>("sMemo")
.HasColumnType("varchar(250) CHARACTER SET utf8mb4")
.HasMaxLength(250);
b.Property<string>("sOuterNo")
.IsRequired()
.HasColumnType("varchar(50) CHARACTER SET utf8mb4")
.HasMaxLength(50);
b.Property<string>("sRequestNo")
.IsRequired()
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<DateTime>("tCreateTime")
.HasColumnType("datetime(6)");
b.Property<DateTime>("tExpireTime")
.HasColumnType("datetime(6)");
b.HasKey("id");
b.HasIndex("iGroupId");
b.HasIndex("iAccountId", "iGroupId", "sOuterNo")
.IsUnique();
b.ToTable("TcRequsets");
});
modelBuilder.Entity("TicketCode.Core.Models.TcConsume", b =>
{
b.HasOne("TicketCode.Core.Models.TcAccounts", "TcAccount")
.WithMany()
.HasForeignKey("iAccountId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("TicketCode.Core.Models.TcGroups", "TcGroup")
.WithMany()
.HasForeignKey("iGroupId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("TicketCode.Core.Models.TcRequestLines", "TcRequestLine")
.WithOne("TcConsume")
.HasForeignKey("TicketCode.Core.Models.TcConsume", "iRequestLineId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("TicketCode.Core.Models.TcGroupInAccount", b =>
{
b.HasOne("TicketCode.Core.Models.TcAccounts", "TcAccount")
.WithMany("TcGroupInAccounts")
.HasForeignKey("iAccountId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("TicketCode.Core.Models.TcGroups", "TcGroup")
.WithMany("TcGroupInAccounts")
.HasForeignKey("iGroupId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("TicketCode.Core.Models.TcRequestLines", b =>
{
b.HasOne("TicketCode.Core.Models.TcRequsets", "TcRequset")
.WithMany("TcRequestLines")
.HasForeignKey("iRequestId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("TicketCode.Core.Models.TcRequsets", b =>
{
b.HasOne("TicketCode.Core.Models.TcAccounts", "TcAccount")
.WithMany()
.HasForeignKey("iAccountId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("TicketCode.Core.Models.TcGroups", "TcGroup")
.WithMany()
.HasForeignKey("iGroupId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 35.482993 | 92 | 0.438938 | [
"BSD-3-Clause"
] | tanlingyun/ticketcode | src/TicketCode/TicketCode/Migrations/TcDbContextModelSnapshot.cs | 10,434 | C# |
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
namespace MastersThesisCountDown.I2C
{
public abstract class I2C : IDisposable
{
protected I2CDevice Device { get; }
protected int Timeout { get; }
public ushort Address { get; }
public I2C(ushort address, int clockRate, int timeout)
{
this.Address = address;
this.Timeout = timeout;
this.Device = new I2CDevice(new I2CDevice.Configuration(address, clockRate));
}
protected void Write(params byte[] buffer)
{
var transactions = new I2CDevice.I2CWriteTransaction[] { I2CDevice.CreateWriteTransaction(buffer) };
var resultLength = Device.Execute(transactions, Timeout);
while (resultLength < buffer.Length)
{
var extendedBuffer = new byte[buffer.Length - resultLength];
Array.Copy(buffer, resultLength, extendedBuffer, 0, extendedBuffer.Length);
transactions = new I2CDevice.I2CWriteTransaction[] { I2CDevice.CreateWriteTransaction(extendedBuffer) };
resultLength += Device.Execute(transactions, Timeout);
}
if (resultLength != buffer.Length)
{
throw new Exception("Could not write to device.");
}
}
protected byte[] Read(int length)
{
var buffer = new byte[length];
var transactions = new I2CDevice.I2CReadTransaction[] { I2CDevice.CreateReadTransaction(buffer) };
var resultLength = Device.Execute(transactions, Timeout);
if (resultLength != length)
{
throw new Exception("Could not read from device.");
}
return buffer;
}
protected void WriteToRegister(byte register, byte value)
{
Write(register, value);
}
protected byte[] ReadFromRegister(byte register, int length)
{
var buffer = new byte[length];
var transactions = new I2CDevice.I2CTransaction[]
{
I2CDevice.CreateWriteTransaction(new byte[] { register }),
I2CDevice.CreateReadTransaction(buffer)
};
var resultLength = Device.Execute(transactions, Timeout);
if (resultLength != (length + 1))
{
throw new Exception("Could not read from device.");
}
return buffer;
}
public void Dispose()
{
Device.Dispose();
GC.SuppressFinalize(this);
}
}
}
| 31.329412 | 120 | 0.568907 | [
"MIT"
] | terry-u16/MastersThesisCountDown | MastersThesisCountDown/I2C/I2C.cs | 2,663 | C# |
using HealthyLifestyleTrackingApp.Services.LifeCoaches;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using static HealthyLifestyleTrackingApp.Areas.Admin.AdminConstants;
using static HealthyLifestyleTrackingApp.WebConstants;
namespace HealthyLifestyleTrackingApp.Areas.Admin.Controllers
{
[Area(AreaName)]
[Authorize(Roles = AdminConstants.AdministratorRoleName)]
public class LifeCoachesController : Controller
{
private readonly ILifeCoachService lifeCoaches;
public LifeCoachesController(ILifeCoachService lifeCoaches)
{
this.lifeCoaches = lifeCoaches;
}
public IActionResult All()
{
var lifeCoaches = (this.lifeCoaches.All(approvedOnly: false).LifeCoaches);
return View(lifeCoaches);
}
public IActionResult ApproveForLifeCoach(int id)
{
this.lifeCoaches.ApproveForLifeCoach(id);
TempData[GlobalMessageKey] = "Life Coach application was approved. Please inform user.";
return RedirectToAction(nameof(All));
}
}
}
| 29.657895 | 100 | 0.705413 | [
"MIT"
] | VeselinaSidova/Healthy-Lifestyle-Tracking-App | HealthyLifestyleTrackingApp/Areas/Admin/Controllers/LifeCoachesController.cs | 1,129 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace SakerCore.Serialization.DynmaicType
{
#region DynmaicClassSerialize
/************这里使用服务器动态编译的方法实现类型的序列化和反序列化************/
/// <summary>
/// 表示一个类型的动态编排序列化器
/// </summary>
public class DynmaicClassSerialize<T> : TypeSerializationBase<T> where T : class
{
/// <summary>
/// 定义一个委托,这个委托表示当前序列化器的序列化方法的信息
/// </summary>
/// <param name="obj"></param>
/// <param name="stream"></param>
public delegate void Writer(T obj, Stream stream);
/// <summary>
/// 定义一个委托,这个委托表示当前反序列化器的序列化方法的信息
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public delegate T Reader(Stream stream);
Writer WriterHandle;
Reader ReaderHandle;
delUnsafeReaderMethod UnsafeReaderHandle;
/// <summary>
/// 创建动态序列化器
/// </summary>
/// <param name="type"></param>
public DynmaicClassSerialize()
{
var type = typeof(T);
if (CheckTypeLoopRefer(type))
{
throw new System.Exception($"检查到序列化的对象中包含有循环引用。错误类型 :{type.FullName}");
}
this._serializerType = type;
var serializerAttr = type.GetTypeSerializeAttr();
this._serializerName = serializerAttr.TypeCode.IsEmpty(type.FullName);
var ctor = type.GetConstructor(Type.EmptyTypes);
if (ctor == null) throw Error.NonEmptyCtor(type);
var r = GenerateReadMethod(type);
var w = GenerateWriteMethod(type);
var ur = GenerateUnsafeReadMethod(type);
this.ReaderInfo = r;
this.WriterInfo = w;
this.UnsafeReaderInfo = ur;
WriterHandle = (Writer)w.CreateDelegate(typeof(Writer));
ReaderHandle = (Reader)r.CreateDelegate(typeof(Reader));
UnsafeReaderHandle = ur?.CreateDelegate(typeof(delUnsafeReaderMethod)) as delUnsafeReaderMethod;
}
/// <summary>
///
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public override T Deserialize(Stream stream)
{
return ReaderHandle(stream);
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <param name="stream"></param>
public override void Serialize(T obj, Stream stream)
{
WriterHandle(obj, stream);
}
/// <summary>
///
/// </summary>
/// <param name="stream"></param>
/// <param name="pos"></param>
/// <param name="length"></param>
/// <returns></returns>
public override unsafe T UnsafeDeserialize(byte* stream, int* pos, int length)
{
return UnsafeReaderHandle(stream, pos, length);
}
#region 核心方法(创建动态方法。)
private static DynamicMethod GenerateReadMethod(Type type)
{
#region 测试用代码(生成程序集再反编译为 IL 或 C# 代码查看逻辑是否正确)
//var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(type.Name + "Serializer"), AssemblyBuilderAccess.RunAndSave);
//var moduleBuilder = asmBuilder.DefineDynamicModule(type.Name + "Serializer.dll");
//var typeBuilder = moduleBuilder.DefineType(type.Name + "Serializer", TypeAttributes.Public);
//var method = typeBuilder.DefineMethod("Read",
// MethodAttributes.Public | MethodAttributes.Static,
// CallingConventions.Standard,
// type,
// new Type[] { typeof(Stream) }
// );
#endregion
var PacketMemberInfos = GetPacketMemberInfos(type);
//创建动态方法
var method = new DynamicMethod("Read",
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
type,
new Type[] {
typeof(Stream)},
type,
true
);
//指示生成的属性方法IL指令对象
ILGenerator il = method.GetILGenerator();
Type memberType = null;
ITypeSerializer memberSerializer = null;
MethodInfo readMethod = null;
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
#region IL实例
/*
.maxstack 2
.locals init (
[0] class UyiSerlizerTest.TestClass,
[1] bool,
[2] class UyiSerlizerTest.TestClass
)
IL_0001: ldarg.0
IL_0002: call bool class [Uyi.Serialization]Uyi.Serialization.DynmaicType.DynmaicClassSerialize`1<class UyiSerlizerTest.TestClass>::CheckReadObject(class [mscorlib]System.IO.Stream)
IL_0007: ldc.i4.0
IL_0008: ceq
IL_000a: stloc.1
IL_000b: ldloc.1
IL_000c: brfalse.s IL_0012
IL_000e: ldnull
IL_000f: stloc.2
IL_0010: br.s IL_0034
IL_0012: newobj instance void UyiSerlizerTest.TestClass::.ctor()
IL_0017: stloc.0
IL_0018: ldloc.0
IL_0019: ldarg.0
IL_001a: call int32 [Uyi.Serialization]Uyi.Serialization.BaseType.Int32TypeSerialize::Read(class [mscorlib]System.IO.Stream)
IL_001f: stfld int32 UyiSerlizerTest.TestClass::ID
IL_0024: ldloc.0
IL_0025: ldarg.0
IL_0026: call int32 [Uyi.Serialization]Uyi.Serialization.BaseType.Int32TypeSerialize::Read(class [mscorlib]System.IO.Stream)
IL_002b: stfld int32 UyiSerlizerTest.TestClass::ID2
IL_0030: ldloc.0
IL_0031: stloc.2
IL_0032: br.s IL_0034
IL_0034: ldloc.2
IL_0035: ret
*/
#endregion
//验证类型是否具有默认的初始化方法
var defaultConstructor = type.GetConstructor(Type.EmptyTypes);
if (defaultConstructor == null)
throw Error.NonEmptyCtor(type);
var retValue = il.DeclareLocal(type); // 声明局部变量(变量类型为需返回的消息类型)。
#if CanSerializeNullObject
/****插入指令验证对象是否可以反序列化,不是 null 对象则序列化,是 null 则返回 null ****/
var bl = il.DeclareLocal(typeof(bool)); // 声明局部变量(变量类型为需返回的消息类型)。
//获取验证方法
var checkReadMethod = typeof(DynmaicClassSerialize<>).MakeGenericType(type)
.GetMethod(nameof(CheckReadObject), BindingFlags.Public | BindingFlags.Static);
if (checkReadMethod == null)
throw new System.Exception($"没找到指定类型【{type.FullName}】的【{nameof(CheckWriterObject)}】,无法完成对象反序列化的验证过程");
var labelFalse = il.DefineLabel();
//加载第一个参数以便后续调用
il.Emit(OpCodes.Ldarg_0);
//调用验证方法
il.Emit(OpCodes.Call, checkReadMethod);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ceq); //插入判断比较的IL指令
il.Emit(OpCodes.Stloc, bl);
il.Emit(OpCodes.Ldloc, bl);
il.Emit(OpCodes.Brfalse_S, labelFalse); //判断为false 跳转到 labelFalse 标签位置指令
il.Emit(OpCodes.Ldnull); //将空引用(O 类型)推送到计算堆栈上。
il.Emit(OpCodes.Stloc, retValue); // 将已实例化并已完成字段或属性值赋值的消息对象压入计算堆栈中。
il.Emit(OpCodes.Ldloc, retValue); // 将已实例化并已完成字段或属性值赋值的消息对象压入计算堆栈中。
il.Emit(OpCodes.Ret); // 函数返回。
//插入指令标签 labelFalse
il.MarkLabel(labelFalse);
#endif
//调用类型的默认初始化方法来创建新的实例
il.Emit(OpCodes.Newobj, defaultConstructor);
//将类型初始化的的对象实例存储到指定的变量中
il.Emit(OpCodes.Stloc, retValue);
foreach (var pmi in PacketMemberInfos)
{
readMethod = null;
memberType = (pmi.Member is FieldInfo) ? ((FieldInfo)pmi.Member).FieldType : ((PropertyInfo)pmi.Member).PropertyType;
if (memberType.IsEnum)
memberType = typeof(byte);
// 使用全局序列化器。
memberSerializer = TypeSerializerFactory.GetOrCreateTypeSerializer(memberType);
if (null == memberSerializer)
throw new System.Exception(string.Format("系统未找到类型 {0} 的序列化器,无法反序列化。1", memberType.FullName));
readMethod = memberSerializer.ReaderInfo;
if (null == readMethod)
throw new System.Exception(string.Format("系统未找到类型 {0} 的序列化器,无法反序列化。2", memberType.FullName));
// 将刚刚创建的对象压入到计算堆栈中(后进先出)供后续方法调用。(在栈底)
il.Emit(OpCodes.Ldloc, retValue);
il.Emit(OpCodes.Ldarg_0); // 将第 1 个参数 stream 的值压入到计算堆栈中供后续方法调用。(在栈顶)
il.Emit(OpCodes.Call, readMethod); // 调用反序列化方法,方法签名为:public static T Read<T>(Stream)。
if (pmi.Member is PropertyInfo) // 成员是属性,调用 Set 方法。
il.Emit(OpCodes.Callvirt, type.GetProperty(pmi.Member.Name, bindingFlags).GetSetMethod(true));
else // 成员是字段,直接赋值。
il.Emit(OpCodes.Stfld, type.GetField(pmi.Member.Name, bindingFlags));
}
il.Emit(OpCodes.Ldloc, retValue); // 将已实例化并已完成字段或属性值赋值的消息对象压入计算堆栈中。
il.Emit(OpCodes.Ret); // 函数返回。
#region 测试用代码(生成程序集)
//var t = typeBuilder.CreateType();
//asmBuilder.Save(type.Name + "Serializer.dll");
#endregion
return method;
}
private static DynamicMethod GenerateWriteMethod(Type type)
{
//var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(type.Name + "Serializer"), AssemblyBuilderAccess.RunAndSave);
//var moduleBuilder = asmBuilder.DefineDynamicModule(type.Name + "Serializer.dll");
//var typeBuilder = moduleBuilder.DefineType(type.Name + "Serializer", TypeAttributes.Public);
//var method = typeBuilder.DefineMethod("Writer",
// MethodAttributes.Public | MethodAttributes.Static,
// CallingConventions.Standard,
// null,
// new Type[] { type, typeof(Stream) }
// );
var PacketMemberInfos = GetPacketMemberInfos(type);
var method = new DynamicMethod("Write",
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
null,
new Type[] { type, typeof(Stream) },
type,
true
);
#region IL 示例
/*
// 用 C# 编写测试类型的序列化功能后,反编译为如下 IL 代码可供参考。
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: call bool UyiSerlizerTest.TestClass::CheckObjectWriter(class UyiSerlizerTest.TestClass, class [mscorlib]System.IO.Stream)
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_001e
IL_0011: ldarg.0
IL_0012: ldfld int32 UyiSerlizerTest.TestClass::ID
IL_0017: ldarg.1
IL_0018: call void [Uyi.Serialization]Uyi.Serialization.BaseType.Int32TypeSerialize::Write(int32, class [mscorlib]System.IO.Stream)
IL_001d: nop
IL_001e: ret
*/
#endregion
ILGenerator il = method.GetILGenerator();
Type memberType = null;
ITypeSerializer memberSerializer = null;
MethodInfo writeMethod = null;
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
#if CanSerializeNullObject //表示是否可以序列化NULL对象
#region 当序列化器支持序列化null对象时的处理逻辑
var checkWrtertMethod = typeof(DynmaicClassSerialize<>).MakeGenericType(type)
.GetMethod(nameof(CheckWriterObject), BindingFlags.Public | BindingFlags.Static);
if (checkWrtertMethod == null)
throw new System.Exception($"没找到指定类型【{type.FullName}】的【{nameof(CheckWriterObject)}】,无法完成对象序列化的验证过程");
var bl = il.DeclareLocal(typeof(bool));
var labelTrue = il.DefineLabel();
var labelFalse = il.DefineLabel();
il.Emit(OpCodes.Ldarg_0); // 将第 1 个参数 value 压入到计算堆栈中(后进先出)供后续方法调用。
il.Emit(OpCodes.Ldarg_1); // 将第 2 个参数 stream 压入到计算堆栈中(后进先出)供后续方法调用。
//调用对象是否为null的验证方法
il.Emit(OpCodes.Call, checkWrtertMethod);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ceq); //插入比较指令
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Brtrue_S, labelFalse);
il.Emit(OpCodes.Br_S, labelTrue);
il.MarkLabel(labelFalse);//定义判断为false的跳转标签
//验证为false时直接返回
il.Emit(OpCodes.Ret);
il.MarkLabel(labelTrue);//定义判断为true的跳转标签
#endregion
#endif
foreach (var pmi in PacketMemberInfos)
{
writeMethod = null;
memberType = (pmi.Member is FieldInfo) ? ((FieldInfo)pmi.Member).FieldType : ((PropertyInfo)pmi.Member).PropertyType;
if (memberType.IsEnum)
{
memberType = typeof(byte);
}
//获取成员类型的序列化器
memberSerializer = TypeSerializerFactory.GetOrCreateTypeSerializer(memberType);
if (null == memberSerializer)
throw new System.Exception(string.Format("系统未找到类型 {0} 的序列化器,无法反序列化。1", memberType.FullName));
//序列化类型的序列化方法
// var writer = new Writer(memberSerializer.Serialize);
writeMethod = memberSerializer.WriterInfo;
if (writeMethod == null)
throw new System.Exception(string.Format("系统未找到类型 {0} 的序列化器,无法反序列化。2", memberType.FullName));
il.Emit(OpCodes.Ldarg_0); // 将第 1 个参数 value 压入到计算堆栈中(后进先出)供后续方法调用。
if (pmi.Member is PropertyInfo) // 成员是属性。获取属性值。
il.Emit(OpCodes.Callvirt, type.GetProperty(pmi.Member.Name, bindingFlags).GetGetMethod(true));
else // 成员是字段。获取字段值。
il.Emit(OpCodes.Ldfld, type.GetField(pmi.Member.Name, bindingFlags));
il.Emit(OpCodes.Ldarg_1); // 将第 2 个参数 stream 压入到计算堆栈中(后进先出)供后续方法调用。
il.Emit(OpCodes.Call, writeMethod); // 调用序列化方法,方法签名为:public static void Write(object,Stream)。
}
il.Emit(OpCodes.Ret); // 直接返回。
return method;
}
private DynamicMethod GenerateUnsafeReadMethod(Type type)
{
var PacketMemberInfos = GetPacketMemberInfos(type);
//#region 测试用代码(生成程序集再反编译为 IL 或 C# 代码查看逻辑是否正确)
//var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(type.Name + "Serializer"), AssemblyBuilderAccess.RunAndSave);
//var moduleBuilder = asmBuilder.DefineDynamicModule(type.Name + "Serializer.dll");
//var typeBuilder = moduleBuilder.DefineType(type.Name + "Serializer", TypeAttributes.Public);
//var method = typeBuilder.DefineMethod("UnsafeRead",
// MethodAttributes.Public | MethodAttributes.Static,
// CallingConventions.Standard,
// type,
// new Type[] { typeof(byte*), typeof(int*), typeof(int) }
// );
//#endregion
//创建动态方法
var method = new DynamicMethod("UnsafeRead",
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
type,
new Type[] { typeof(byte*), typeof(int*), typeof(int) },
type,
true
);
//指示生成的属性方法IL指令对象
ILGenerator il = method.GetILGenerator();
Type memberType = null;
ITypeSerializer memberSerializer = null;
MethodInfo readMethod = null;
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
//验证类型是否具有默认的初始化方法
var defaultConstructor = type.GetConstructor(Type.EmptyTypes);
if (defaultConstructor == null)
throw Error.NonEmptyCtor(type);
var retValue = il.DeclareLocal(type); // 声明局部变量(变量类型为需返回的消息类型)。
#if CanSerializeNullObject
/****插入指令验证对象是否可以反序列化,不是 null 对象则序列化,是 null 则返回 null ****/
var bl = il.DeclareLocal(typeof(bool)); // 声明局部变量(变量类型为需返回的消息类型)。
//获取验证方法
var checkReadMethod = typeof(DynmaicClassSerialize<>).MakeGenericType(type)
.GetMethod(nameof(UnsafeCheckReadObject), BindingFlags.Public | BindingFlags.Static);
if (checkReadMethod == null)
throw new System.Exception($"没找到指定类型【{type.FullName}】的【{nameof(UnsafeCheckReadObject)}】,无法完成对象反序列化的验证过程");
var labelFalse = il.DefineLabel();
//加载第一个参数以便后续调用
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
//调用验证方法
il.Emit(OpCodes.Call, checkReadMethod);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ceq); //插入判断比较的IL指令
il.Emit(OpCodes.Stloc, bl);
il.Emit(OpCodes.Ldloc, bl);
il.Emit(OpCodes.Brfalse_S, labelFalse); //判断为false 跳转到 labelFalse 标签位置指令
il.Emit(OpCodes.Ldnull); //将空引用(O 类型)推送到计算堆栈上。
il.Emit(OpCodes.Stloc, retValue); // 将已实例化并已完成字段或属性值赋值的消息对象压入计算堆栈中。
il.Emit(OpCodes.Ldloc, retValue); // 将已实例化并已完成字段或属性值赋值的消息对象压入计算堆栈中。
il.Emit(OpCodes.Ret); // 函数返回。
//插入指令标签 labelFalse
il.MarkLabel(labelFalse);
#endif
//调用类型的默认初始化方法来创建新的实例
il.Emit(OpCodes.Newobj, defaultConstructor);
//将类型初始化的的对象实例存储到指定的变量中
il.Emit(OpCodes.Stloc, retValue);
foreach (var pmi in PacketMemberInfos)
{
readMethod = null;
memberType = (pmi.Member is FieldInfo) ? ((FieldInfo)pmi.Member).FieldType : ((PropertyInfo)pmi.Member).PropertyType;
if (memberType.IsEnum)
memberType = typeof(byte); //如果是枚举类型使用byte类型的序列化器
// 使用全局序列化器。
memberSerializer = TypeSerializerFactory.GetOrCreateTypeSerializer(memberType);
if (null == memberSerializer)
throw new System.Exception(string.Format("系统未找到类型 {0} 的序列化器,无法反序列化。1", memberType.FullName));
readMethod = memberSerializer.UnsafeReaderInfo;
if (null == readMethod)
throw new System.Exception(string.Format("系统未找到类型 {0} 的序列化器,无法反序列化。2", memberType.FullName));
// 将刚刚创建的对象压入到计算堆栈中(后进先出)供后续方法调用。(在栈底)
il.Emit(OpCodes.Ldloc, retValue);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2); //向计算机堆栈压入输入参数
il.Emit(OpCodes.Call, readMethod); // 调用反序列化方法
if (pmi.Member is PropertyInfo) // 成员是属性,调用 Set 方法。
il.Emit(OpCodes.Callvirt, type.GetProperty(pmi.Member.Name, bindingFlags).GetSetMethod(true));
else // 成员是字段,直接赋值。
il.Emit(OpCodes.Stfld, type.GetField(pmi.Member.Name, bindingFlags));
}
il.Emit(OpCodes.Ldloc, retValue); // 将已实例化并已完成字段或属性值赋值的消息对象压入计算堆栈中。
il.Emit(OpCodes.Ret); // 函数返回。
#region 测试用代码(生成程序集)
//var t = typeBuilder.CreateType();
//asmBuilder.Save($@"{type.Name}Serializer.dll");
//return null;
#endregion
return method;
}
#endregion
/// <summary>
/// 反射获取类型的类型成员信息
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static IEnumerable<TypeSerlizaMemberInfo> GetPacketMemberInfos(Type type)
{
var field = type.GetFields();
var pros = type.GetProperties();
List<TypeSerlizaMemberInfo> _listMember = new List<TypeSerlizaMemberInfo>();
foreach (var r in field)
{
if (!r.IsCanSerializeProperty()) continue;
_listMember.Add(new TypeSerlizaMemberInfo()
{
Attribute = r.GetMemberSerializeAttr(),
Member = r
});
}
foreach (var r in pros)
{
if (!r.IsCanSerializeProperty()) continue;
if (!r.CanRead) continue;
if (!r.CanWrite) continue;
_listMember.Add(new TypeSerlizaMemberInfo()
{
Attribute = r.GetMemberSerializeAttr(),
Member = r
});
}
//获取一个属性在继承链条中的继承深度
//var shendu = GetPacketMemberInfosJCSD(r,)
var _serializerList = _listMember.OrderBy(p => p.Attribute.Order);
string befindex = "";
TypeSerlizaMemberInfo before = null;
foreach (var cur in _serializerList)
{
if (cur.Attribute.Order == befindex) throw Error.RepeatOrder(typeof(T).FullName, before, cur);
befindex = cur.Attribute.Order;
before = cur;
}
return _serializerList;
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <param name="stream"></param>
/// <returns></returns>
public static bool CheckWriterObject(T obj, Stream stream)
{
byte by = (byte)(obj == null ? 0 : 1);
stream.WriteByte(by);
if (by == 0)
return false;
return true;
}
/// <summary>
///
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static bool CheckReadObject(Stream stream)
{
var by = stream.ReadByte();
if (by == 0) return false;
return true;
}
/// <summary>
///
/// </summary>
/// <param name="stream"></param>
/// <param name="pos"></param>
/// <param name="length"></param>
/// <returns></returns>
public unsafe static bool UnsafeCheckReadObject(byte* stream, int* pos, int length)
{
*pos += 1;
if (*pos >= length) return false;
var by = stream[(*pos) - 1];
return by == 1;
}
/// <summary>
/// 检查序列化的类中是否有循环引用的对象
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool CheckTypeLoopRefer(Type type)
{
//检查一个类中是否包含循环引用字段信息
Stack<Type> stacktype = new Stack<Type>();
return CheckTypeLoopReferHelper(type, stacktype);
}
private static bool CheckTypeLoopReferHelper(Type type, Stack<Type> stacktype)
{
//检查类型是否是基础类型,如果是直接返回
if (type.IsValueType) return false;
if (type.IsArray)
{
return CheckTypeLoopReferHelper(type.GetElementType(), stacktype);
}
//在当前栈压入当前类型信息
if (CheckHasTypeInfoInStack(type, stacktype))
{
return true;
}
stacktype.Push(type);
//找到当前类型的所有字段信息
var allfields = type.GetFields().Where(p => p.IsDefined(typeof(PacketMemberAttribute), true));
foreach (var f in allfields)
{
if (CheckTypeLoopReferHelper(f.FieldType, stacktype))
{
stacktype.Pop();
return true;
}
}
//找到当前类型的所有字段信息
var allpros = type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.IsDefined(typeof(PacketMemberAttribute), true)
);
foreach (var f in allpros)
{
if (CheckTypeLoopReferHelper(f.PropertyType, stacktype))
{
stacktype.Pop();
return true;
}
}
stacktype.Pop();
return false;
}
private static bool CheckHasTypeInfoInStack(Type type, Stack<Type> stacktype)
{
//遍历栈判断当前类型的对象是否存在
foreach (var r in stacktype)
{
if (r.Equals(type))
return true;
}
return false;
}
}
internal class TypeSerlizaMemberInfo
{
internal PacketMemberAttribute Attribute;
internal MemberInfo Member;
}
#endregion
#region CustomSerializer
/// <summary>
/// 对象的自定义序列化器
/// </summary>
internal class CustomSerializer<T> : TypeSerializationBase<T> where T : ICustomSerializer, new()
{
public CustomSerializer()
{
var type = typeof(T);
this._serializerType = type;
var serializerAttr = type.GetTypeSerializeAttr();
this._serializerName = serializerAttr.TypeCode.IsEmpty(type.FullName);
}
public static void Write(T obj, Stream stream)
{
if (obj == null)
{
stream.WriteByte(0);
return;
}
stream.WriteByte(1);
obj.Serialize(stream);
}
public static T Read(Stream stream)
{
var v = stream.ReadByte();
if (v != 1) return default(T);
var obj = new T();
obj.Deserialize(stream);
return obj;
}
public override T Deserialize(Stream stream)
{
return Read(stream);
}
public override void Serialize(T obj, Stream stream)
{
Write(obj, stream);
}
}
#endregion
}
| 35.746702 | 201 | 0.54067 | [
"MIT"
] | shenrui93/sakercore | SakerCore/Serialization/DynmaicType/DynmaicSerialize.cs | 30,500 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
namespace System.ComponentModel
{
/// <summary>
/// A "container" is an object that logically contains zero or more child
/// components.
/// In this context, "containment" refers to logical containment, not visual
/// containment. Components and containers can be used in a variety of
/// scenarios, including both visual and non-visual scenarios.
/// Provides functionality for containers.
/// </summary>
public interface IContainer : IDisposable
{
/// <summary>
/// Adds the specified <see cref='System.ComponentModel.IComponent'/> to the
/// <see cref='System.ComponentModel.IContainer'/> at the end of the list.
/// </summary>
void Add(IComponent component);
// Adds a component to the container.
/// <summary>
/// Adds the specified <see cref='System.ComponentModel.IComponent'/> to the
/// <see cref='System.ComponentModel.IContainer'/> at the end of the list,
/// and assigns a name to the component.
/// </summary>
void Add(IComponent component, string name);
/// <summary>
/// Gets all the components in the <see cref='System.ComponentModel.IContainer'/>.
/// </summary>
ComponentCollection Components { get; }
/// <summary>
/// Removes a component from the <see cref='System.ComponentModel.IContainer'/>.
/// </summary>
void Remove(IComponent component);
}
}
| 39.113636 | 90 | 0.647298 | [
"MIT"
] | ARhj/corefx | src/System.ComponentModel.Primitives/src/System/ComponentModel/IContainer.cs | 1,721 | C# |
using ENet;
using MHLab.AspNetCore.Enet.Handlers;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Host = ENet.Host;
namespace MHLab.AspNetCore.Enet.Servers
{
public sealed class EnetServer : IHostedService
{
private readonly EnetConfiguration _configuration;
private readonly ILogger<EnetServer> _logger;
private readonly IConnectionHandlerContainer _connectionHandlers;
private readonly IDisconnectionHandlerContainer _disconnectionHandlers;
private readonly ITimeoutHandlerContainer _timeoutHandlers;
private readonly IPacketHandlerContainer _packetHandlers;
private volatile bool _shouldRun;
private Task _serverTask;
public EnetServer(
EnetConfiguration configuration,
IServiceProvider serviceProvider,
ILogger<EnetServer> logger,
IConnectionHandlerContainer connectionHandlers,
IDisconnectionHandlerContainer disconnectionHandlers,
ITimeoutHandlerContainer timeoutHandlers,
IPacketHandlerContainer packetHandlers
)
{
_configuration = configuration;
_logger = logger;
_connectionHandlers = connectionHandlers;
_disconnectionHandlers = disconnectionHandlers;
_timeoutHandlers = timeoutHandlers;
_packetHandlers = packetHandlers;
_configuration.BindConnectionHandlers(_connectionHandlers, serviceProvider);
_configuration.BindDisconnectionHandlers(_disconnectionHandlers, serviceProvider);
_configuration.BindTimeoutHandlers(_timeoutHandlers, serviceProvider);
_configuration.BindPacketHandlers(_packetHandlers, serviceProvider);
}
public Task StartAsync(CancellationToken cancellationToken)
{
cancellationToken.Register(() =>
{
_shouldRun = false;
_logger.LogInformation("Enet server is shutting down...");
});
_serverTask = Task.Factory.StartNew(() =>
{
Library.Initialize();
_shouldRun = true;
using (Host server = new Host())
{
Address address = new Address
{
Port = _configuration.Port
};
int pollingTimeout = _configuration.PollingTimeout;
server.Create(address, (int)_configuration.PeerLimit);
_logger.LogInformation($"Enet server listening at 0.0.0.0:{address.Port}");
Event netEvent;
while (_shouldRun)
{
bool polled = false;
while (!polled)
{
if (server.CheckEvents(out netEvent) <= 0)
{
if (server.Service(pollingTimeout, out netEvent) <= 0)
break;
polled = true;
}
switch (netEvent.Type)
{
case EventType.None:
break;
case EventType.Connect:
_connectionHandlers.OnConnectedPeer(netEvent.Peer);
break;
case EventType.Disconnect:
_disconnectionHandlers.OnDisconnectedPeer(netEvent.Peer);
break;
case EventType.Timeout:
_timeoutHandlers.OnTimeoutPeer(netEvent.Peer);
break;
case EventType.Receive:
_packetHandlers.OnPacketReceived(netEvent.Peer, netEvent.ChannelID, netEvent.Packet);
break;
}
}
}
server.Flush();
}
_logger.LogInformation("Enet server closed.");
Library.Deinitialize();
}, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
return _serverTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
| 34.911111 | 121 | 0.527689 | [
"MIT"
] | manhunterita/MHLab.AspNetCore.Enet | MHLab.AspNetCore.Enet/Servers/EnetServer.cs | 4,715 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
// ReSharper disable once CheckNamespace
public static class EnumHelper
{
#region Static Methods
public static Dictionary<int, string> GetDictionary<T>() where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T is not an Enum type!");
}
return Enum.GetValues(typeof(T))
.Cast<object>()
.ToDictionary(x => (int) x, x => x.ToString());
}
public static Dictionary<int, string> GetDictionary<T>(params T[] ignoreValues) where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T is not an Enum type!");
}
var ignore = ignoreValues.Cast<object>();
return Enum.GetValues(typeof(T))
.Cast<object>()
.Where(x => !ignore.Contains(x))
.ToDictionary(x => (int) x, x => x.ToString());
}
public static Dictionary<int, string> GetDictionaryInDescription<T>() where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T is not an Enum type!");
}
return Enum.GetValues(typeof(T))
.Cast<object>()
.ToDictionary(x => (int) x, x => ((Enum) x).GetDescription());
}
public static Dictionary<int, string> GetDictionaryInDescription<T>(params T[] ignoreValues) where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T is not an Enum type!");
}
var ignore = ignoreValues.Cast<object>();
return Enum.GetValues(typeof(T))
.Cast<object>()
.Where(x => !ignore.Contains(x))
.ToDictionary(x => (int) x, x => ((Enum) x).GetDescription());
}
public static Dictionary<int, string> GetDictionaryInDisplayText<T>() where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T is not an Enum type!");
}
return Enum.GetValues(typeof(T))
.Cast<object>()
.ToDictionary(x => (int) x, x => ((Enum) x).GetDisplayText());
}
public static Dictionary<int, string> GetDictionaryInDisplayText<T>(params T[] ignoreValues) where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T is not an Enum type!");
}
var ignore = ignoreValues.Cast<object>();
return Enum.GetValues(typeof(T))
.Cast<object>()
.Where(x => !ignore.Contains(x))
.ToDictionary(x => (int) x, x => ((Enum) x).GetDisplayText());
}
#endregion
}
| 28.935484 | 113 | 0.559272 | [
"MIT"
] | modular-net/Modular.NET | src/Modular.NET.Core/Helpers/EnumHelper.cs | 2,693 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Gamekit3D.GameCommands
{
public static class CommandGizmos
{
static GUIStyle sceneNote;
static CommandGizmos()
{
sceneNote = new GUIStyle("box");
sceneNote.fontStyle = FontStyle.Bold;
sceneNote.normal.textColor = Color.white;
sceneNote.margin = sceneNote.overflow = sceneNote.padding = new RectOffset(3, 3, 3, 3);
sceneNote.richText = true;
sceneNote.alignment = TextAnchor.MiddleLeft;
}
static void DrawNote(Vector3 position, string text, string warning = "", float distance = 10)
{
if (!string.IsNullOrEmpty(warning))
text = text + "<color=red>" + warning + "</color>";
if ((Camera.current.transform.position - position).magnitude <= distance)
Handles.Label(position, text, sceneNote);
}
[DrawGizmo(GizmoType.InSelectionHierarchy | GizmoType.NotInSelectionHierarchy, typeof(Teleporter))]
static void DrawTeleporterGizmos(Teleporter teleporter, GizmoType gizmoType)
{
if (teleporter.destinationTransform)
{
DrawNote(teleporter.transform.position, "Teleport Enter");
Handles.color = Color.yellow * 0.5f;
Handles.DrawDottedLine(teleporter.transform.position, teleporter.destinationTransform.position, 5);
DrawNote(teleporter.destinationTransform.position, "Teleport Exit");
}
else
{
DrawNote(teleporter.transform.position, "Teleport Enter", "(No Destination!)");
}
}
}
}
| 37.510638 | 115 | 0.614861 | [
"Apache-2.0"
] | Scottdyt/3DGamekitWeb | Frontend/Assets/3DGamekit/Packages/Interactive/Editor/TeleporterGizmo.cs | 1,765 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace ServiceStack
{
//Interfaces and DTO's used in AutoQuery
public interface IQuery
{
int? Skip { get; set; }
int? Take { get; set; }
string OrderBy { get; set; }
string OrderByDesc { get; set; }
}
public interface IQuery<From> : IQuery { }
public interface IQuery<From,Into> : IQuery { }
public interface IJoin { }
public interface IJoin<Source, Join1> : IJoin { }
public interface IJoin<Source, Join1, Join2> : IJoin { }
public interface IJoin<Source, Join1, Join2, Join3> : IJoin { }
public interface IJoin<Source, Join1, Join2, Join3, Join4> : IJoin { }
public interface ILeftJoin<Source, Join1> : IJoin { }
public interface ILeftJoin<Source, Join1, Join2> : IJoin { }
public interface ILeftJoin<Source, Join1, Join2, Join3> : IJoin { }
public interface ILeftJoin<Source, Join1, Join2, Join3, Join4> : IJoin { }
public enum QueryTerm
{
Default = 0,
And = 1,
Or = 2,
}
public enum ValueStyle
{
Single = 0,
Multiple = 1,
List = 2,
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class QueryAttribute : AttributeBase
{
public QueryAttribute() {}
public QueryAttribute(QueryTerm defaultTerm)
{
DefaultTerm = defaultTerm;
}
public QueryTerm DefaultTerm { get; set; }
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class QueryFieldAttribute : AttributeBase
{
public QueryTerm Term { get; set; }
public string Operand { get; set; }
public string Template { get; set; }
public string Field { get; set; }
public string ValueFormat { get; set; }
public ValueStyle ValueStyle { get; set; }
public int ValueArity { get; set; }
}
public abstract class QueryBase : IQuery
{
[DataMember(Order = 1)]
public virtual int? Skip { get; set; }
[DataMember(Order = 2)]
public virtual int? Take { get; set; }
[DataMember(Order = 3)]
public virtual string OrderBy { get; set; }
[DataMember(Order = 4)]
public virtual string OrderByDesc { get; set; }
}
public abstract class QueryBase<T> : QueryBase, IQuery<T>, IReturn<QueryResponse<T>> { }
public abstract class QueryBase<From, Into> : QueryBase, IQuery<From, Into>, IReturn<QueryResponse<Into>> { }
[DataContract]
public class QueryResponse<T> : IHasResponseStatus, IMeta
{
[DataMember(Order = 1)]
public virtual int Offset { get; set; }
[DataMember(Order = 2)]
public virtual int Total { get; set; }
[DataMember(Order = 3)]
public virtual List<T> Results { get; set; }
[DataMember(Order = 4)]
public virtual Dictionary<string, string> Meta { get; set; }
[DataMember(Order = 5)]
public virtual ResponseStatus ResponseStatus { get; set; }
}
} | 31.066667 | 114 | 0.594114 | [
"Apache-2.0"
] | Chris-Kim/ServiceStack | src/ServiceStack.Interfaces/IQuery.cs | 3,160 | C# |
using System.Collections.Generic;
namespace OneScriptDocumenter.Model
{
abstract class AbstractSyntaxItem
{
public MultilangString Caption { get; set; }
public MultilangString Description { get; set; }
public IList<AbstractSyntaxItem> Children { get; protected set; }
}
}
| 23.923077 | 73 | 0.697749 | [
"MIT"
] | EvilBeaver/OneScriptDocumenter | OneScriptDocumenter/Model/AbstractSyntaxItem.cs | 313 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RazorCompile
{
using System.Text.RegularExpressions;
/// <summary>
/// An incredibly shoddy implementation of the Razor Web View compiler.
/// There are certain C# syntax combinations which are currently unsupported. If in doubt, use a @ to escape.
/// </summary>
public class RazorTemplate
{
private List<string> _renderedLines = new List<string>();
private List<string> _usingDeclarations = new List<string>();
private List<VariableDeclaration> _variableDeclarations = new List<VariableDeclaration>();
private readonly Regex XML_PARSER = new Regex("(<!.+?>)|(<[^ ]+?)((?: +.+?=\".+?\")* *\\/?>)([^<]*)");
private readonly Regex LEADIN_PARSER = new Regex("^[^<]+");
private string _viewName;
private string _namespace = "RazorViews";
private static readonly Regex SUBST_REGEX = new Regex("@(?:\\((.+?)\\)|([a-zA-Z0-9\\.()\\{\\}]+))");
public RazorTemplate(string viewName)
{
_viewName = viewName;
_renderedLines.Add("//// DO NOT MODIFY!!! THIS FILE IS AUTOGENED AND WILL BE OVERWRITTEN!!! ////");
_renderedLines.Add(string.Empty);
_renderedLines.Add("using System;");
_renderedLines.Add("using System.Text;");
_renderedLines.Add("using System.Collections;");
_renderedLines.Add("using System.Collections.Generic;");
}
public IList<string> Render(IList<string> inputLines)
{
try
{
int endOfHeaders = this.ReadHeaders(inputLines);
StringBuilder xmlBuilder = new StringBuilder();
for (int line = endOfHeaders; line < inputLines.Count; line++)
{
xmlBuilder.AppendLine(inputLines[line]);
}
// Write @using declarations
_renderedLines.AddRange(_usingDeclarations);
// Write the leadin
_renderedLines.Add("namespace " + _namespace);
_renderedLines.Add("{");
_renderedLines.Add(" public class " + _viewName);
_renderedLines.Add(" {");
// Write @var declarations
foreach (VariableDeclaration var in _variableDeclarations)
{
_renderedLines.Add(" public " + var.Type + " " + var.Name + " {get; set;}");
}
// Write initializers in the constructor
_renderedLines.Add(" public " + _viewName + "()");
_renderedLines.Add(" {");
foreach (VariableDeclaration var in _variableDeclarations)
{
if (!string.IsNullOrEmpty(var.Initializer))
{
_renderedLines.Add(" " + var.Name + " = " + var.Initializer + ";");
}
}
_renderedLines.Add(" }");
_renderedLines.Add(" public string Render()");
_renderedLines.Add(" {");
_renderedLines.Add(" StringBuilder returnVal = new StringBuilder();");
// Process the HTML body
ReadHtml(xmlBuilder.ToString(), endOfHeaders);
// Write the leadout
_renderedLines.Add(" return returnVal.ToString();");
_renderedLines.Add(" }");
_renderedLines.Add(" }");
_renderedLines.Add("}");
}
catch (Exception e)
{
_renderedLines.Add(e.GetType().ToString());
_renderedLines.Add(e.Message);
_renderedLines.Add(e.Source);
_renderedLines.Add(e.StackTrace);
}
return _renderedLines;
}
private int ReadHeaders(IList<string> inputLines)
{
int curLine = -1;
foreach (string line in inputLines)
{
curLine++;
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
if (line.StartsWith("@"))
{
// It's one of the header-only values like @model or @using
string namespaceDec = TryExtractNamespace(line);
if (namespaceDec != null)
{
_namespace = namespaceDec;
continue;
}
string usingDec = TryExtractUsing(line);
if (usingDec != null)
{
_usingDeclarations.Add("using " + usingDec + ";");
continue;
}
VariableDeclaration varDec = TryExtractVar(line);
if (varDec != null)
{
_variableDeclarations.Add(varDec);
continue;
}
break;
}
break;
}
return curLine;
}
private void ReadHtml(string htmlString, int lineNumberOffset)
{
// Read the lead-in, if any
Match leadInMatch = LEADIN_PARSER.Match(htmlString);
if (leadInMatch.Success)
{
IList<string> splitLines = SplitLines(leadInMatch.Value);
foreach (string line in splitLines)
{
string transformedLine = this.TransformLine(line);
if (transformedLine != null)
{
_renderedLines.Add(transformedLine);
}
}
}
foreach (Match parserMatch in XML_PARSER.Matches(htmlString))
{
HandleRegexMatch(parserMatch);
}
}
private void HandleRegexMatch(Match parserMatch)
{
// 1 is DOCTYPE tag
// 2 is the tag name
// 3 is the tag attributes with terminator
// 4 is the body content
if (parserMatch.Groups[1].Success)
{
// It's a !DOCTYPE tag. Pass it through
_renderedLines.Add(" returnVal.AppendLine(\"" + EscapeCSharpString(parserMatch.Groups[1].Value) + "\");");
}
else
{
IList<string> splitLines = SplitLines(parserMatch.Groups[4].Value);
bool isJavascriptBlock = parserMatch.Groups[2].Value.Equals("<script", StringComparison.OrdinalIgnoreCase);
// Echo the current tag
_renderedLines.Add(" returnVal.AppendLine(\"" + EscapeCSharpString(parserMatch.Groups[2].Value) + ApplySubstitutionInHtml(parserMatch.Groups[3].Value) + "\");");
// And then handle whataver comes after it (its body text content, if any)
foreach (string line in splitLines)
{
string transformedLine = this.TransformLine(line, isJavascriptBlock);
if (transformedLine != null)
{
_renderedLines.Add(transformedLine);
}
}
}
}
private string TransformLine(string input, bool isJavascriptBlock = false)
{
if (string.IsNullOrWhiteSpace(input))
return null;
if (!isJavascriptBlock && IsCodeLine(input))
{
if (IsPureCode(input))
{
// It's a code line like "@foreach (var x in Model)"
return " " + ApplySubstitutionInCode(input.Trim());
}
else
{
// Usually this means it's an HTML line that begins with code, like "@Model.Value<br/>", intended to be echoed
return " returnVal.AppendLine(\"" + ApplySubstitutionInHtml(input.Trim()) + "\");";
}
}
else if (isJavascriptBlock && IsPureCodeInsideJavascript(input))
{
// It's a code line inside of a javascript block (be careful!)
return " " + ApplySubstitutionInCode(input.Trim());
}
else
{
// It's a plain HTML (not Javascript) line, possibly containing "@" tokens that need substitution
return " returnVal.AppendLine(\"" + ApplySubstitutionInHtml(input) + "\");";
}
}
private static IList<string> SplitLines(string input)
{
List<string> returnVal = new List<string>();
Regex splitter = new Regex("(.+?)(\\r|\\n|$)+");
foreach (Match m in splitter.Matches(input))
{
returnVal.Add(m.Groups[1].Value);
}
return returnVal;
}
private static bool IsCodeLine(string inputLine)
{
string trimmedLine = inputLine.TrimStart(' ', '\t');
return trimmedLine.StartsWith("@") ||
trimmedLine.StartsWith("{") ||
trimmedLine.StartsWith("}") ||
trimmedLine.EndsWith(";");
}
/// <summary>
/// Indicates that no string data can possibly be emitted by the current line
/// </summary>
/// <param name="inputLine"></param>
/// <returns></returns>
private static bool IsPureCode(string inputLine)
{
string trimmedLine = inputLine.ToLowerInvariant();
if (trimmedLine.Contains("//"))
{
trimmedLine = trimmedLine.Substring(0, trimmedLine.IndexOf("//"));
}
trimmedLine = trimmedLine.Trim(' ', '\t');
return trimmedLine.StartsWith("@foreach") ||
trimmedLine.StartsWith("@for") ||
trimmedLine.StartsWith("@while") ||
trimmedLine.StartsWith("@if") ||
trimmedLine.StartsWith("@else") ||
trimmedLine.StartsWith("@{") ||
trimmedLine.StartsWith("{") ||
trimmedLine.StartsWith("}") ||
trimmedLine.EndsWith(";");
}
private static bool IsPureCodeInsideJavascript(string inputLine)
{
string trimmedLine = inputLine.ToLowerInvariant();
if (trimmedLine.Contains("//"))
{
trimmedLine = trimmedLine.Substring(0, trimmedLine.IndexOf("//"));
}
trimmedLine = trimmedLine.Trim(' ', '\t');
return trimmedLine.StartsWith("@foreach") ||
trimmedLine.StartsWith("@for") ||
trimmedLine.StartsWith("@while") ||
trimmedLine.StartsWith("@if") ||
trimmedLine.StartsWith("@else") ||
trimmedLine.StartsWith("@{") ||
trimmedLine.StartsWith("@}");
}
private static VariableDeclaration TryExtractVar(string input)
{
if (input.Trim().ToLowerInvariant().StartsWith("@var"))
{
string line = input.Substring(4).Trim().TrimEnd(';');
VariableDeclaration returnVal = new VariableDeclaration();
int typeIndex = line.IndexOf(' ');
int initializerIndex = line.IndexOf('=');
if (typeIndex < 0)
{
throw new FormatException("The variable declaration has no type: " + line);
}
returnVal.Type = line.Substring(0, typeIndex);
if (initializerIndex > typeIndex)
{
// Variable contains an initializer; save it for later
returnVal.Name = line.Substring(typeIndex + 1, initializerIndex - typeIndex - 1).Trim();
returnVal.Initializer = line.Substring(initializerIndex + 1).Trim();
}
else
{
returnVal.Name = line.Substring(typeIndex + 1).Trim();
returnVal.Initializer = string.Empty;
}
return returnVal;
}
return null;
}
private static string TryExtractUsing(string input)
{
if (input.Trim().ToLowerInvariant().StartsWith("@using"))
{
return input.Substring(6).Trim();
}
return null;
}
private static string TryExtractNamespace(string input)
{
if (input.Trim().ToLowerInvariant().StartsWith("@namespace"))
{
return input.Substring(10).Trim();
}
return null;
}
private static string ApplySubstitutionInCode(string inputLine)
{
inputLine = EscapeCSharpString(inputLine);
foreach (Match m in SUBST_REGEX.Matches(inputLine))
{
if (m.Groups[1].Success)
{
inputLine = inputLine.Replace(m.Value, m.Groups[1].Value);
}
else
{
inputLine = inputLine.Replace(m.Value, m.Groups[2].Value);
}
}
return inputLine;
}
private static string ApplySubstitutionInHtml(string inputLine)
{
//inputLine = inputLine.Replace("\"", "\\\"");
inputLine = EscapeCSharpString(inputLine);
foreach (Match m in SUBST_REGEX.Matches(inputLine))
{
if (m.Groups[1].Success)
{
inputLine = inputLine.Replace(m.Value, "\" + " + m.Groups[1].Value + " + \"");
}
else
{
inputLine = inputLine.Replace(m.Value, "\" + " + m.Groups[2].Value + " + \"");
}
}
return inputLine;
}
private static string EscapeCSharpString(string input)
{
return input.Replace("\\", "\\\\")
.Replace("\'", "\\\'")
.Replace("\"", "\\\"")
.Replace("\r", "\\\r")
.Replace("\n", "\\\n");
}
private class VariableDeclaration
{
public string Type;
public string Name;
public string Initializer;
}
}
}
| 38.708333 | 188 | 0.481364 | [
"BSD-2-Clause"
] | lostromb/pokemon_world | RazorCompile/RazorTemplate.cs | 14,866 | C# |
using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Serialization.Tests.ExampleModel
{
[Serializable]
[JsonObject]
public class ClassC : ISerializable
{
public ClassC() { }
public ClassC(string className, DateTime dateTimeValue, ClassA a)
{
ClassName = className;
DateTimeValue = dateTimeValue;
A = a;
}
public ClassC(SerializationInfo info, StreamingContext context)
{
ClassName = info.GetString("ClassName");
DateTimeValue = info.GetDateTime("DateTimeValue");
A = (ClassA) info.GetValue("refA", typeof(ClassA));
}
public ClassA A { get; set; }
public string ClassName { get; set; }
public DateTime DateTimeValue { get; set; }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ClassName", ClassName);
info.AddValue("DateTimeValue", DateTimeValue);
info.AddValue("refA", A);
}
}
} | 28.736842 | 83 | 0.60348 | [
"Apache-2.0"
] | Nawrok/tp | Task_2/Serialization.Tests/ExampleModel/ClassC.cs | 1,094 | C# |
using System.Collections.Generic;
namespace CTournament.Models.CReplay.Players
{
public class PlayersDataInfo
{
public int GameId { get; set; }
public long MetaId { get; set; }
public int Level { get; set; }
public bool HasPremium { get; set; }
public int Role { get; set; }
public ConsumablesInfo SelectedConsumables { get; set; }
public bool IsCurrentUser { get; set; }
public string Userbar { get; set; }
public int TeamNumber { get; set; }
public string Nickname { get; set; }
public int Kills { get; set; }
public int PlayerKills { get; set; }
public int BotKills { get; set; }
public int Deaths { get; set; }
public int Assists { get; set; }
public int HitPointHealed { get; set; }
public int DamageDealt { get; set; }
public int DamageRecieved { get; set; }
public int AllKills { get => Kills + PlayerKills + BotKills; }
public int SortedRole { get => GetKeyRole(Role); }
private static int GetKeyRole(int idRole)
{
if (idRole == 1)
idRole = 4;
else if (idRole == 2)
idRole = 3;
else if (idRole == 3)
idRole = 2;
return idRole;
}
}
}
| 31.139535 | 70 | 0.547423 | [
"MIT"
] | djserega/CTournament | src/CTournament/CTournament/Models/CReplay/Players/PlayersDataInfo.cs | 1,341 | C# |
using System;
namespace Shriek.ServiceProxy.Socket
{
/// <summary>
/// 定义服务器插件行为
/// </summary>
public interface IPlug
{
/// <summary>
/// 会话连接成功后触发
/// 如果关闭了会话,将停止传递给下个插件的OnConnected
/// </summary>
/// <param name="sender">发生者</param>
/// <param name="context">上下文</param>
void OnConnected(object sender, IContenxt context);
/// <summary>
/// SSL验证完成后触发
/// 如果起用了SSL,验证通过后才可以往客户端发送数据
/// 如果关闭了会话,将停止传递给下个插件的OnAuthenticated
/// </summary>
/// <param name="sender">发生者</param>
/// <param name="context">上下文</param>
void OnAuthenticated(object sender, IContenxt context);
/// <summary>
/// 收到请求后触发
/// 如果关闭了会话或清空了数据,将停止传递给下个插件的OnRequested
/// </summary>
/// <param name="sender">发生者</param>
/// <param name="context">上下文</param>
void OnRequested(object sender, IContenxt context);
/// <summary>
/// 会话断开后触发
/// </summary>
/// <param name="sender">发生者</param>
/// <param name="context">上下文</param>
void OnDisconnected(object sender, IContenxt context);
/// <summary>
/// 服务异常后触发
/// </summary>
/// <param name="sender">发生者</param>
/// <param name="exception">异常</param>
void OnException(object sender, Exception exception);
}
} | 29.102041 | 63 | 0.545582 | [
"MIT"
] | 1051324354/shriek-fx | src/Shriek.ServiceProxy.Socket/IPlug.cs | 1,748 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.