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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace apiwithpomelo
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.740741 | 70 | 0.646043 | [
"MIT"
] | peedroca/CSharpAdvanced21 | src/generics/apiwithpomelo/Program.cs | 695 | C# |
using System;
using System.Threading.Tasks;
using R5T.T0064;
namespace R5T.D0001.Default
{
[ServiceImplementationMarker]
public class OffsetNowUtcProvider : INowUtcProvider, IServiceImplementation
{
#region Static
public static OffsetNowUtcProvider NewFromOffset(TimeSpan offset)
{
var offsetNowUtcProvider = new OffsetNowUtcProvider(offset);
return offsetNowUtcProvider;
}
public static OffsetNowUtcProvider New(TimeSpan offset)
{
var offsetNowUtcProvider = OffsetNowUtcProvider.NewFromOffset(offset);
return offsetNowUtcProvider;
}
public static OffsetNowUtcProvider NewFromDesiredNowUtc(DateTime desiredNowUtc)
{
var offset = DateTime.UtcNow - desiredNowUtc;
var offsetNowUtcProvider = OffsetNowUtcProvider.NewFromOffset(offset);
return offsetNowUtcProvider;
}
public static OffsetNowUtcProvider NewFromDesiredNowLocal(DateTime desiredNowLocal)
{
var offset = DateTime.Now - desiredNowLocal;
var offsetNowUtcProvider = OffsetNowUtcProvider.NewFromOffset(offset);
return offsetNowUtcProvider;
}
#endregion
private TimeSpan Offset { get; }
public OffsetNowUtcProvider(
[NotServiceComponent] TimeSpan offset)
{
this.Offset = offset;
}
public Task<DateTime> GetNowUtc()
{
var nowUtc = DateTime.UtcNow;
var offsetNowUtc = nowUtc + this.Offset;
return Task.FromResult(offsetNowUtc);
}
}
}
| 27.428571 | 92 | 0.62037 | [
"MIT"
] | MinexAutomation/R5T.D0001 | source/R5T.D0001.Default/Code/Services/Implementations/OffsetNowUtcProvider.cs | 1,728 | C# |
using log4net;
using TimeLog.TransactionalAPI.SDK;
using TimeLog.TransactionalAPI.SDK.RawHelper;
namespace TimeLog.API.ConsoleApp;
/// <summary>
/// Template class for consuming the transactional API
/// </summary>
public class ManipulateTasks
{
private static readonly ILog Logger = LogManager.GetLogger(typeof(ManipulateTasks));
public static void Consume()
{
// For getting the raw XML
SecurityHandler.Instance.CollectRawRequestResponse = false;
ProjectManagementHandler.Instance.CollectRawRequestResponse = false;
if (SecurityHandler.Instance.TryAuthenticate(out IEnumerable<string> messages))
{
RawMessageHelper.Instance.SaveRecentRequestResponsePair("c:\\temp\\TryAuthenticate.txt");
if (Logger.IsInfoEnabled)
{
Logger.Info("Sucessfully authenticated on transactional API");
}
var tasks = ProjectManagementHandler.Instance.ProjectManagementClient.GetTasksByProjectId(
Guid.Parse("F88D516A-215F-4E5C-A7CB-FD79E64996F5"), ProjectManagementHandler.Instance.Token);
foreach (var task in tasks.Return)
{
Logger.Debug("Task.Details.WBS: " + task.Details.WBS);
Logger.Debug("Task.FullName: " + task.FullName);
Logger.Debug("Task.ProjectSubContractID: " + task.ProjectSubContractID);
// OBSOLETE
//_task.ProjectSubContractID = 22;
//var _updateTaskRaw = ProjectManagementHandler.Instance.ProjectManagementClient.UpdateTask(_task, _task.Details.ProjectHeader.ID, ProjectManagementHandler.Instance.Token);
//foreach (var _apiMessage in _updateTaskRaw.Messages)
//{
// Logger.Debug("UpdateTask message: " + _apiMessage.Message);
//}
var changeTaskContractRaw =
ProjectManagementHandler.Instance.ProjectManagementClient.ChangeTaskContract(task.ID, 22,
ProjectManagementHandler.Instance.Token);
foreach (var apiMessage in changeTaskContractRaw.Messages)
{
Logger.Debug("ChangeTaskContract message: " + apiMessage.Message);
}
Logger.Debug("---");
}
}
else
{
if (Logger.IsWarnEnabled)
{
Logger.Warn("Failed to authenticate to transactional API");
Logger.Warn(string.Join(",", messages));
}
}
}
} | 38.701493 | 188 | 0.615503 | [
"MIT"
] | TimeLog/TransactionalApiSdk | TimeLog.API.ConsoleApp/ManipulateTasks.cs | 2,595 | C# |
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved.
using UnityEngine;
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory("iTween")]
[Tooltip("Changes a GameObject's position over time to a supplied destination.")]
public class iTweenMoveTo : iTweenFsmAction
{
[RequiredField]
public FsmOwnerDefault gameObject;
[Tooltip("iTween ID. If set you can use iTween Stop action to stop it by its id.")]
public FsmString id;
[Tooltip("Move To a transform position.")]
public FsmGameObject transformPosition;
[Tooltip("Position the GameObject will animate to. If Transform Position is defined this is used as a local offset.")]
public FsmVector3 vectorPosition;
[Tooltip("The time in seconds the animation will take to complete.")]
public FsmFloat time;
[Tooltip("The time in seconds the animation will wait before beginning.")]
public FsmFloat delay;
[Tooltip("Can be used instead of time to allow animation based on speed. When you define speed the time variable is ignored.")]
public FsmFloat speed;
[Tooltip("Whether to animate in local or world space.")]
public Space space = Space.World;
[Tooltip("The shape of the easing curve applied to the animation.")]
public iTween.EaseType easeType = iTween.EaseType.linear;
[Tooltip("The type of loop to apply once the animation has completed.")]
public iTween.LoopType loopType = iTween.LoopType.none;
[ActionSection("LookAt")]
[Tooltip("Whether or not the GameObject will orient to its direction of travel. False by default.")]
public FsmBool orientToPath;
[Tooltip("A target object the GameObject will look at.")]
public FsmGameObject lookAtObject;
[Tooltip("A target position the GameObject will look at.")]
public FsmVector3 lookAtVector;
[Tooltip("The time in seconds the object will take to look at either the Look Target or Orient To Path. 0 by default")]
public FsmFloat lookTime;
[Tooltip("Restricts rotation to the supplied axis only.")]
public iTweenFsmAction.AxisRestriction axis = iTweenFsmAction.AxisRestriction.none;
[ActionSection("Path")]
[Tooltip("Whether to automatically generate a curve from the GameObject's current position to the beginning of the path. True by default.")]
public FsmBool moveToPath;
[Tooltip("How much of a percentage (from 0 to 1) to look ahead on a path to influence how strict Orient To Path is and how much the object will anticipate each curve.")]
public FsmFloat lookAhead;
[CompoundArray("Path Nodes", "Transform", "Vector")]
[Tooltip("A list of objects to draw a Catmull-Rom spline through for a curved animation path.")]
public FsmGameObject[] transforms;
[Tooltip("A list of positions to draw a Catmull-Rom through for a curved animation path. If Transform is defined, this value is added as a local offset.")]
public FsmVector3[] vectors;
[Tooltip("Reverse the path so object moves from End to Start node.")]
public FsmBool reverse;
private Vector3[] tempVct3;
public override void OnDrawGizmos(){
if(transforms.Length >= 2) {
tempVct3 = new Vector3[transforms.Length];
for(int i = 0;i<transforms.Length;i++){
if(transforms[i].IsNone) tempVct3[i] = vectors[i].IsNone ? Vector3.zero : vectors[i].Value;
else {
if(transforms[i].Value == null) tempVct3[i] = vectors[i].IsNone ? Vector3.zero : vectors[i].Value;
else tempVct3[i] = transforms[i].Value.transform.position + (vectors[i].IsNone ? Vector3.zero : vectors[i].Value);
}
}
iTween.DrawPathGizmos(tempVct3, Color.yellow);
}
}
public override void Reset()
{
base.Reset();
id = new FsmString { UseVariable = true };
transformPosition = new FsmGameObject { UseVariable = true };
vectorPosition = new FsmVector3 { UseVariable = true };
time = 1f;
delay = 0f; //new FsmFloat { UseVariable = true };
loopType = iTween.LoopType.none;
speed = new FsmFloat { UseVariable = true };
space = Space.World;
orientToPath = new FsmBool { Value = true };
lookAtObject = new FsmGameObject { UseVariable = true};
lookAtVector = new FsmVector3 { UseVariable = true };
lookTime = new FsmFloat { UseVariable = true };
moveToPath = true; // new FsmBool { UseVariable = true };
lookAhead = new FsmFloat { UseVariable = true };
transforms = new FsmGameObject[0];
vectors = new FsmVector3[0];
tempVct3 = new Vector3[0];
axis = iTweenFsmAction.AxisRestriction.none;
reverse = false; //new FsmBool { UseVariable = true };
}
public override void OnEnter()
{
base.OnEnteriTween(gameObject);
if(loopType != iTween.LoopType.none) base.IsLoop(true);
DoiTween();
}
public override void OnExit(){
base.OnExitiTween(gameObject);
}
void DoiTween()
{
GameObject go = Fsm.GetOwnerDefaultTarget(gameObject);
if (go == null) return;
Vector3 pos = vectorPosition.IsNone ? Vector3.zero : vectorPosition.Value;
if(!transformPosition.IsNone)
if(transformPosition.Value)
pos = (space == Space.World || go.transform.parent == null) ? transformPosition.Value.transform.position + pos : go.transform.parent.InverseTransformPoint(transformPosition.Value.transform.position) + pos;
System.Collections.Hashtable hash = new System.Collections.Hashtable();
hash.Add("position", pos);
hash.Add(speed.IsNone ? "time" : "speed", speed.IsNone ? time.IsNone ? 1f : time.Value : speed.Value);
hash.Add("delay", delay.IsNone ? 0f : delay.Value);
hash.Add("easetype", easeType);
hash.Add("looptype", loopType);
hash.Add("oncomplete", "iTweenOnComplete");
hash.Add("oncompleteparams", itweenID);
hash.Add("onstart", "iTweenOnStart");
hash.Add("onstartparams", itweenID);
hash.Add("ignoretimescale", realTime.IsNone ? false : realTime.Value);
hash.Add("name", id.IsNone ? "" : id.Value);
hash.Add("islocal", space == Space.Self );
hash.Add("axis", axis == iTweenFsmAction.AxisRestriction.none ? "" : System.Enum.GetName(typeof(iTweenFsmAction.AxisRestriction), axis));
if(!orientToPath.IsNone) {
hash.Add("orienttopath", orientToPath.Value);
}
if(!lookAtObject.IsNone) {
hash.Add("looktarget", lookAtVector.IsNone ? lookAtObject.Value.transform.position : lookAtObject.Value.transform.position + lookAtVector.Value);
} else {
if(!lookAtVector.IsNone) {
hash.Add("looktarget", lookAtVector.Value);
}
}
if(!lookAtObject.IsNone || !lookAtVector.IsNone){
hash.Add("looktime", lookTime.IsNone ? 0f : lookTime.Value);
}
if(transforms.Length >= 2) {
tempVct3 = new Vector3[transforms.Length];
if(reverse.IsNone ? false : reverse.Value){
for(int i = 0;i<transforms.Length;i++){
if(transforms[i].IsNone) tempVct3[tempVct3.Length - 1 - i] = vectors[i].IsNone ? Vector3.zero : vectors[i].Value;
else {
if(transforms[i].Value == null) tempVct3[tempVct3.Length - 1 - i] = vectors[i].IsNone ? Vector3.zero : vectors[i].Value;
else tempVct3[tempVct3.Length - 1 - i] = (space == Space.World ? transforms[i].Value.transform.position : transforms[i].Value.transform.localPosition) + (vectors[i].IsNone ? Vector3.zero : vectors[i].Value);
}
}
} else {
for(int i = 0;i<transforms.Length;i++){
if(transforms[i].IsNone) tempVct3[i] = vectors[i].IsNone ? Vector3.zero : vectors[i].Value;
else {
if(transforms[i].Value == null) tempVct3[i] = vectors[i].IsNone ? Vector3.zero : vectors[i].Value;
else tempVct3[i] = (space == Space.World ? transforms[i].Value.transform.position : go.transform.parent.InverseTransformPoint( transforms[i].Value.transform.position) ) + (vectors[i].IsNone ? Vector3.zero : vectors[i].Value);
}
}
}
hash.Add("path", tempVct3);
hash.Add("movetopath", moveToPath.IsNone ? true : moveToPath.Value);
hash.Add("lookahead", lookAhead.IsNone ? 1f : lookAhead.Value);
}
itweenType = "move";
iTween.MoveTo(go, hash);
}
}
} | 44.205556 | 232 | 0.69863 | [
"MIT"
] | andyrolfes/savr-escape | Assets/PlayMaker/Actions/iTween/iTweenMoveTo.cs | 7,957 | C# |
using UnityEngine;
using System.Collections;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine.Serialization;
namespace HexTiles
{
[SelectionBase]
public class HexTileMap : MonoBehaviour
{
[FormerlySerializedAs("hexWidth")]
public float tileDiameter = 1f;
[SerializeField]
private bool drawHexPositionGizmos = false;
[SerializeField]
private int chunkSize = 10;
public int ChunkSize
{
get
{
return chunkSize;
}
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException("value", "ChunkSize must be at least 1");
}
chunkSize = value;
}
}
/// <summary>
/// Whether or not to draw the position of each tile on top of the tile in the editor.
/// </summary>
public bool DrawHexPositionHandles
{
get
{
return drawHexPositionGizmos;
}
set
{
drawHexPositionGizmos = value;
}
}
[SerializeField]
private bool drawWireframeWhenSelected = true;
/// <summary>
/// Whether or not to highlight all hexes in wireframe when the tile map is selected.
/// </summary>
public bool DrawWireframeWhenSelected
{
get
{
return drawWireframeWhenSelected;
}
set
{
drawWireframeWhenSelected = value;
}
}
public enum HexCoordinateFormat
{
Axial,
OffsetOddQ,
WorldSpacePosition
}
/// <summary>
/// The format to use when drawing hex position handles.
/// </summary>
public HexCoordinateFormat HexPositionHandleFormat { get; set; }
/// <summary>
/// Collection of all hex tiles that are part of this map.
/// </summary>
private IEnumerable<HexTileData> Tiles
{
get
{
return Chunks
.SelectMany(chunk => chunk
.Tiles
.Select(tile => new HexTileData(tile, chunk.TileDiameter, chunk.Material))
);
}
}
private IList<HexChunk> chunks;
private IList<HexChunk> Chunks
{
get
{
if (chunks == null)
{
chunks = new List<HexChunk>();
foreach (var chunk in GetComponentsInChildren<HexChunk>())
{
chunks.Add(chunk);
}
}
return chunks;
}
}
/// <summary>
/// The current material used for painting tiles. Serialised here so that it will be saved for convenience
/// when we have to reload scripts.
/// </summary>
public Material CurrentMaterial
{
get
{
return currentMaterial;
}
set
{
currentMaterial = value;
}
}
[SerializeField]
private Material currentMaterial;
/// <summary>
/// Highlighted tile for editing
/// </summary>
public HexCoords SelectedTile
{
get
{
return selectedTile;
}
set
{
selectedTile = value;
}
}
private HexCoords selectedTile;
/// <summary>
/// Tile that the mouse is currently hovering over.
/// </summary>
public IEnumerable<HexPosition> HighlightedTiles { get; set; }
/// <summary>
/// The position where a new tile will appear when we paint
/// </summary>
public IEnumerable<HexPosition> NextTilePositions { get; set; }
void OnDrawGizmosSelected()
{
if (HighlightedTiles != null)
{
foreach (var tile in HighlightedTiles)
{
DrawHexGizmo(HexPositionToWorldPosition(tile), Color.white);
}
}
if (NextTilePositions != null)
{
foreach (var tile in NextTilePositions)
{
DrawHexGizmo(HexPositionToWorldPosition(tile), Color.cyan);
}
}
if (SelectedTile != null)
{
var tile = FindTileForCoords(SelectedTile);
if (tile != null)
{
DrawHexGizmo(HexPositionToWorldPosition(tile.Position), Color.green);
}
}
}
/// <summary>
/// Returns the tile at the specified coordinates, or null
/// if none exists.
/// </summary>
private HexTileData FindTileForCoords(HexCoords coords)
{
return Tiles
.Where(t => t.Position.Coordinates == coords)
.FirstOrDefault();
}
/// <summary>
/// Draws the outline of a hex at the specified position.
/// Can be grey or green depending on whether it's highlighted or not.
/// </summary>
private void DrawHexGizmo(Vector3 position, Color color)
{
Gizmos.color = color;
var verts = HexMetrics.GetHexVertices(tileDiameter)
.Select(v => (transform.localToWorldMatrix * v) + (Vector4)position)
.ToArray();
for (var i = 0; i < verts.Length; i++)
{
Gizmos.DrawLine(verts[i], verts[(i + 1) % verts.Length]);
}
}
/// <summary>
/// Take a vector in world space and return the closest hex coords.
/// </summary>
public HexCoords QuantizeVector3ToHexCoords(Vector3 vIn)
{
var vector = transform.InverseTransformPoint(vIn);
var q = vector.x * 2f/3f / (tileDiameter/2f);
var r = (-vector.x / 3f + Mathf.Sqrt(3f)/3f * vector.z) / (tileDiameter/2f);
return new HexCoords (Mathf.RoundToInt(q), Mathf.RoundToInt(r));
}
/// <summary>
/// Get the world space position of the specified hex coords.
/// This uses axial coordinates for the hexes.
/// </summary>
public Vector3 HexPositionToWorldPosition(HexPosition position)
{
return transform.TransformPoint(position.GetPositionVector(tileDiameter));
}
/// <summary>
/// Returns the nearest hex tile position in world space
/// to the specified position.
/// </summary>
public Vector3 QuantizePositionToHexGrid(Vector3 vIn)
{
return HexPositionToWorldPosition(new HexPosition(QuantizeVector3ToHexCoords(vIn), vIn.y));
}
/// <summary>
/// Re-position and re-generate geometry for all tiles.
/// Needed after changing global settings that affect all the tiles
/// such as the tile size.
///
/// Returns the chunks that were changed as a result of this operation.
/// </summary>
public IEnumerable<ModifiedTileInfo> RegenerateAllTiles()
{
var tileData = new List<HexTileData>();
foreach (var hexTile in Tiles)
{
tileData.Add(hexTile);
}
Chunks.Clear();
var childChunks = GetComponentsInChildren<HexChunk>();
foreach (var chunk in childChunks)
{
if (Application.isEditor)
{
DestroyImmediate(chunk.gameObject);
}
else
{
Destroy(chunk.gameObject);
}
}
var modifiedChunks = tileData
.Select(tile => CreateAndAddTile(tile.Position, tile.Material))
.Distinct()
.ToArray(); // Need to force this to evaluate now so that CreateAndAddTile actually gets called.
UpdateTileChunks();
return modifiedChunks;
}
/// <summary>
/// Refresh the meshes of any chunks that have been modified.
/// Returns true if any changes have been made.
/// </summary>
public bool UpdateTileChunks()
{
var updatedChunk = false;
var oldChunks = Chunks.ToArray();
for (int i = 0; i < oldChunks.Length; i++)
{
// Remove the chunk if it has no tiles in it.
if (oldChunks[i].Tiles.Count <= 0)
{
Chunks.Remove(oldChunks[i]);
Utils.Destroy(oldChunks[i].gameObject);
updatedChunk = true;
continue;
}
// Re-generate meshes.
if (oldChunks[i].Dirty)
{
oldChunks[i].GenerateMesh();
updatedChunk = true;
}
}
return updatedChunk;
}
//public HexChunk FindChunkForCoordinates
/// <summary>
/// Add a tile to the map. Returns the chunk object containing the new tile.
/// </summary>
public ModifiedTileInfo CreateAndAddTile(HexPosition position, Material material)
{
var coords = position.Coordinates;
var elevation = position.Elevation;
var chunk = FindChunkForCoordinatesAndMaterial(coords, material);
var chunkOperation = ModifiedTileInfo.ChunkOperation.Modified;
// Create new chunk if necessary
if (chunk == null)
{
chunk = CreateChunkForCoordinates(position.Coordinates, material);
chunkOperation = ModifiedTileInfo.ChunkOperation.Added;
}
// See if there's already a tile at the specified position.
var tile = FindTileForCoords(coords);
if (tile != null)
{
// If a tlie at that position and that height already exists, return it.
if (tile.Position.Elevation == elevation
&& tile.Material == material)
{
return new ModifiedTileInfo(chunk, chunkOperation);
}
// Remove the tile before adding a new one.
TryRemovingTile(coords);
}
chunk.AddTile(position);
// Generate side pieces
// Note that we also need to update all the tiles adjacent to this one so that any side pieces that could be
// Obscured by this one are removed.
foreach (var side in HexMetrics.AdjacentHexes)
{
var adjacentTilePos = coords + side;
var adjacentTile = FindTileForCoords(adjacentTilePos);
if (adjacentTile != null)
{
var adjacentTileChunk = FindChunkForCoordinatesAndMaterial(adjacentTilePos, adjacentTile.Material);
SetUpSidePiecesForTile(adjacentTilePos, adjacentTileChunk);
}
}
SetUpSidePiecesForTile(coords, chunk);
return new ModifiedTileInfo(chunk, chunkOperation);
}
/// <summary>
/// Add a new chunk with the specified material and bounds around the specified coordinates.
/// </summary>
private HexChunk CreateChunkForCoordinates(HexCoords coordinates, Material material)
{
var lowerBounds = new HexCoords(RoundDownToInterval(coordinates.Q, chunkSize), RoundDownToInterval(coordinates.R, chunkSize));
var upperBounds = new HexCoords(lowerBounds.Q + chunkSize, lowerBounds.R + chunkSize);
return CreateNewChunk(lowerBounds, upperBounds, material);
}
/// <summary>
/// Returns the chunk for the tile at the specified coordinates, or
/// null if none exists.
/// </summary>
public HexChunk FindChunkForCoordinates(HexCoords coordinates)
{
return Chunks.Where(c => c.Tiles.Where(tile => tile.Coordinates == coordinates).Any())
.FirstOrDefault();
}
/// <summary>
/// Find a chunk with bounds that match the specified coordinates, and the specified material.
/// Returns null if none was found.
/// </summary>
public HexChunk FindChunkForCoordinatesAndMaterial(HexCoords coordinates, Material material)
{
// Try to find existing chunk.
var matchingChunks = Chunks.Where(c => coordinates.IsWithinBounds(c.lowerBounds, c.upperBounds))
.Where(c => c.Material == material);
if (matchingChunks.Count() > 1)
{
Debug.LogWarning("Overlapping chunks detected for coordinates " + coordinates + ". Taking first.");
}
return matchingChunks.FirstOrDefault();
}
/// <summary>
/// Create a new chunk with the specified bounds and material.
/// </summary>
private HexChunk CreateNewChunk(HexCoords lowerBounds, HexCoords upperBounds, Material material)
{
var newGameObject = new GameObject(string.Format("Chunk {0} - {1}", lowerBounds, upperBounds));
newGameObject.transform.parent = transform;
var hexChunk = newGameObject.AddComponent<HexChunk>();
hexChunk.lowerBounds = lowerBounds;
hexChunk.upperBounds = upperBounds;
hexChunk.Material = material;
hexChunk.TileDiameter = tileDiameter;
Chunks.Add(hexChunk);
return hexChunk;
}
/// <summary>
/// Round the input integer down to the nearest multiple of the supplied interval.
/// Used to calculate which chunk a tile falls inside the bounds of.
/// </summary>
private static int RoundDownToInterval(int input, int interval)
{
return ((int)Math.Floor(input / (float)interval)) * interval;
}
private void SetUpSidePiecesForTile(HexCoords position, HexChunk tileChunk)
{
var tile = FindTileForCoords(position);
if (tile == null)
{
throw new ApplicationException("Tried to set up side pieces for non-existent tile.");
}
foreach (var side in HexMetrics.AdjacentHexes)
{
var sidePosition = position + side;
var adjacentTile = FindTileForCoords(sidePosition);
if (adjacentTile != null)
{
var chunkWithTile = FindChunkForCoordinatesAndMaterial(sidePosition, adjacentTile.Material);
if (chunkWithTile != null)
{
chunkWithTile.TryRemovingSidePiece(position, side);
if (adjacentTile.Position.Elevation < tile.Position.Elevation)
{
tileChunk.AddSidePiece(position, side, tile.Position.Elevation - adjacentTile.Position.Elevation);
}
}
}
}
}
/// <summary>
/// Attempt to remove the tile at the specified position.
/// Returns true if it was removed successfully, false if no tile was found at that position.
/// </summary>
public bool TryRemovingTile(HexCoords position)
{
var tile = FindTileForCoords(position);
if (tile == null)
{
return false;
}
var chunksWithTile = Chunks.Where(c => c.Tiles.Select(pos => pos.Coordinates).Contains(position));
if (chunksWithTile == null || chunksWithTile.Count() < 1)
{
Debug.LogError("Tile found in internal tile collection but not in scene. Removing", this);
}
foreach (var chunk in chunksWithTile)
{
chunk.RemoveTile(position);
}
return true;
}
private GameObject SpawnTileObject(HexPosition position)
{
var newObject = new GameObject("Tile [" + position.Coordinates.Q + ", " + position.Coordinates.R + "]");
newObject.transform.parent = transform;
newObject.transform.position = HexPositionToWorldPosition(position);
return newObject;
}
/// <summary>
/// Destroy all child tiles and clear hashtable.
/// </summary>
public void ClearAllTiles()
{
Chunks.Clear();
// Note that we must add all children to a list first because if we
// destroy children as we loop through them, the array we're looping
// through will change and we can miss some.
var children = new List<GameObject>();
foreach (Transform child in transform)
{
children.Add(child.gameObject);
}
children.ForEach(child => DestroyImmediate(child));
}
/// <summary>
/// Returns whether or not the specified tile exists.
/// </summary>
public bool ContainsTile(HexCoords tileCoords)
{
return FindTileForCoords(tileCoords) != null;
}
/// <summary>
/// Return data about the tile at the specified position.
/// </summary>
public bool TryGetTile(HexCoords tileCoords, out HexTileData data)
{
data = FindTileForCoords(tileCoords);
return data != null;
}
/// <summary>
/// Remove the tile at the specified coordinates and replace it with one with the specified material.
/// Returns the chunk with the tile that was modified.
/// </summary>
public ModifiedTileInfo ReplaceMaterialOnTile(HexCoords tileCoords, Material material)
{
HexTileData tile;
if (!TryGetTile(tileCoords, out tile))
{
throw new ArgumentOutOfRangeException("Tried replacing material on tile but map contains no tile at position " + tileCoords);
}
// Early out if the material is the same.
if (tile.Material == material)
{
var chunk = FindChunkForCoordinatesAndMaterial(tileCoords, material);
return new ModifiedTileInfo(chunk, ModifiedTileInfo.ChunkOperation.Modified);
}
TryRemovingTile(tileCoords);
return CreateAndAddTile(tile.Position, material);
}
/// <summary>
/// Returns all the tiles in this map.
/// </summary>
public IEnumerable<HexTileData> GetAllTiles()
{
return Tiles;
}
/// <summary>
/// Clears the internal cache of chunks, which will be lazily rebuilt next
/// time it's needed by scanning the scene hierarchy. Needed to be done after
/// a chunk is deleted by an undo action.
/// </summary>
public void ClearChunkCache()
{
chunks = null;
}
}
}
| 33.351443 | 141 | 0.532631 | [
"MIT"
] | Lepozuk/HexTiles | Assets/Code/HexTiles/HexTileMap.cs | 19,646 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace atividade_abstracao_01
{
class Arranjo : AnaliseCombinatoria
{
public override double calcular(int n, int p = 0)
{
return base.fatorial(n) / base.fatorial(n - p);
}
}
}
| 20.294118 | 59 | 0.657971 | [
"MIT"
] | otavio-augusto/pucminas | 08-roteiro-abstracao/atividade-abstracao-01/atividade-abstracao-01/Arranjo.cs | 347 | C# |
using System;
using System.Runtime.CompilerServices;
using LibHac.Common;
using LibHac.Sf;
using IStorageSf = LibHac.FsSrv.Sf.IStorage;
namespace LibHac.Fs.Impl
{
/// <summary>
/// An adapter for using an <see cref="IStorageSf"/> service object as an <see cref="IStorage"/>. Used
/// when receiving a Horizon IPC storage object so it can be used as an <see cref="IStorage"/> locally.
/// </summary>
internal class StorageServiceObjectAdapter : IStorage
{
private ReferenceCountedDisposable<IStorageSf> BaseStorage { get; }
public StorageServiceObjectAdapter(ReferenceCountedDisposable<IStorageSf> baseStorage)
{
BaseStorage = baseStorage.AddReference();
}
protected StorageServiceObjectAdapter(ref ReferenceCountedDisposable<IStorageSf> baseStorage)
{
BaseStorage = Shared.Move(ref baseStorage);
}
public static ReferenceCountedDisposable<IStorage> CreateShared(
ref ReferenceCountedDisposable<IStorageSf> baseStorage)
{
return new ReferenceCountedDisposable<IStorage>(new StorageServiceObjectAdapter(ref baseStorage));
}
protected override Result DoRead(long offset, Span<byte> destination)
{
return BaseStorage.Target.Read(offset, new OutBuffer(destination), destination.Length);
}
protected override Result DoWrite(long offset, ReadOnlySpan<byte> source)
{
return BaseStorage.Target.Write(offset, new InBuffer(source), source.Length);
}
protected override Result DoFlush()
{
return BaseStorage.Target.Flush();
}
protected override Result DoSetSize(long size)
{
return BaseStorage.Target.SetSize(size);
}
protected override Result DoGetSize(out long size)
{
return BaseStorage.Target.GetSize(out size);
}
protected override Result DoOperateRange(Span<byte> outBuffer, OperationId operationId, long offset, long size,
ReadOnlySpan<byte> inBuffer)
{
switch (operationId)
{
case OperationId.InvalidateCache:
return BaseStorage.Target.OperateRange(out _, (int)OperationId.InvalidateCache, offset, size);
case OperationId.QueryRange:
if (outBuffer.Length != Unsafe.SizeOf<QueryRangeInfo>())
return ResultFs.InvalidSize.Log();
ref QueryRangeInfo info = ref SpanHelpers.AsStruct<QueryRangeInfo>(outBuffer);
return BaseStorage.Target.OperateRange(out info, (int)OperationId.QueryRange, offset, size);
default:
return ResultFs.UnsupportedOperateRangeForFileServiceObjectAdapter.Log();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
BaseStorage?.Dispose();
}
base.Dispose(disposing);
}
}
} | 36.482759 | 120 | 0.611846 | [
"BSD-3-Clause"
] | Thealexbarney/LibHac | src/LibHac/Fs/Impl/StorageServiceObjectAdapter.cs | 3,176 | C# |
#if !NET452 && !NET46
namespace Microsoft.ApplicationInsights.TestFramework.Extensibility.Implementation.Authentication
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
/// <remarks>
/// Copied from (https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/core/Azure.Core.TestFramework/src/MockCredential.cs).
/// </remarks>
public class MockCredential : TokenCredential
{
public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
return new ValueTask<AccessToken>(GetToken(requestContext, cancellationToken));
}
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
return new AccessToken("TEST TOKEN " + string.Join(" ", requestContext.Scopes), DateTimeOffset.MaxValue);
}
}
}
#endif
| 36 | 133 | 0.717078 | [
"MIT"
] | 304NotModified/ApplicationInsights-dotnet | BASE/Test/Microsoft.ApplicationInsights.Test/Microsoft.ApplicationInsights.Tests/Extensibility/Implementation/Authentication/MockCredential.cs | 974 | C# |
//------------------------------------------------------------------------------
// <auto-generated>This code was generated by LLBLGen Pro v5.3.</auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace EFCore20.Bencher.EntityClasses
{
/// <summary>Class which represents the entity 'Address'.</summary>
public partial class Address : CommonEntityBase
{
#region Class Extensibility Methods
/// <summary>Method called from the constructor</summary>
partial void OnCreated();
#endregion
/// <summary>Initializes a new instance of the <see cref="Address"/> class.</summary>
public Address() : base()
{
this.BusinessEntityAddresses = new List<BusinessEntityAddress>();
this.SalesOrderHeaders = new List<SalesOrderHeader>();
this.SalesOrderHeaders_ = new List<SalesOrderHeader>();
OnCreated();
}
/// <summary>Gets or sets the AddressId field. </summary>
public System.Int32 AddressId { get; set;}
/// <summary>Gets or sets the AddressLine1 field. </summary>
public System.String AddressLine1 { get; set;}
/// <summary>Gets or sets the AddressLine2 field. </summary>
public System.String AddressLine2 { get; set;}
/// <summary>Gets or sets the City field. </summary>
public System.String City { get; set;}
/// <summary>Gets or sets the ModifiedDate field. </summary>
public System.DateTime ModifiedDate { get; set;}
/// <summary>Gets or sets the PostalCode field. </summary>
public System.String PostalCode { get; set;}
/// <summary>Gets or sets the Rowguid field. </summary>
public System.Guid Rowguid { get; set;}
/// <summary>Gets or sets the StateProvinceId field. </summary>
public System.Int32 StateProvinceId { get; set;}
/// <summary>Represents the navigator which is mapped onto the association 'Person.BusinessEntityAddress.Address - Address.BusinessEntityAddresses (m:1)'</summary>
public List<BusinessEntityAddress> BusinessEntityAddresses { get; set;}
/// <summary>Represents the navigator which is mapped onto the association 'SalesOrderHeader.Address - Address.SalesOrderHeaders (m:1)'</summary>
public List<SalesOrderHeader> SalesOrderHeaders { get; set;}
/// <summary>Represents the navigator which is mapped onto the association 'SalesOrderHeader.Address_ - Address.SalesOrderHeaders_ (m:1)'</summary>
public List<SalesOrderHeader> SalesOrderHeaders_ { get; set;}
/// <summary>Represents the navigator which is mapped onto the association 'Address.StateProvince - StateProvince.Addresses (m:1)'</summary>
public StateProvince StateProvince { get; set;}
}
}
| 50.980769 | 165 | 0.696718 | [
"MIT"
] | sanekpr/RawDataAccessBencher | EFCore2.0/Model/EntityClasses/Address.cs | 2,653 | C# |
using FakeItEasy;
using NUnit.Framework;
using System;
namespace Conway.Domain.Utilities.Tests
{
public class FastRandomTests
{
[Test]
public void NextBoolean_SetsBitsOnlyOnceEveryThirtyOneCalls()
{
var sut = A.Fake<FastRandom>();
A.CallTo(sut).CallsBaseMethod();
for (int i = 0; i < 62; ++i)
{
sut.NextBoolean();
}
A.CallTo(() => sut.CallNext()).MustHaveHappenedTwiceExactly();
}
[Test]
public void NextBoolean_ProducesARandomBoolean()
{
var sut = new FastRandom();
var trueCount = 0;
for (int i = 0; i < 1000000; ++i)
{
trueCount += sut.NextBoolean() ? 1 : 0;
}
Console.WriteLine($"{trueCount} / 1000000 results were true");
Assert.IsTrue(trueCount < 1000000);
}
}
} | 19.473684 | 65 | 0.651351 | [
"MIT"
] | Riegardt/Conway | tests/Conway.Domain.Tests/Utilities/FastRandomTests.cs | 740 | C# |
using System;
using System.Reflection;
using Acquaintance.Utility;
namespace Acquaintance.RequestResponse
{
public class UntypedListenerBuilder
{
private readonly IReqResBus _messageBus;
public UntypedListenerBuilder(IReqResBus messageBus)
{
_messageBus = messageBus;
}
private Type EnsureResponseType(Type requestType, Type responseType)
{
if (responseType != null)
return responseType;
var definedResponseType = requestType.GetRequestResponseType();
if (definedResponseType != null)
return definedResponseType;
throw new Exception("No response type provided and one cannot be determined from metadata");
}
public IDisposable ListenUntyped(Type requestType, Type responseType, string topic, Func<object, object> func, bool useWeakReference = false)
{
Assert.ArgumentNotNull(requestType, nameof(requestType));
Assert.ArgumentNotNull(func, nameof(func));
responseType = EnsureResponseType(requestType, responseType);
var method = GetMethod(nameof(ListenUntypedFuncInternal));
method = method.MakeGenericMethod(requestType, responseType);
return method.Invoke(this, new object[] { topic, func, useWeakReference }) as IDisposable;
}
public IDisposable ListenUntyped(Type requestType, Type responseType, string topic, object target, MethodInfo listener, bool useWeakReference = false)
{
Assert.ArgumentNotNull(requestType, nameof(requestType));
Assert.ArgumentNotNull(target, nameof(target));
Assert.ArgumentNotNull(listener, nameof(listener));
responseType = EnsureResponseType(requestType, responseType);
var method = GetMethod(nameof(ListenUntypedMethodInfoInternal));
method = method.MakeGenericMethod(requestType, responseType);
return method.Invoke(this, new object[] { topic, target, listener, useWeakReference }) as IDisposable;
}
public IDisposable ListenEnvelopeUntyped(Type requestType, Type responseType, string topic, object target, MethodInfo listener, bool useWeakReference = false)
{
Assert.ArgumentNotNull(requestType, nameof(requestType));
Assert.ArgumentNotNull(target, nameof(target));
Assert.ArgumentNotNull(listener, nameof(listener));
responseType = EnsureResponseType(requestType, responseType);
var method = GetMethod(nameof(ListenEnvelopeUntypedMethodInfoInternal));
method = method.MakeGenericMethod(requestType, responseType);
return method.Invoke(this, new object[] { topic, target, listener, useWeakReference }) as IDisposable;
}
private MethodInfo GetMethod(string name)
{
var method = GetType().GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod);
if (method == null)
throw new Exception($"Could not find method {GetType().Name}.{name}");
return method;
}
private IDisposable ListenUntypedMethodInfoInternal<TRequest, TResponse>(string topic, object target, MethodInfo method, bool useWeakReference)
{
return _messageBus.Listen<TRequest, TResponse>(b => b
.WithTopic(topic)
.Invoke(p => (TResponse)method.Invoke(target, new object[] { p }), useWeakReference));
}
private IDisposable ListenUntypedFuncInternal<TRequest, TResponse>(string topic, Func<object, object> func, bool useWeakReference)
{
return _messageBus.Listen<TRequest, TResponse>(b => b
.WithTopic(topic)
.Invoke(p => (TResponse)func(p), useWeakReference));
}
private IDisposable ListenEnvelopeUntypedMethodInfoInternal<TRequest, TResponse>(string topic, object target, MethodInfo method, bool useWeakReference)
{
var token = _messageBus.Listen<TRequest, TResponse>(b => b
.WithTopic(topic)
.InvokeEnvelope(p => (TResponse)method.Invoke(target, new object[] { p }), useWeakReference));
return token;
}
}
}
| 46.408602 | 166 | 0.662419 | [
"Apache-2.0"
] | Whiteknight/Acquaintance | Acquaintance/RequestResponse/UntypedListenerBuilder.cs | 4,318 | C# |
//
// Copyright © Martin Tamme
//
// 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;
namespace NProxy.Core.Test.Types
{
internal class EnumArrayOutConstructor : IConstructor
{
public EnumArrayOutConstructor(out EnumType[] value)
{
value = new EnumType[0];
}
}
internal class EnumOutConstructor : IConstructor
{
public EnumOutConstructor(out EnumType value)
{
value = default(EnumType);
}
}
internal class GenericArrayOutConstructor<TValue> : IGenericConstructor<TValue>
{
public GenericArrayOutConstructor(out TValue[] value)
{
value = new TValue[0];
}
}
internal class GenericJaggedArrayOutConstructor<TValue> : IGenericConstructor<TValue>
{
public GenericJaggedArrayOutConstructor(out TValue[][] value)
{
value = new TValue[0][];
}
}
internal class GenericRankArrayOutConstructor<TValue> : IGenericConstructor<TValue>
{
public GenericRankArrayOutConstructor(out TValue[,] value)
{
value = new TValue[0, 0];
}
}
internal class GenericListOutConstructor<TValue> : IGenericConstructor<TValue>
{
public GenericListOutConstructor(out List<TValue> value)
{
value = new List<TValue>();
}
}
internal class GenericOutConstructor<TValue> : IGenericConstructor<TValue>
{
public GenericOutConstructor(out TValue value)
{
value = default(TValue);
}
}
internal class IntArrayOutConstructor : IConstructor
{
public IntArrayOutConstructor(out int[] value)
{
value = new int[0];
}
}
internal class IntOutConstructor : IConstructor
{
public IntOutConstructor(out int value)
{
value = default(int);
}
}
internal class StringArrayOutConstructor : IConstructor
{
public StringArrayOutConstructor(out string[] value)
{
value = new string[0];
}
}
internal class StringOutConstructor : IConstructor
{
public StringOutConstructor(out string value)
{
value = String.Empty;
}
}
internal class StructArrayOutConstructor : IConstructor
{
public StructArrayOutConstructor(out StructType[] value)
{
value = new StructType[0];
}
}
internal class StructOutConstructor : IConstructor
{
public StructOutConstructor(out StructType value)
{
value = default(StructType);
}
}
} | 25.872 | 89 | 0.624613 | [
"Apache-2.0"
] | mtamme/NProxy | Source/Test/NProxy.Core.Test/Types/OutConstructor.cs | 3,237 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
using System;
namespace Aiursoft.Gateway.Migrations
{
public partial class AnotherWayToMarkCodeUseTime : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsUsed",
table: "OAuthPack");
migrationBuilder.AddColumn<DateTime>(
name: "UseTime",
table: "OAuthPack",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "UseTime",
table: "OAuthPack");
migrationBuilder.AddColumn<bool>(
name: "IsUsed",
table: "OAuthPack",
nullable: false,
defaultValue: false);
}
}
}
| 28.857143 | 83 | 0.548515 | [
"MIT"
] | AiursoftWeb/Infrastructures | src/WebServices/Basic/Gateway/Migrations/20190210080359_AnotherWayToMarkCodeUseTime.cs | 1,012 | C# |
// <copyright file="Multinomial.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.Properties;
using MathNet.Numerics.Random;
using MathNet.Numerics.Statistics;
namespace MathNet.Numerics.Distributions
{
/// <summary>
/// Multivariate Multinomial distribution. For details about this distribution, see
/// <a href="http://en.wikipedia.org/wiki/Multinomial_distribution">Wikipedia - Multinomial distribution</a>.
/// </summary>
/// <remarks>
/// The distribution is parameterized by a vector of ratios: in other words, the parameter
/// does not have to be normalized and sum to 1. The reason is that some vectors can't be exactly normalized
/// to sum to 1 in floating point representation.
/// </remarks>
public class Multinomial : IDistribution
{
System.Random _random;
/// <summary>
/// Stores the normalized multinomial probabilities.
/// </summary>
readonly double[] _p;
/// <summary>
/// The number of trials.
/// </summary>
readonly int _trials;
/// <summary>
/// Initializes a new instance of the Multinomial class.
/// </summary>
/// <param name="p">An array of nonnegative ratios: this array does not need to be normalized
/// as this is often impossible using floating point arithmetic.</param>
/// <param name="n">The number of trials.</param>
/// <exception cref="ArgumentOutOfRangeException">If any of the probabilities are negative or do not sum to one.</exception>
/// <exception cref="ArgumentOutOfRangeException">If <paramref name="n"/> is negative.</exception>
public Multinomial(double[] p, int n)
{
if (Control.CheckDistributionParameters && !IsValidParameterSet(p, n))
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
_random = SystemRandomSource.Default;
_p = (double[])p.Clone();
_trials = n;
}
/// <summary>
/// Initializes a new instance of the Multinomial class.
/// </summary>
/// <param name="p">An array of nonnegative ratios: this array does not need to be normalized
/// as this is often impossible using floating point arithmetic.</param>
/// <param name="n">The number of trials.</param>
/// <param name="randomSource">The random number generator which is used to draw random samples.</param>
/// <exception cref="ArgumentOutOfRangeException">If any of the probabilities are negative or do not sum to one.</exception>
/// <exception cref="ArgumentOutOfRangeException">If <paramref name="n"/> is negative.</exception>
public Multinomial(double[] p, int n, System.Random randomSource)
{
if (Control.CheckDistributionParameters && !IsValidParameterSet(p, n))
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
_random = randomSource ?? SystemRandomSource.Default;
_p = (double[])p.Clone();
_trials = n;
}
/// <summary>
/// Initializes a new instance of the Multinomial class from histogram <paramref name="h"/>. The distribution will
/// not be automatically updated when the histogram changes.
/// </summary>
/// <param name="h">Histogram instance</param>
/// <param name="n">The number of trials.</param>
/// <exception cref="ArgumentOutOfRangeException">If any of the probabilities are negative or do not sum to one.</exception>
/// <exception cref="ArgumentOutOfRangeException">If <paramref name="n"/> is negative.</exception>
public Multinomial(Histogram h, int n)
{
if (h == null)
{
throw new ArgumentNullException(nameof(h));
}
// The probability distribution vector.
var p = new double[h.BucketCount];
// Fill in the distribution vector.
for (var i = 0; i < h.BucketCount; i++)
{
p[i] = h[i].Count;
}
if (Control.CheckDistributionParameters && !IsValidParameterSet(p, n))
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
_p = (double[])p.Clone();
_trials = n;
RandomSource = SystemRandomSource.Default;
}
/// <summary>
/// A string representation of the distribution.
/// </summary>
/// <returns>a string representation of the distribution.</returns>
public override string ToString()
{
return $"Multinomial(Dimension = {_p.Length}, Number of Trails = {_trials})";
}
/// <summary>
/// Tests whether the provided values are valid parameters for this distribution.
/// </summary>
/// <param name="p">An array of nonnegative ratios: this array does not need to be normalized
/// as this is often impossible using floating point arithmetic.</param>
/// <param name="n">The number of trials.</param>
/// <returns>If any of the probabilities are negative returns <c>false</c>,
/// if the sum of parameters is 0.0, or if the number of trials is negative; otherwise <c>true</c>.</returns>
public static bool IsValidParameterSet(IEnumerable<double> p, int n)
{
var sum = 0.0;
foreach (var t in p)
{
if (t < 0.0 || double.IsNaN(t))
{
return false;
}
sum += t;
}
if (sum == 0.0)
{
return false;
}
return n >= 0;
}
/// <summary>
/// Gets the proportion of ratios.
/// </summary>
public double[] P => (double[])_p.Clone();
/// <summary>
/// Gets the number of trials.
/// </summary>
public int N => _trials;
/// <summary>
/// Gets or sets the random number generator which is used to draw random samples.
/// </summary>
public System.Random RandomSource
{
get => _random;
set => _random = value ?? SystemRandomSource.Default;
}
/// <summary>
/// Gets the mean of the distribution.
/// </summary>
public Vector<double> Mean => _trials*(DenseVector)P;
/// <summary>
/// Gets the variance of the distribution.
/// </summary>
public Vector<double> Variance
{
get
{
// Do not use _p, because operations below will modify _p array. Use P or _p.Clone().
var res = (DenseVector)P;
for (var i = 0; i < res.Count; i++)
{
res[i] *= _trials*(1 - res[i]);
}
return res;
}
}
/// <summary>
/// Gets the skewness of the distribution.
/// </summary>
public Vector<double> Skewness
{
get
{
// Do not use _p, because operations below will modify _p array. Use P or _p.Clone().
var res = (DenseVector)P;
for (var i = 0; i < res.Count; i++)
{
res[i] = (1.0 - (2.0*res[i]))/Math.Sqrt(_trials*(1.0 - res[i])*res[i]);
}
return res;
}
}
/// <summary>
/// Computes values of the probability mass function.
/// </summary>
/// <param name="x">Non-negative integers x1, ..., xk</param>
/// <returns>The probability mass at location <paramref name="x"/>.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="x"/> is null.</exception>
/// <exception cref="ArgumentException">When length of <paramref name="x"/> is not equal to event probabilities count.</exception>
public double Probability(int[] x)
{
if (null == x)
{
throw new ArgumentNullException(nameof(x));
}
if (x.Length != _p.Length)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength, nameof(x));
}
if (x.Sum() == _trials)
{
var coef = SpecialFunctions.Multinomial(_trials, x);
var num = 1.0;
for (var i = 0; i < x.Length; i++)
{
num *= Math.Pow(_p[i], x[i]);
}
return coef*num;
}
return 0.0;
}
/// <summary>
/// Computes values of the log probability mass function.
/// </summary>
/// <param name="x">Non-negative integers x1, ..., xk</param>
/// <returns>The log probability mass at location <paramref name="x"/>.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="x"/> is null.</exception>
/// <exception cref="ArgumentException">When length of <paramref name="x"/> is not equal to event probabilities count.</exception>
public double ProbabilityLn(int[] x)
{
if (null == x)
{
throw new ArgumentNullException(nameof(x));
}
if (x.Length != _p.Length)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength, nameof(x));
}
if (x.Sum() == _trials)
{
var coef = Math.Log(SpecialFunctions.Multinomial(_trials, x));
var num = x.Select((t, i) => t*Math.Log(_p[i])).Sum();
return coef + num;
}
return 0.0;
}
/// <summary>
/// Samples one multinomial distributed random variable.
/// </summary>
/// <returns>the counts for each of the different possible values.</returns>
public int[] Sample()
{
return Sample(_random, _p, _trials);
}
/// <summary>
/// Samples a sequence multinomially distributed random variables.
/// </summary>
/// <returns>a sequence of counts for each of the different possible values.</returns>
public IEnumerable<int[]> Samples()
{
while (true)
{
yield return Sample(_random, _p, _trials);
}
}
/// <summary>
/// Samples one multinomial distributed random variable.
/// </summary>
/// <param name="rnd">The random number generator to use.</param>
/// <param name="p">An array of nonnegative ratios: this array does not need to be normalized
/// as this is often impossible using floating point arithmetic.</param>
/// <param name="n">The number of trials.</param>
/// <returns>the counts for each of the different possible values.</returns>
public static int[] Sample(System.Random rnd, double[] p, int n)
{
if (Control.CheckDistributionParameters && !IsValidParameterSet(p, n))
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
// The cumulative density of p.
var cp = Categorical.ProbabilityMassToCumulativeDistribution(p);
// The variable that stores the counts.
var ret = new int[p.Length];
for (var i = 0; i < n; i++)
{
ret[Categorical.SampleUnchecked(rnd, cp)]++;
}
return ret;
}
/// <summary>
/// Samples a multinomially distributed random variable.
/// </summary>
/// <param name="rnd">The random number generator to use.</param>
/// <param name="p">An array of nonnegative ratios: this array does not need to be normalized
/// as this is often impossible using floating point arithmetic.</param>
/// <param name="n">The number of variables needed.</param>
/// <returns>a sequence of counts for each of the different possible values.</returns>
public static IEnumerable<int[]> Samples(System.Random rnd, double[] p, int n)
{
if (Control.CheckDistributionParameters && !IsValidParameterSet(p, n))
{
throw new ArgumentException(Resources.InvalidDistributionParameters);
}
// The cumulative density of p.
var cp = Categorical.ProbabilityMassToCumulativeDistribution(p);
while (true)
{
// The variable that stores the counts.
var ret = new int[p.Length];
for (var i = 0; i < n; i++)
{
ret[Categorical.SampleUnchecked(rnd, cp)]++;
}
yield return ret;
}
}
}
}
| 38 | 138 | 0.565893 | [
"MIT"
] | Evangelink/mathnet-numerics | src/Numerics/Distributions/Multinomial.cs | 14,556 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic;
using UnityEngine;
namespace Fizzyo
{
// Serializable which holds high score data
[System.Serializable]
public class AllHighscoreData
{
public HighscoreData[] highscores;
}
// Serializable which holds individual high score data
[System.Serializable]
public class HighscoreData
{
public string tag;
public int score;
public bool belongsToUser;
}
// Serializable which holds achievement data
[System.Serializable]
public class AllAchievementData
{
public AchievementData[] achievements;
public AchievementData[] unlockedAchievements;
}
// Serializable that is used to pull and hold the data of each Achievement in the Achievements.json file
[System.Serializable]
public class AchievementData
{
public string category;
public string id;
public string title;
public string description;
public int points;
public int unlock;
public int unlockProgress;
public int unlockRequirement;
public string dependency;
public string unlockedOn;
}
// Serializable which holds calibration data
[System.Serializable]
public class CalibrationData
{
public string calibratedOn;
public float pressure;
public int time;
}
/// <summary>
/// Used to unlock Fizzyo achievements and post high scores in the Fizzyo rest API
/// </summary>
public class FizzyoAchievements
{
/// <summary>
/// Array of type AchievementData which holds all the achievements that the game has to offer.
/// </summary>
public AchievementData[] allAchievements;
/// <summary>
/// Array of type AchievementData which holds the achievements the user has unlocked.
/// </summary>
public AchievementData[] unlockedAchievements;
/// <summary>
/// Array of type HighscoreData which holds the top 20 highest scores for the game.
/// </summary>
public HighscoreData[] highscores;
/// <summary>
/// Loads all game achievements and the users unlocked achievements and achievement progress.
/// </summary>
/// <returns>
/// A JSON formatted string containing the list of achievements
/// </returns>
public FizzyoRequestReturnType LoadAchievements()
{
if (FizzyoNetworking.loginResult != LoginReturnType.SUCCESS)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
LoadAllAchievements();
LoadUnlockedAchievements();
return FizzyoRequestReturnType.SUCCESS;
}
internal FizzyoRequestReturnType LoadAllAchievements()
{
if (FizzyoNetworking.loginResult != LoginReturnType.SUCCESS)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
//Get all achievements from server
var webRequest = FizzyoNetworking.GetWebRequest(FizzyoNetworking.ApiEndpoint + "games/" + FizzyoFramework.Instance.FizzyoConfigurationProfile.GameID + "/achievements");
webRequest.SendWebRequest();
while (!webRequest.isDone) { }
string achievementsJSONData = webRequest.downloadHandler.text;
allAchievements = JsonUtility.FromJson<AllAchievementData>(achievementsJSONData).achievements;
return FizzyoRequestReturnType.SUCCESS;
}
internal FizzyoRequestReturnType LoadUnlockedAchievements()
{
if (FizzyoNetworking.loginResult != LoginReturnType.SUCCESS)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
//get unlocked achievements
var webRequest = FizzyoNetworking.GetWebRequest(FizzyoNetworking.ApiEndpoint + "users/" + FizzyoFramework.Instance.User.UserID + "/unlocked-achievements/" + FizzyoFramework.Instance.FizzyoConfigurationProfile.GameID);
webRequest.SendWebRequest();
while (!webRequest.isDone) { }
if (webRequest.error != null)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
string unlockedJSONData = webRequest.downloadHandler.text;
unlockedAchievements = JsonUtility.FromJson<AllAchievementData>(unlockedJSONData).unlockedAchievements;
return FizzyoRequestReturnType.SUCCESS;
}
internal void Load()
{
LoadAchievements();
}
/// <summary>
/// Loads in the top 20 high-scores for the current game.
/// </summary>
/// <returns>
/// A JSON formatted string containing tag and score for the top 20 scores of the game
/// </returns>
public FizzyoRequestReturnType GetHighscores()
{
if (FizzyoNetworking.loginResult != LoginReturnType.SUCCESS)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
var webRequest = FizzyoNetworking.GetWebRequest(FizzyoNetworking.ApiEndpoint + "games/" + FizzyoFramework.Instance.FizzyoConfigurationProfile.GameID + "/highscores");
webRequest.SendWebRequest();
while (!webRequest.isDone) { }
if (webRequest.error != null)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
string topScoresJSONData = webRequest.downloadHandler.text;
highscores = JsonUtility.FromJson<AllHighscoreData>(topScoresJSONData).highscores;
return FizzyoRequestReturnType.SUCCESS;
}
/// <summary>
/// Uploads a players Score
/// </summary>
/// <returns>
/// String - "High Score Upload Complete" - If upload completes
/// String - "High Score Upload Failed" - If upload fails
/// </returns>
public FizzyoRequestReturnType PostScore(int score)
{
if (FizzyoNetworking.loginResult != LoginReturnType.SUCCESS)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
Dictionary<string, string> formData = new Dictionary<string, string>();
formData.Add("gameSecret", FizzyoFramework.Instance.FizzyoConfigurationProfile.GameSecret);
formData.Add("userId", FizzyoFramework.Instance.User.UserID);
formData.Add("score", score.ToString());
var webRequest = FizzyoNetworking.PostWebRequest(FizzyoNetworking.ApiEndpoint + "games/" + FizzyoFramework.Instance.FizzyoConfigurationProfile.GameID + "/highscores", formData);
webRequest.SendWebRequest();
while (!webRequest.isDone) { };
if (webRequest.error != null)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
return FizzyoRequestReturnType.SUCCESS;
}
/// <summary>
/// Unlocks the achievement specified in the parameter, its achievementID.
/// </summary>
/// <returns>
/// FizzyoRequestReturnType.SUCCESS is upload is successful.
/// FizzyoRequestReturnType.FAILED_TO_CONNECT if connection failed.
/// </returns>
public FizzyoRequestReturnType UnlockAchievement(string achievementId)
{
if (FizzyoNetworking.loginResult != LoginReturnType.SUCCESS)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
Dictionary<string, string> formData = new Dictionary<string, string>();
formData.Add("gameSecret", FizzyoFramework.Instance.FizzyoConfigurationProfile.GameSecret);
formData.Add("userId", FizzyoFramework.Instance.User.UserID);
formData.Add("achievementId", achievementId);
var webRequest = FizzyoNetworking.PostWebRequest(FizzyoNetworking.ApiEndpoint + "games/" + FizzyoFramework.Instance.FizzyoConfigurationProfile.GameID + "/achievements/" + achievementId + "/unlock", formData);
webRequest.SendWebRequest();
while (!webRequest.isDone) { };
if (webRequest.error != null)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
//Refresh unlocked achievements to get the latest unlocked.
LoadUnlockedAchievements();
return FizzyoRequestReturnType.SUCCESS;
}
/// <summary>
/// Uploads a players achievements for a session
/// </summary>
/// <returns>
/// FizzyoRequestReturnType.SUCCESS is upload is successful.
/// FizzyoRequestReturnType.FAILED_TO_CONNECT if connection failed.
/// </returns>
private FizzyoRequestReturnType PostAchievements()
{
if (FizzyoNetworking.loginResult != LoginReturnType.SUCCESS)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
string achievementsToUpload = PlayerPrefs.GetString("achievementsToUpload");
if (achievementsToUpload != "")
{
string[] achievementsToUploadArray = achievementsToUpload.Split(',');
for (int i = 0; i < achievementsToUploadArray.Length; i++)
{
if (achievementsToUploadArray[i] != "")
{
Dictionary<string, string> formData = new Dictionary<string, string>();
formData.Add("gameSecret", FizzyoFramework.Instance.FizzyoConfigurationProfile.GameSecret);
formData.Add("userId", FizzyoFramework.Instance.User.UserID);
var webRequest = FizzyoNetworking.PostWebRequest(FizzyoNetworking.ApiEndpoint + "games/" + FizzyoFramework.Instance.FizzyoConfigurationProfile.GameID + "/achievements/" + achievementsToUploadArray[i] + "/unlock", formData);
webRequest.SendWebRequest();
while (!webRequest.isDone) { }
if (webRequest.error != null)
{
return FizzyoRequestReturnType.FAILED_TO_CONNECT;
}
}
}
}
string achievementsToProgress = PlayerPrefs.GetString("achievementsToProgress");
string[] achievementsToProgressArray = achievementsToProgress.Split(',');
AllAchievementData allUserProgress = JsonUtility.FromJson<AllAchievementData>(PlayerPrefs.GetString(FizzyoFramework.Instance.User.UserID + "AchievementProgress"));
AllAchievementData allAchievements = JsonUtility.FromJson<AllAchievementData>(PlayerPrefs.GetString("achievements"));
// Add achievement progress to player preferences
for (int i = 0; i < achievementsToProgressArray.Length; i++)
{
if (achievementsToProgressArray[i] != "")
{
for (int j = 0; j < allUserProgress.achievements.Length; j++)
{
if (allUserProgress.achievements[j].id == achievementsToProgressArray[i])
{
for (int k = 0; k < allAchievements.achievements.Length; k++)
{
if (allUserProgress.achievements[j].id == allAchievements.achievements[k].id)
{
allUserProgress.achievements[j].unlockProgress = allAchievements.achievements[k].unlockProgress;
string newAllData = JsonUtility.ToJson(allUserProgress);
PlayerPrefs.SetString(FizzyoFramework.Instance.User.UserID + "AchievementProgress", newAllData);
break;
}
}
break;
}
}
}
}
return FizzyoRequestReturnType.SUCCESS;
}
public AchievementData GetAchievement(string AchievementName)
{
if (allAchievements != null && allAchievements.Length > 0)
{
for (int i = 0; i < allAchievements.Length; i++)
{
if (allAchievements[i].title.ToLower() == AchievementName.ToLower())
{
return allAchievements[i];
}
}
}
return null;
}
public AchievementData GetUnlockedAchievement(string AchievementName)
{
if (unlockedAchievements != null && unlockedAchievements.Length > 0)
{
for (int i = 0; i < unlockedAchievements.Length; i++)
{
if (unlockedAchievements[i].title.ToLower() == AchievementName.ToLower())
{
return unlockedAchievements[i];
}
}
}
return null;
}
public FizzyoRequestReturnType CheckAndUnlockAchievement(string AchievementName)
{
if (unlockedAchievements != null)
{
Debug.LogError("Attempting to unlock [" + AchievementName + "]");
}
//Check if the user has already gained this achievement
var fizzyoUnlockedAchievement = GetUnlockedAchievement(AchievementName);
// If the player has not had this achievement before, unlock it
if (fizzyoUnlockedAchievement != null)
{
Debug.LogError("[" + AchievementName + "] - Already Unlocked");
return FizzyoRequestReturnType.ALREADY_UNLOCKED;
}
//Check if an achievement for this name exists
var fizzyoAchievement = GetAchievement(AchievementName);
if (fizzyoAchievement != null && fizzyoUnlockedAchievement == null)
{
Debug.LogError("[" + AchievementName + "] - Unlocked");
return UnlockAchievement(fizzyoAchievement.id);
}
if (unlockedAchievements != null)
{
Debug.LogError("[" + AchievementName + "] - Not Found");
}
return FizzyoRequestReturnType.NOT_FOUND;
}
}
} | 39.51436 | 248 | 0.576054 | [
"MIT"
] | Fizzyo/FizzyoFramework-Unity | Assets/Fizzyo/FizzyoFramework/Scripts/FizzyoAchievements.cs | 15,136 | C# |
using System;
namespace Xsolla.Login
{
[Serializable]
public class AccessTokenResponse
{
public string access_token;
}
}
| 11.636364 | 33 | 0.757813 | [
"Apache-2.0"
] | xsolla/inventory-unity-sdk | Assets/Xsolla/Login/Scripts/Entities/AccessTokenResponse.cs | 128 | C# |
namespace SudokuApplication.Core.Enums
{
public enum PlayerDecisionType
{
FillCell,
Restart,
Solve
}
}
| 14 | 39 | 0.592857 | [
"MIT"
] | danielrss/SudokuApplication | SudokuApplication/SudokuApplication.Core/Enums/PlayerDecisionType.cs | 142 | 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;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Query.SqlExpressions
{
public class CaseWhenClause
{
public CaseWhenClause([NotNull] SqlExpression test, [NotNull] SqlExpression result)
{
Check.NotNull(test, nameof(test));
Check.NotNull(result, nameof(result));
Test = test;
Result = result;
}
public virtual SqlExpression Test { get; }
public virtual SqlExpression Result { get; }
public override bool Equals(object obj)
=> obj != null
&& (ReferenceEquals(this, obj)
|| obj is CaseWhenClause caseWhenClause
&& Equals(caseWhenClause));
private bool Equals(CaseWhenClause caseWhenClause)
=> Test.Equals(caseWhenClause.Test)
&& Result.Equals(caseWhenClause.Result);
public override int GetHashCode() => HashCode.Combine(Test, Result);
}
}
| 32.756757 | 111 | 0.638614 | [
"Apache-2.0"
] | 1iveowl/efcore | src/EFCore.Relational/Query/SqlExpressions/CaseWhenClause.cs | 1,212 | C# |
using System.Collections.Generic;
using People.Domain;
namespace Map.Domain
{
/**
* List of all people on the map
*/
public class PersonList
{
public List<Person> People { get; }
public PersonList()
{
People = new List<Person>();
}
}
} | 17.111111 | 43 | 0.545455 | [
"MIT"
] | keypax/object-pooling-in-unity-demo | Assets/Scripts/Map/Domain/PersonList.cs | 310 | C# |
using System;
using System.Text;
using SampleApp.Business.Entities;
using Tenor.Data;
using System.Linq;
#if MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
#else
using TestMethodAttribute = NUnit.Framework.TestAttribute;
using TestClassAttribute = NUnit.Framework.TestFixtureAttribute;
using Assert = NUnit.Framework.Assert;
#endif
namespace Tenor.Test
{
/// <summary>
/// Summary description for SavingEntities
/// </summary>
[TestClass]
public class SavingEntities : TestBase
{
public static string RandomString(int size, bool lowerCase)
{
Random randomSeed = new Random();
StringBuilder randStr = new StringBuilder(size);
// Ascii start position (65 = A / 97 = a)
int Start = (lowerCase) ? 97 : 65;
// Add random chars
for (int i = 0; i < size; i++)
randStr.Append((char)(26 * randomSeed.NextDouble() + Start));
return randStr.ToString();
}
public static Person CreateNewPerson()
{
Person p = new Person();
p.Active = true;
p.Name = "Test " + RandomString(8, true);
p.Save();
return p;
}
[TestMethod]
public void CreateNewEntity()
{
Person p = CreateNewPerson();
p = new Person(p.PersonId);
}
[TestMethod]
public void TransactionScopeTest()
{
try
{
using (var t = new System.Transactions.TransactionScope())
{
Person p1 = CreateNewPerson();
Person p2 = CreateNewPerson();
throw new Exception();
}
}
catch (Exception)
{
var persons =
(from p in Tenor.Linq.SearchOptions<Person>.CreateQuery()
select p).Count();
Assert.AreEqual(2, persons);
}
}
[TestMethod]
public void SaveManyToManyList()
{
//Loads a person and adds 3 departments to its N:N relation.
Person p = new Person(2);
p.MaritalStatus = (MaritalStatus)new Random().Next(0, 8);
p.DepartmentList.Clear();
int[] departments = new int[] { 1, 3, 4 };
foreach (int id in departments)
{
Department d = new Department();
d.DepartmentId = id;
p.DepartmentList.Add(d);
}
Transaction t = new Transaction();
try
{
t.Include(p);
p.Save(true);
p.SaveList("DepartmentList");
t.Commit();
}
catch (Exception ex)
{
t.Rollback();
Assert.Fail("Cannot save person. " + ex.Message);
}
//Check if person 2 have the departments 1, 3 and 4
p = new Person(2);
foreach (int id in departments)
{
Department d = new Department();
d.DepartmentId = id;
if (!p.DepartmentList.Contains(d))
Assert.Fail(string.Format("Department {0} was not associated with person 2. ", id));
}
}
[TestMethod]
public void SaveByteArray()
{
EntityBase.LastSearches.Clear();
var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 7, 8 };
var p = new Person() { PersonId = 1 };
p.Bind();
Assert.IsTrue(EntityBase.LastSearches.Count == 1);
p.Photo3 = bytes;
p.Save();
Assert.IsTrue(EntityBase.LastSearches.Count == 1);
p = new Person() { PersonId = 1 };
p.Bind();
Assert.IsTrue(EntityBase.LastSearches.Count == 2);
CollectionAssert.AreEquivalent(bytes, p.Photo3);
Assert.IsTrue(EntityBase.LastSearches.Count == 2);
}
[TestMethod]
public void SaveBinaryStream()
{
EntityBase.LastSearches.Clear();
var bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 7, 8 };
var p = new Person() { PersonId = 1 };
p.Bind();
var photo = p.Photo;
Assert.IsTrue(EntityBase.LastSearches.Count == 1);
p.Save();
p.Photo = new MemoryStream(bytes);
p.Save();
Assert.IsTrue(EntityBase.LastSearches.Count == 1);
p = new Person() { PersonId = 1 };
p.Bind();
Assert.IsTrue(EntityBase.LastSearches.Count == 2);
var returnedBytes = (p.Photo as BinaryStream).ToArray();
CollectionAssert.AreEquivalent(bytes, returnedBytes);
Assert.IsTrue(EntityBase.LastSearches.Count == 3);
}
}
}
| 28.688889 | 105 | 0.482572 | [
"MIT"
] | junalmeida/tenor-framework | Tenor.Test/SavingEntities.cs | 5,166 | C# |
using System.Net;
namespace Shared.Api.Response
{
public class ApiActionResultNotFound : ApiActionResultBase, IApiActionResult
{
public override int StatusCode { get { return (int)HttpStatusCode.NotFound; } }
public ApiActionResultNotFound() : base(null)
{
Message = "not found";
}
public ApiActionResultNotFound(string msg) : base(msg)
{
Message = msg;
}
public override string GetDefaultMessage()
{
return "Not Found";
}
}
}
| 22.4 | 87 | 0.585714 | [
"MIT"
] | chenjunsheep/Shared.Library | Shared.Api/Response/ApiActionResultNotFound.cs | 562 | C# |
using System;
using DevExpress.Xpo;
using DevExpress.Xpo.Metadata;
using DevExpress.Data.Filtering;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace DbSurat
{
public partial class Pegawai
{
public Pegawai(Session session) : base(session) { }
public override void AfterConstruction() { base.AfterConstruction(); }
}
}
| 22.055556 | 78 | 0.738035 | [
"Apache-2.0"
] | hendrawash/AppSurat | Surat/ORMDataModelSuratCode/Pegawai.cs | 399 | C# |
using System;
using Param_ItemNamespace.Core.Models;
using Param_ItemNamespace.Services;
using Param_ItemNamespace.Helpers;
using Microsoft.Toolkit.Uwp.UI.Animations;
using Windows.System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
namespace Param_ItemNamespace.Views
{
public sealed partial class ImageGalleryViewDetailPage : Page
{
public ImageGalleryViewDetailPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
ViewModel.Initialize(e.Parameter as string, e.NavigationMode);
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
if (e.NavigationMode == NavigationMode.Back)
{
NavigationService.Frame.SetListDataItemForNextConnectedAnnimation(ViewModel.SelectedImage);
ImagesNavigationHelper.RemoveImageId(ImageGalleryViewViewModel.ImageGalleryViewSelectedIdKey);
}
}
private void OnPageKeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Escape && NavigationService.CanGoBack)
{
NavigationService.GoBack();
e.Handled = true;
}
}
}
}
| 30.826087 | 110 | 0.657264 | [
"MIT"
] | AzureMentor/WindowsTemplateStudio | templates/Uwp/Pages/ImageGallery/Views/ImageGalleryViewDetailPage.xaml.cs | 1,420 | C# |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System.Collections.Generic;
using System.Xml;
/// <summary>
/// Represents the UserProfilePicture.
/// </summary>
public sealed class UserProfilePicture : InsightValue
{
private string blob;
private string photoSize;
private string url;
private string imageType;
/// <summary>
/// Gets the Blob
/// </summary>
public string Blob
{
get
{
return this.blob;
}
set
{
this.SetFieldValue<string>(ref this.blob, value);
}
}
/// <summary>
/// Gets the PhotoSize
/// </summary>
public string PhotoSize
{
get
{
return this.photoSize;
}
set
{
this.SetFieldValue<string>(ref this.photoSize, value);
}
}
/// <summary>
/// Gets the Url
/// </summary>
public string Url
{
get
{
return this.url;
}
set
{
this.SetFieldValue<string>(ref this.url, value);
}
}
/// <summary>
/// Gets the ImageType
/// </summary>
public string ImageType
{
get
{
return this.imageType;
}
set
{
this.SetFieldValue<string>(ref this.imageType, value);
}
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">XML reader</param>
/// <returns>Whether the element was read</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.InsightSource:
this.InsightSource = reader.ReadElementValue<InsightSourceType>();
break;
case XmlElementNames.UpdatedUtcTicks:
this.UpdatedUtcTicks = reader.ReadElementValue<long>();
break;
case XmlElementNames.Blob:
this.Blob = reader.ReadElementValue();
break;
case XmlElementNames.PhotoSize:
this.PhotoSize = reader.ReadElementValue();
break;
case XmlElementNames.Url:
this.Url = reader.ReadElementValue();
break;
case XmlElementNames.ImageType:
this.ImageType = reader.ReadElementValue();
break;
default:
return false;
}
return true;
}
}
} | 29.964029 | 93 | 0.539976 | [
"MIT"
] | serious6/ews-managed-api | ComplexProperties/PeopleInsights/UserProfilePicture.cs | 4,165 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Background",
GUID = "8895582f-97ce-42f3-be8b-fb41ef933867",
Description = "Adds an image background to the current image.",
GroupName = Global.GroupName,
Order = 4)]
[Icon]
public class BackgroundBlock : ImageProcessorMethodBaseBlock
{
public virtual int X { get; set; }
public virtual int Y { get; set; }
public virtual int Width { get; set; }
public virtual int Height { get; set; }
public virtual int Opacity { get; set; }
[Display(Name = "Background image")]
public virtual string BackgroundImage { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Overlay(BackgroundImage, X, Y, Width, Height, Opacity);
}
public override void SetDefaultValues(ContentType contentType)
{
base.SetDefaultValues(contentType);
Opacity = 100;
}
}
} | 33.394737 | 78 | 0.661151 | [
"MIT"
] | ErikHen/ImageProcessor.Web.Episerver | src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/BackgroundBlock.cs | 1,271 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float _speed = 5f;
[SerializeField] private float _xClamp;
[SerializeField] private float _slowTime = 2f;
private Rigidbody2D _rbd;
void Start()
{
_rbd = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
float xMov = Input.GetAxis("Horizontal") * _speed * Time.fixedDeltaTime;
Vector2 newPos = _rbd.position + Vector2.right * xMov;
newPos.x = Mathf.Clamp(newPos.x, -_xClamp, _xClamp); // Clamping the player so it won't go out of play area
_rbd.MovePosition(newPos);
}
private void OnCollisionEnter2D(Collision2D other)
{
GameManager.Instance.GameOver();
//this.enabled = false;
}
}
| 23.783784 | 122 | 0.653409 | [
"MIT"
] | Crew7Studio/Dodge_The_Blocks | Dodge The Blocks/Assets/Scripts/PlayerController.cs | 882 | C# |
//Generated by LateBindingApi.CodeGenerator
using System;
using System.Runtime.InteropServices;
using NetOffice;
namespace NetOffice.MSHTMLApi
{
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersionAttribute("MSHTML", 4)]
[StructLayout(LayoutKind.Sequential, Pack=4), Guid("00000000-0000-0000-0000-000000000000")]
[EntityTypeAttribute(EntityType.IsStruct)]
public struct __MIDL___MIDL_itf_mshtml_0001_0042_0001
{
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersionAttribute("MSHTML", 4)]
[MarshalAs(UnmanagedType.BStr)]
public string lpReading;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersionAttribute("MSHTML", 4)]
[MarshalAs(UnmanagedType.BStr)]
public string lpWord;
}
} | 27.37931 | 92 | 0.732997 | [
"MIT"
] | brunobola/NetOffice | Source/MSHTML/Records/__MIDL___MIDL_itf_mshtml_0001_0042_0001.cs | 796 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using FluentAssertions;
using Nest;
using Tests.Core.Extensions;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.EndpointTests.TestState;
using static Nest.Infer;
namespace Tests.Aggregations.Metric.Average
{
public class AverageAggregationUsageTests : AggregationUsageTestBase
{
public AverageAggregationUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
protected override object AggregationJson => new
{
average_commits = new
{
meta = new
{
foo = "bar"
},
avg = new
{
field = "numberOfCommits",
missing = 10.0,
script = new
{
source = "_value * 1.2",
}
}
}
};
protected override Func<AggregationContainerDescriptor<Project>, IAggregationContainer> FluentAggs => a => a
.Average("average_commits", avg => avg
.Meta(m => m
.Add("foo", "bar")
)
.Field(p => p.NumberOfCommits)
.Missing(10)
.Script(ss => ss.Source("_value * 1.2"))
);
protected override AggregationDictionary InitializerAggs =>
new AverageAggregation("average_commits", Field<Project>(p => p.NumberOfCommits))
{
Meta = new Dictionary<string, object>
{
{ "foo", "bar" }
},
Missing = 10,
Script = new InlineScript("_value * 1.2")
};
protected override void ExpectResponse(ISearchResponse<Project> response)
{
response.ShouldBeValid();
var commitsAvg = response.Aggregations.Average("average_commits");
commitsAvg.Should().NotBeNull();
commitsAvg.Value.Should().BeGreaterThan(0);
commitsAvg.Meta.Should().NotBeNull().And.HaveCount(1);
commitsAvg.Meta["foo"].Should().Be("bar");
}
}
}
| 26.589041 | 110 | 0.687275 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | tests/Tests/Aggregations/Metric/Average/AverageAggregationUsageTests.cs | 1,941 | 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("Web.Configuration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Web.Configuration")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("180c50d8-d1ba-4ddb-a9da-739a74631c0f")]
// 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.891892 | 84 | 0.748217 | [
"MIT"
] | sourcewalker/hexago.net | Source/Web/Web.Configuration/Properties/AssemblyInfo.cs | 1,405 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/enums/conversion_custom_variable_status.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V10.Enums {
/// <summary>Holder for reflection information generated from google/ads/googleads/v10/enums/conversion_custom_variable_status.proto</summary>
public static partial class ConversionCustomVariableStatusReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v10/enums/conversion_custom_variable_status.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ConversionCustomVariableStatusReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CkZnb29nbGUvYWRzL2dvb2dsZWFkcy92MTAvZW51bXMvY29udmVyc2lvbl9j",
"dXN0b21fdmFyaWFibGVfc3RhdHVzLnByb3RvEh5nb29nbGUuYWRzLmdvb2ds",
"ZWFkcy52MTAuZW51bXMaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8i",
"lAEKIkNvbnZlcnNpb25DdXN0b21WYXJpYWJsZVN0YXR1c0VudW0ibgoeQ29u",
"dmVyc2lvbkN1c3RvbVZhcmlhYmxlU3RhdHVzEg8KC1VOU1BFQ0lGSUVEEAAS",
"CwoHVU5LTk9XThABEhUKEUFDVElWQVRJT05fTkVFREVEEAISCwoHRU5BQkxF",
"RBADEgoKBlBBVVNFRBAEQv0BCiJjb20uZ29vZ2xlLmFkcy5nb29nbGVhZHMu",
"djEwLmVudW1zQiNDb252ZXJzaW9uQ3VzdG9tVmFyaWFibGVTdGF0dXNQcm90",
"b1ABWkNnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fk",
"cy9nb29nbGVhZHMvdjEwL2VudW1zO2VudW1zogIDR0FBqgIeR29vZ2xlLkFk",
"cy5Hb29nbGVBZHMuVjEwLkVudW1zygIeR29vZ2xlXEFkc1xHb29nbGVBZHNc",
"VjEwXEVudW1z6gIiR29vZ2xlOjpBZHM6Okdvb2dsZUFkczo6VjEwOjpFbnVt",
"c2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V10.Enums.ConversionCustomVariableStatusEnum), global::Google.Ads.GoogleAds.V10.Enums.ConversionCustomVariableStatusEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V10.Enums.ConversionCustomVariableStatusEnum.Types.ConversionCustomVariableStatus) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum describing possible statuses of a conversion custom
/// variable.
/// </summary>
public sealed partial class ConversionCustomVariableStatusEnum : pb::IMessage<ConversionCustomVariableStatusEnum>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<ConversionCustomVariableStatusEnum> _parser = new pb::MessageParser<ConversionCustomVariableStatusEnum>(() => new ConversionCustomVariableStatusEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<ConversionCustomVariableStatusEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V10.Enums.ConversionCustomVariableStatusReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ConversionCustomVariableStatusEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ConversionCustomVariableStatusEnum(ConversionCustomVariableStatusEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ConversionCustomVariableStatusEnum Clone() {
return new ConversionCustomVariableStatusEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as ConversionCustomVariableStatusEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(ConversionCustomVariableStatusEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(ConversionCustomVariableStatusEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the ConversionCustomVariableStatusEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static partial class Types {
/// <summary>
/// Possible statuses of a conversion custom variable.
/// </summary>
public enum ConversionCustomVariableStatus {
/// <summary>
/// Not specified.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Used for return value only. Represents value unknown in this version.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// The conversion custom variable is pending activation and will not
/// accrue stats until set to ENABLED.
///
/// This status can't be used in CREATE and UPDATE requests.
/// </summary>
[pbr::OriginalName("ACTIVATION_NEEDED")] ActivationNeeded = 2,
/// <summary>
/// The conversion custom variable is enabled and will accrue stats.
/// </summary>
[pbr::OriginalName("ENABLED")] Enabled = 3,
/// <summary>
/// The conversion custom variable is paused and will not accrue stats
/// until set to ENABLED again.
/// </summary>
[pbr::OriginalName("PAUSED")] Paused = 4,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 40.73494 | 359 | 0.709948 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V10/Services/ConversionCustomVariableStatus.g.cs | 10,143 | C# |
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace AutoCRM
{
public class CrmFile
{
//Variáveis para a construção
private static int TableRows = 0;
private static int TableColumns;
private static string arq;
private static Excel.Application xlApp = new Excel.Application();
private static Excel.Workbook xlbook;
private static Excel._Worksheet xlsheets;
private static Excel.Range xlrange;
private static double PROVdata;
private static double PROVhorai = 0;
private static double PROVhoraf = 0;
private static string PROVdatafin;
private static string PROVdatain;
private static int aux;
/// <summary>
/// Informa o que está sendo lido na linha atual
/// </summary>
/// <returns></returns>
public static string ShowInformations()
{
return DateTime.FromOADate(PROVdata).ToShortDateString() + " " + V11BD.Cliente + " " + V11BD.Cliente_id + " " + V11BD.Problema + " " + V11BD.Solucao + " " + V11BD.Datainicio + " " + V11BD.Datafim + " " + V11BD.NumCRM;
}
/// <summary>
/// Carrega o Excel para aumentar o desempenho
/// deve ser usado quando sistema estiver inicializando para que o efeito esperado seda realizado
/// </summary>
public static void CreateXLSApp()
{
xlApp = new Excel.Application();
}
/// <summary>
/// fecha o arquvio excel e salva as alterações
/// </summary>
public static string CloseXLS()
{
try
{
xlbook.Save();
xlbook.Close(true);
Marshal.ReleaseComObject(xlApp);
Marshal.ReleaseComObject(xlbook);
Marshal.ReleaseComObject(xlsheets);
Marshal.ReleaseComObject(xlrange);
GC.Collect();
return "";
}
catch (Exception ex)
{
return ex.ToString();
}
}
/// <summary>
/// Cria as instruções necessárias para leitura do arquivo bem como a atribuição no valor
/// de requeridas variáveis
/// </summary>
/// <param name="arquivo"></param>
public static string SetFile(string arquivo)
{
arq = arquivo;
if (arq != null)
{
try
{
xlbook = xlApp.Workbooks.Open(arq, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", true, false, 0, false, 1, 0);
xlsheets = (Excel.Worksheet)xlbook.Worksheets.get_Item(1);
xlrange = xlsheets.UsedRange;
TableRows = 0;
TableColumns = 0;
for (int aux = 1; aux < xlrange.Rows.Count; aux++)
{
if ((xlrange.Cells[aux, 1] as Excel.Range).Value2 == null)
{
break;
}
else TableRows++;
}
TableColumns = xlrange.Columns.Count;
return "";
}
catch
{
return "Não foi possível abrir o arquivo selecionado. Verifique se ele está aberto em alguma estação de trabalho.";
}
}
else return " ";
}
/// <summary>
/// Tal método NÃO lê cada linha automaticamente. É preciso criar 2 for: O VALOR INICIAL DO FOR COM ROWS DEVE SER = 4, e o de Columns = 1.
/// Escrita: for(int r = 4; r (menor que) xlsRowsCount(); r++) {
/// for(int c = 4; c (menor que) xlsColumnsCount(); r++)
/// }
/// 1º for menor que xlsRowsCount()
/// 2º for menor que xlsColumnsCount().
/// </summary>
/// <param name="r">Valor atual de R dentro do for com comparação ao método xlsRowsCount()</param>
/// <param name="c">Valor atual de C dentro do for com comparação ao método xlsColumnsCount()</param>
/// <returns></returns>
public static string LerArquivoESalvarManual(int r)
{ //Arquivo Vazio
if (arq != null || arq != "")
{
//Lendo a primeira linha apenas
if (r == 1)
{
//Verificando nome do funcionário
if (Convert.ToString((xlrange.Cells[1, 1] as Excel.Range).Value2) != "")
{
V11BD.Funcionario = (xlrange.Cells[1, 1] as Excel.Range).Value2;
if (V11BD.GetFuncionario() == false) return "Funcionário não encontrado";
}
else
{
return "Nome do funcionário não informado";
}
//Verificando campo processo
if (Convert.ToString((xlrange.Cells[1, 10] as Excel.Range).Value2) != "")
{
try
{
V11BD.Processo = Convert.ToInt32((xlrange.Cells[1, 10] as Excel.Range).Value2);
if (V11BD.Processo != 3 && V11BD.Processo != 14) return "Valores inválidos para Nº do processo";
}
catch
{
return "VALOR INVÁLIDO PARA 'PROCESSO' [1,10] ACEITANDO os NÚMEROS 3 OU 8 APENAS";
}
}
else return "Processo não informado.";
}
else
{
//verificando se esse CRM já foi preenchido
if (Convert.ToString((xlrange.Cells[r, 10] as Excel.Range).Value2) == "" || Convert.ToString((xlrange.Cells[r, 10] as Excel.Range).Value2) == null)
{
//Verificando se a primeira linha é válida (data)
if (Convert.ToString((xlrange.Cells[r, 1] as Excel.Range).Value2) != null || Convert.ToString((xlrange.Cells[r, 1] as Excel.Range).Value2) == "")
{
//Data
try
{
PROVdata = ((xlrange.Cells[r, 1] as Excel.Range).Value2);
}
catch
{
return "VALOR INVÁLIDO PARA A COLUNA DATA NA LINHA " + r;
}
}
else
{
return "VALOR INVÁLIDO PARA A COLUNA DATA NA LINHA " + r;
}
//Hora inicial
if (Convert.ToString((xlrange.Cells[r, 2] as Excel.Range).Value2) == null || Convert.ToString((xlrange.Cells[r, 2] as Excel.Range).Value2) == "") return "CÉLULA DA COLUNA 'HORA INICIAL' NA LINHA " + r + " NÃO FOI PREENCHIDA.";
else
{
try
{
PROVhorai = (xlrange.Cells[r, 2] as Excel.Range).Value2;
}
catch
{
string aux = (xlrange.Cells[r, 2] as Excel.Range).Value2;
PROVdatain = DateTime.FromOADate(PROVdata).ToShortDateString() + " " + aux;
}
}
//Hora final
if (Convert.ToString((xlrange.Cells[r, 3] as Excel.Range).Value2) == null || Convert.ToString((xlrange.Cells[r, 3] as Excel.Range).Value2) == "") return "CÉLULA DA COLUNA 'HORA FINAL' NA LINHA " + r + " NÃO FOI PREENCHIDA.";
else
{
try
{
PROVhoraf = (xlrange.Cells[r, 3] as Excel.Range).Value2;
}
catch
{
string aux = (xlrange.Cells[r, 3] as Excel.Range).Value2;
PROVdatafin = DateTime.FromOADate(PROVdata).ToShortDateString() + " " + aux;
}
}
//Cliente
if ((xlrange.Cells[r, 4] as Excel.Range).Value2 == null || (xlrange.Cells[r, 4] as Excel.Range).Value2 == "") return "CÉLULA DA COLUNA 'CLIENTE' NA LINHA " + r + " NÃO PREENCHIDA";
else
{
V11BD.Cliente = (xlrange.Cells[r, 4] as Excel.Range).Value2;
}
//Cliente ID
if (Convert.ToString((xlrange.Cells[r, 5] as Excel.Range).Value2) == null || Convert.ToString((xlrange.Cells[r, 5] as Excel.Range).Value2) == "") return "CÉLULA DA COLUNA 'CLIENTE ID' NA LINHA " + r + " NÃO PREENCHIDA";
else
{
try
{
V11BD.Cliente_id = Convert.ToInt32((xlrange.Cells[r, 5] as Excel.Range).Value2);
}
catch
{
return "VALOR INVÁLIDO INFORMADO NO CAMPO 'CLIENTE_ID' NA LINHA " + r;
}
}
//Centro de Custo
if (Convert.ToString((xlrange.Cells[r, 6] as Excel.Range).Value2) == null || Convert.ToString((xlrange.Cells[r, 6] as Excel.Range).Value2) == "") return "CÉLULA DA COLUNA 'CENTRO.CUSTO' NA LINHA " + r + " NÃO PREENCHIDA";
else
{
try
{
V11BD.Centrodecusto = Convert.ToInt32((xlrange.Cells[r, 6] as Excel.Range).Value2);
}
catch
{
return "VALOR INVÁLIDO INFORMADO NO CAMPO 'CENTRO.CUSTO' NA LINHA " + r;
}
}
//Problema
if (Convert.ToString((xlrange.Cells[r, 7] as Excel.Range).Value2) == null || Convert.ToString((xlrange.Cells[r, 7] as Excel.Range).Value2) == "") return " CÉLULA DA COLUNA 'PROBLEMA' NA LINHA " + r + "NÃO FOI PREENCHIDA.";
else
{
V11BD.Problema = (xlrange.Cells[r, 7] as Excel.Range).Value2;
V11BD.Problema = V11BD.Problema.ToUpper();
}
//Solução
if (Convert.ToString((xlrange.Cells[r, 8] as Excel.Range).Value2) == null || Convert.ToString((xlrange.Cells[r, 8] as Excel.Range).Value2) == "") return "CÉLULA DA COLUNA 'SOLUÇÃO' NA LINHA " + r + " NÃO FOI PREENCHIDA.";
else
{
V11BD.Solucao = (xlrange.Cells[r, 8] as Excel.Range).Value2;
V11BD.Solucao = V11BD.Solucao.ToUpper();
}
//Tentativa de conversão das datas
try
{
PROVdatain = DateTime.FromOADate(PROVdata).ToShortDateString() + " " + DateTime.FromOADate(PROVhorai).ToShortTimeString();
PROVdatafin = DateTime.FromOADate(PROVdata).ToShortDateString() + " " + DateTime.FromOADate(PROVhoraf).ToShortTimeString();
V11BD.Datainicio = Convert.ToDateTime(PROVdatain);
V11BD.Datafim = Convert.ToDateTime(PROVdatafin);
}
catch
{
return "INFORMAÇÕES NA DATA HORA DA LINHA " + r + " NÃO FORAM INFORMADAS CORRETAMENTE";
}
}
else return "skip";
}
aux = r;
return "OK";
}
else return "Não há arquivo para leitura";
}
/// <summary>
/// Conta o número de linhas preenchidas com CRM parar lançar
/// </summary>
/// <returns></returns>
public static int xlsRowsCount()
{
return TableRows;
}
/// <summary>
/// fornece o número de CRM que estão no XLS
/// </summary>
/// <returns></returns>
public static int xlColumnsCount()
{
return TableColumns;
}
public static void InsertValueEXCEL()
{
if (aux > 3) xlsheets.Cells[aux, 10] = V11BD.NumCRM;
xlApp.DisplayAlerts = false;
xlbook.Save();
}
public static string ValidarArquivo()
{
//Pegando informações para validade do arquivo padrão
string n1 = Convert.ToString((xlrange.Cells[3, 1] as Excel.Range).Value2);//DATA
string n2 = Convert.ToString((xlrange.Cells[3, 2] as Excel.Range).Value2);//INICIO
string n3 = Convert.ToString((xlrange.Cells[3, 3] as Excel.Range).Value2);//FINAL
string n4 = Convert.ToString((xlrange.Cells[3, 4] as Excel.Range).Value2);//CLIENTE
string n5 = Convert.ToString((xlrange.Cells[3, 5] as Excel.Range).Value2);//COD.
string n6 = Convert.ToString((xlrange.Cells[3, 6] as Excel.Range).Value2);//C. CUSTO
string n7 = Convert.ToString((xlrange.Cells[3, 7] as Excel.Range).Value2);//PROBLEMA
string n8 = Convert.ToString((xlrange.Cells[3, 8] as Excel.Range).Value2);//SOLUÇÃO
string n10 = Convert.ToString((xlrange.Cells[3, 9] as Excel.Range).Value2);//TOTAL MIN
string n11 = Convert.ToString((xlrange.Cells[3, 10] as Excel.Range).Value2);// N° CRM
if (n1 == "DATA" && n2 == "INICIO" && n3 == "FINAL" && n4 == "CLIENTE" && n5 == "COD." && n6 == "C. CUSTO" && n7 == "PROBLEMA" && n8 == "SOLUÇÃO" && n10 == "TOTAL MIN" && n11 == "N° CRM") return "";
else return "Arquivo não compativel com o modelo padrão de cadastro de CRM";
}
}
}
| 48.594059 | 250 | 0.457349 | [
"MIT"
] | SieShow/Windows-Forms | AutoCRM/CrmFile.cs | 14,811 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.Staffing
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Stock_PlanObjectType : INotifyPropertyChanged
{
private Stock_PlanObjectIDType[] idField;
private string descriptorField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement("ID", Order = 0)]
public Stock_PlanObjectIDType[] ID
{
get
{
return this.idField;
}
set
{
this.idField = value;
this.RaisePropertyChanged("ID");
}
}
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string Descriptor
{
get
{
return this.descriptorField;
}
set
{
this.descriptorField = value;
this.RaisePropertyChanged("Descriptor");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 21.672131 | 136 | 0.729955 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.Staffing/Stock_PlanObjectType.cs | 1,322 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using Elastic.Apm.Config;
using Elastic.Apm.Helpers;
using Elastic.Apm.Metrics;
using Elastic.Apm.Metrics.MetricsProvider;
using Elastic.Apm.Tests.Utilities;
namespace Elastic.Apm.Benchmarks
{
[MemoryDiagnoser]
public class MetricsBenchmarks
{
private MetricsCollector _metricsCollector;
[GlobalSetup(Target = nameof(CollectAllMetrics2X))]
public void SetUpForAllMetrics()
{
var noopLogger = new NoopLogger();
var mockPayloadSender = new MockPayloadSender();
_metricsCollector = new MetricsCollector(noopLogger, mockPayloadSender, new ConfigurationStore(new MockConfiguration(noopLogger), noopLogger));
}
[GlobalCleanup(Target = nameof(CollectAllMetrics2X))]
public void CleanUpForAllMetrics()
=> _metricsCollector?.Dispose();
[Benchmark]
public void CollectAllMetrics2X()
{
_metricsCollector.CollectAllMetrics();
_metricsCollector.CollectAllMetrics();
}
[Benchmark]
public void CollectProcessTotalCpuTime2X()
{
var mockPayloadSender = new ProcessTotalCpuTimeProvider(new NoopLogger());
mockPayloadSender.GetSamples();
mockPayloadSender.GetSamples();
}
[Benchmark]
public void CollectTotalCpuTime2X()
{
var systemTotalCpuProvider = new SystemTotalCpuProvider(new NoopLogger());
systemTotalCpuProvider.GetSamples();
systemTotalCpuProvider.GetSamples();
}
[Benchmark]
public void CollectTotalAndFreeMemory2X()
{
var mockPayloadSender = new FreeAndTotalMemoryProvider( new List<WildcardMatcher>());
mockPayloadSender.GetSamples();
mockPayloadSender.GetSamples();
}
[Benchmark]
public void CollectWorkingSetAndVirMem2X()
{
var mockPayloadSender = new ProcessWorkingSetAndVirtualMemoryProvider(new List<WildcardMatcher>());
mockPayloadSender.GetSamples();
mockPayloadSender.GetSamples();
}
}
}
| 27.116883 | 146 | 0.772989 | [
"Apache-2.0"
] | SebastienDegodez/apm-agent-dotnet | test/Elastic.Apm.Benchmarks/MetricsBenchmarks.cs | 2,088 | C# |
using System;
using System.Linq.Expressions;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.VirtualRoutes;
using ShardingCore.Helpers;
using ShardingCore.Test5x.Common;
using ShardingCore.Test5x.Domain.Entities;
using ShardingCore.VirtualRoutes.Months;
namespace ShardingCore.Test5x.Shardings
{
public class MultiShardingOrderVirtualTableRoute:AbstractSimpleShardingMonthKeyDateTimeVirtualTableRoute<MultiShardingOrder>
{
public override void Configure(EntityMetadataTableBuilder<MultiShardingOrder> builder)
{
builder.ShardingProperty(o => o.CreateTime);
builder.ShardingExtraProperty(o => o.Id);
}
public override Expression<Func<string, bool>> GetExtraRouteFilter(object shardingKey, ShardingOperatorEnum shardingOperator, string shardingPropertyName)
{
switch (shardingPropertyName)
{
case nameof(MultiShardingOrder.Id): return GetIdRouteFilter(shardingKey, shardingOperator);
default: throw new NotImplementedException(shardingPropertyName);
}
}
private Expression<Func<string, bool>> GetIdRouteFilter(object shardingKey,
ShardingOperatorEnum shardingOperator)
{
//解析雪花id 需要考虑异常情况,传入的可能不是雪花id那么可以随机查询一张表
var analyzeIdToDateTime = SnowflakeId.AnalyzeIdToDateTime(Convert.ToInt64(shardingKey));
//当前时间的tail
var t = TimeFormatToTail(analyzeIdToDateTime);
//因为是按月分表所以获取下个月的时间判断id是否是在灵界点创建的
var nextMonthFirstDay = ShardingCoreHelper.GetNextMonthFirstDay(DateTime.Now);
if (analyzeIdToDateTime.AddSeconds(10) > nextMonthFirstDay)
{
var nextT = TimeFormatToTail(nextMonthFirstDay);
if (shardingOperator == ShardingOperatorEnum.Equal)
{
return tail => tail == t||tail== nextT;
}
}
var currentMonthFirstDay = ShardingCoreHelper.GetCurrentMonthFirstDay(DateTime.Now);
if (analyzeIdToDateTime.AddSeconds(-10) < currentMonthFirstDay)
{
//上个月tail
var nextT = TimeFormatToTail(analyzeIdToDateTime.AddSeconds(-10));
if (shardingOperator == ShardingOperatorEnum.Equal)
{
return tail => tail == t || tail == nextT;
}
}
else
{
if (shardingOperator == ShardingOperatorEnum.Equal)
{
return tail => tail == t;
}
}
return tail => true;
}
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 9, 1);
}
}
}
| 36.35 | 162 | 0.615543 | [
"Apache-2.0"
] | ChangYinHan/sharding-core | test/ShardingCore.Test5x/Shardings/MultiShardingOrderVirtualTableRoute.cs | 3,048 | 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 redshift-2012-12-01.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.Redshift.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Redshift.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for CreateAuthenticationProfile operation
/// </summary>
public class CreateAuthenticationProfileResponseUnmarshaller : XmlResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
CreateAuthenticationProfileResponse response = new CreateAuthenticationProfileResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.IsStartElement)
{
if(context.TestExpression("CreateAuthenticationProfileResult", 2))
{
UnmarshallResult(context, response);
continue;
}
if (context.TestExpression("ResponseMetadata", 2))
{
response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
}
}
}
return response;
}
private static void UnmarshallResult(XmlUnmarshallerContext context, CreateAuthenticationProfileResponse response)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("AuthenticationProfileContent", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.AuthenticationProfileContent = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("AuthenticationProfileName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.AuthenticationProfileName = unmarshaller.Unmarshall(context);
continue;
}
}
}
return;
}
/// <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(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("AuthenticationProfileAlreadyExistsFault"))
{
return AuthenticationProfileAlreadyExistsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("AuthenticationProfileQuotaExceededFault"))
{
return AuthenticationProfileQuotaExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidAuthenticationProfileRequestFault"))
{
return InvalidAuthenticationProfileRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonRedshiftException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static CreateAuthenticationProfileResponseUnmarshaller _instance = new CreateAuthenticationProfileResponseUnmarshaller();
internal static CreateAuthenticationProfileResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CreateAuthenticationProfileResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.245161 | 163 | 0.610452 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Redshift/Generated/Model/Internal/MarshallTransformations/CreateAuthenticationProfileResponseUnmarshaller.cs | 6,238 | 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;
using System.Threading.Tasks;
using NuGet.Jobs.Validation.Symbols.Core;
using NuGet.Services.ServiceBus;
namespace NuGet.Services.Validation.Symbols
{
public class SymbolsIngesterMessageEnqueuer : ISymbolsIngesterMessageEnqueuer
{
private readonly ITopicClient _topicClient;
private readonly TimeSpan? _messageDelay;
private readonly IBrokeredMessageSerializer<SymbolsIngesterMessage> _serializer;
public SymbolsIngesterMessageEnqueuer(
ITopicClient topicClient,
IBrokeredMessageSerializer<SymbolsIngesterMessage> serializer,
TimeSpan? messageDelay)
{
_topicClient = topicClient ?? throw new ArgumentNullException(nameof(topicClient));
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
_messageDelay = messageDelay;
}
public async Task<SymbolsIngesterMessage> EnqueueSymbolsIngestionMessageAsync(IValidationRequest request)
{
var message = new SymbolsIngesterMessage(validationId: request.ValidationId,
symbolPackageKey: request.PackageKey,
packageId: request.PackageId,
packageNormalizedVersion: request.PackageVersion,
snupkgUrl: request.NupkgUrl,
requestName : SymbolsValidationEntitiesService.CreateSymbolServerRequestNameFromValidationRequest(request));
var brokeredMessage = _serializer.Serialize(message);
var visibleAt = DateTimeOffset.UtcNow + (_messageDelay ?? TimeSpan.Zero);
brokeredMessage.ScheduledEnqueueTimeUtc = visibleAt;
await _topicClient.SendAsync(brokeredMessage);
return message;
}
}
}
| 43.044444 | 124 | 0.710893 | [
"Apache-2.0"
] | fredatgithub/NuGet.Jobs | src/NuGet.Services.Validation.Orchestrator/Symbols/SymbolsIngesterMessageEnqueuer.cs | 1,939 | C# |
namespace Parametre_sys_Helper
{
partial class ConfigForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.scPanels = new System.Windows.Forms.SplitContainer();
this.tvParametre = new System.Windows.Forms.TreeView();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.générerLeCodeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.developpéParYassinLOKHATToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.scPanels)).BeginInit();
this.scPanels.Panel1.SuspendLayout();
this.scPanels.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// scPanels
//
this.scPanels.Dock = System.Windows.Forms.DockStyle.Fill;
this.scPanels.Location = new System.Drawing.Point(0, 24);
this.scPanels.Name = "scPanels";
//
// scPanels.Panel1
//
this.scPanels.Panel1.Controls.Add(this.tvParametre);
this.scPanels.Size = new System.Drawing.Size(800, 487);
this.scPanels.SplitterDistance = 224;
this.scPanels.SplitterWidth = 5;
this.scPanels.TabIndex = 0;
//
// tvParametre
//
this.tvParametre.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvParametre.FullRowSelect = true;
this.tvParametre.HideSelection = false;
this.tvParametre.Location = new System.Drawing.Point(0, 0);
this.tvParametre.Name = "tvParametre";
this.tvParametre.PathSeparator = " \\ ";
this.tvParametre.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tvParametre.Size = new System.Drawing.Size(224, 487);
this.tvParametre.TabIndex = 0;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.générerLeCodeToolStripMenuItem,
this.developpéParYassinLOKHATToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(800, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// générerLeCodeToolStripMenuItem
//
this.générerLeCodeToolStripMenuItem.Name = "générerLeCodeToolStripMenuItem";
this.générerLeCodeToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F5;
this.générerLeCodeToolStripMenuItem.Size = new System.Drawing.Size(101, 20);
this.générerLeCodeToolStripMenuItem.Text = "Générer le code";
this.générerLeCodeToolStripMenuItem.Click += new System.EventHandler(this.générerLeCodeToolStripMenuItem_Click);
//
// developpéParYassinLOKHATToolStripMenuItem
//
this.developpéParYassinLOKHATToolStripMenuItem.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.developpéParYassinLOKHATToolStripMenuItem.Name = "developpéParYassinLOKHATToolStripMenuItem";
this.developpéParYassinLOKHATToolStripMenuItem.Size = new System.Drawing.Size(178, 20);
this.developpéParYassinLOKHATToolStripMenuItem.Text = "Developpé par Yassin LOKHAT";
this.developpéParYassinLOKHATToolStripMenuItem.Click += new System.EventHandler(this.developpéParYassinLOKHATToolStripMenuItem_Click);
//
// ConfigForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 511);
this.Controls.Add(this.scPanels);
this.Controls.Add(this.menuStrip1);
this.DoubleBuffered = true;
this.MinimumSize = new System.Drawing.Size(800, 550);
this.Name = "ConfigForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "ConfigForm";
this.scPanels.Panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.scPanels)).EndInit();
this.scPanels.ResumeLayout(false);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.SplitContainer scPanels;
private System.Windows.Forms.TreeView tvParametre;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem générerLeCodeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem developpéParYassinLOKHATToolStripMenuItem;
}
} | 47.304 | 146 | 0.628277 | [
"Apache-2.0"
] | YassinLokhat/Parametre_sys_Helper | Parametre_sys_Helper/ConfigForm.Designer.cs | 5,951 | C# |
using System;
using System.Threading;
using Avalonia;
using GitHub.UI.Controls;
using GitHub.UI.Commands;
using Microsoft.Git.CredentialManager;
using Microsoft.Git.CredentialManager.UI;
namespace GitHub.UI
{
public static class Program
{
public static void Main(string[] args)
{
// If we have no arguments then just start the app with the test window.
if (args.Length == 0)
{
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
return;
}
// Create the dispatcher on the main thread. This is required
// for some platform UI services such as macOS that mandates
// all controls are created/accessed on the initial thread
// created by the process (the process entry thread).
Dispatcher.Initialize();
// Run AppMain in a new thread and keep the main thread free
// to process the dispatcher's job queue.
var appMain = new Thread(AppMain) {Name = nameof(AppMain)};
appMain.Start(args);
// Process the dispatcher job queue (aka: message pump, run-loop, etc...)
// We must ensure to run this on the same thread that it was created on
// (the main thread) so we cannot use any async/await calls between
// Dispatcher.Create and Run.
Dispatcher.MainThread.Run();
// Execution should never reach here as AppMain terminates the process on completion.
throw new InvalidOperationException("Main dispatcher job queue shutdown unexpectedly");
}
private static void AppMain(object o)
{
string[] args = (string[]) o;
string appPath = ApplicationBase.GetEntryApplicationPath();
using (var context = new CommandContext(appPath))
using (var app = new HelperApplication(context))
{
app.RegisterCommand(new CredentialsCommandImpl(context));
app.RegisterCommand(new TwoFactorCommandImpl(context));
int exitCode = app.RunAsync(args)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
Environment.Exit(exitCode);
}
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure(() => new AvaloniaApp(() => new TesterWindow()))
.UsePlatformDetect()
.LogToTrace();
}
}
| 36.942029 | 99 | 0.593174 | [
"MIT"
] | nimatt/Git-Credential-Manager-Core | src/shared/GitHub.UI.Avalonia/Program.cs | 2,551 | C# |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Windows.Forms;
using MaterialSkin.Animations;
namespace MaterialSkin.Controls
{
public class MaterialRadioButton : RadioButton, IMaterialControl
{
[Browsable(false)]
public int Depth { get; set; }
[Browsable(false)]
public MaterialSkinManager SkinManager => MaterialSkinManager.Instance;
[Browsable(false)]
public MouseState MouseState { get; set; }
[Browsable(false)]
public Point MouseLocation { get; set; }
private bool ripple;
[Category("Behavior")]
public bool Ripple
{
get { return ripple; }
set
{
ripple = value;
AutoSize = AutoSize; //Make AutoSize directly set the bounds.
if (value)
{
Margin = new Padding(0);
}
Invalidate();
}
}
// animation managers
private readonly AnimationManager _animationManager;
private readonly AnimationManager _rippleAnimationManager;
// size related variables which should be recalculated onsizechanged
private Rectangle _radioButtonBounds;
private int _boxOffset;
// size constants
private const int RADIOBUTTON_SIZE = 19;
private const int RADIOBUTTON_SIZE_HALF = RADIOBUTTON_SIZE / 2;
private const int RADIOBUTTON_OUTER_CIRCLE_WIDTH = 2;
private const int RADIOBUTTON_INNER_CIRCLE_SIZE = RADIOBUTTON_SIZE - (2 * RADIOBUTTON_OUTER_CIRCLE_WIDTH);
public MaterialRadioButton()
{
SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer, true);
_animationManager = new AnimationManager
{
AnimationType = AnimationType.EaseInOut,
Increment = 0.06
};
_rippleAnimationManager = new AnimationManager(false)
{
AnimationType = AnimationType.Linear,
Increment = 0.10,
SecondaryIncrement = 0.08
};
_animationManager.OnAnimationProgress += sender => Invalidate();
_rippleAnimationManager.OnAnimationProgress += sender => Invalidate();
CheckedChanged += (sender, args) => _animationManager.StartNewAnimation(Checked ? AnimationDirection.In : AnimationDirection.Out);
SizeChanged += OnSizeChanged;
Ripple = true;
MouseLocation = new Point(-1, -1);
}
private void OnSizeChanged(object sender, EventArgs eventArgs)
{
_boxOffset = Height / 2 - (int)Math.Ceiling(RADIOBUTTON_SIZE / 2d);
_radioButtonBounds = new Rectangle(_boxOffset, _boxOffset, RADIOBUTTON_SIZE, RADIOBUTTON_SIZE);
}
public override Size GetPreferredSize(Size proposedSize)
{
var width = _boxOffset + 20 + (int)CreateGraphics().MeasureString(Text, SkinManager.ROBOTO_MEDIUM_10).Width;
return Ripple ? new Size(width, 30) : new Size(width, 20);
}
protected override void OnPaint(PaintEventArgs pevent)
{
var g = pevent.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
// clear the control
g.Clear(Parent.BackColor);
var RADIOBUTTON_CENTER = _boxOffset + RADIOBUTTON_SIZE_HALF;
var animationProgress = _animationManager.GetProgress();
int colorAlpha = Enabled ? (int)(animationProgress * 255.0) : SkinManager.GetCheckBoxOffDisabledColor().A;
int backgroundAlpha = Enabled ? (int)(SkinManager.GetCheckboxOffColor().A * (1.0 - animationProgress)) : SkinManager.GetCheckBoxOffDisabledColor().A;
float animationSize = (float)(animationProgress * 8f);
float animationSizeHalf = animationSize / 2;
animationSize = (float)(animationProgress * 9f);
var brush = new SolidBrush(Color.FromArgb(colorAlpha, Enabled ? SkinManager.ColorScheme.DarkPrimaryColor : SkinManager.GetCheckBoxOffDisabledColor()));
var pen = new Pen(brush.Color);
// draw ripple animation
if (Ripple && _rippleAnimationManager.IsAnimating())
{
for (var i = 0; i < _rippleAnimationManager.GetAnimationCount(); i++)
{
var animationValue = _rippleAnimationManager.GetProgress(i);
var animationSource = new Point(RADIOBUTTON_CENTER, RADIOBUTTON_CENTER);
var rippleBrush = new SolidBrush(Color.FromArgb((int)((animationValue * 40)), ((bool)_rippleAnimationManager.GetData(i)[0]) ? Color.Black : brush.Color));
var rippleHeight = (Height % 2 == 0) ? Height - 3 : Height - 2;
var rippleSize = (_rippleAnimationManager.GetDirection(i) == AnimationDirection.InOutIn) ? (int)(rippleHeight * (0.8d + (0.2d * animationValue))) : rippleHeight;
using (var path = DrawHelper.CreateRoundRect(animationSource.X - rippleSize / 2, animationSource.Y - rippleSize / 2, rippleSize, rippleSize, rippleSize / 2))
{
g.FillPath(rippleBrush, path);
}
rippleBrush.Dispose();
}
}
// draw radiobutton circle
Color uncheckedColor = DrawHelper.BlendColor(Parent.BackColor, Enabled ? SkinManager.GetCheckboxOffColor() : SkinManager.GetCheckBoxOffDisabledColor(), backgroundAlpha);
using (var path = DrawHelper.CreateRoundRect(_boxOffset, _boxOffset, RADIOBUTTON_SIZE, RADIOBUTTON_SIZE, 9f))
{
g.FillPath(new SolidBrush(uncheckedColor), path);
if (Enabled)
{
g.FillPath(brush, path);
}
}
g.FillEllipse(
new SolidBrush(Parent.BackColor),
RADIOBUTTON_OUTER_CIRCLE_WIDTH + _boxOffset,
RADIOBUTTON_OUTER_CIRCLE_WIDTH + _boxOffset,
RADIOBUTTON_INNER_CIRCLE_SIZE,
RADIOBUTTON_INNER_CIRCLE_SIZE);
if (Checked)
{
using (var path = DrawHelper.CreateRoundRect(RADIOBUTTON_CENTER - animationSizeHalf, RADIOBUTTON_CENTER - animationSizeHalf, animationSize, animationSize, 4f))
{
g.FillPath(brush, path);
}
}
SizeF stringSize = g.MeasureString(Text, SkinManager.ROBOTO_MEDIUM_10);
g.DrawString(Text, SkinManager.ROBOTO_MEDIUM_10, Enabled ? SkinManager.GetPrimaryTextBrush() : SkinManager.GetDisabledOrHintBrush(), _boxOffset + 22, Height / 2 - stringSize.Height / 2);
brush.Dispose();
pen.Dispose();
}
private bool IsMouseInCheckArea()
{
return _radioButtonBounds.Contains(MouseLocation);
}
protected override void OnCreateControl()
{
base.OnCreateControl();
Font = SkinManager.ROBOTO_MEDIUM_10;
if (DesignMode) return;
MouseState = MouseState.OUT;
MouseEnter += (sender, args) =>
{
MouseState = MouseState.HOVER;
};
MouseLeave += (sender, args) =>
{
MouseLocation = new Point(-1, -1);
MouseState = MouseState.OUT;
};
MouseDown += (sender, args) =>
{
MouseState = MouseState.DOWN;
if (Ripple && args.Button == MouseButtons.Left && IsMouseInCheckArea())
{
_rippleAnimationManager.SecondaryIncrement = 0;
_rippleAnimationManager.StartNewAnimation(AnimationDirection.InOutIn, new object[] { Checked });
}
};
MouseUp += (sender, args) =>
{
MouseState = MouseState.HOVER;
_rippleAnimationManager.SecondaryIncrement = 0.08;
};
MouseMove += (sender, args) =>
{
MouseLocation = args.Location;
Cursor = IsMouseInCheckArea() ? Cursors.Hand : Cursors.Default;
};
}
}
}
| 40.15566 | 198 | 0.587572 | [
"MIT"
] | jokidz90/MaterialSkin | MaterialSkin/Controls/MaterialRadioButton.cs | 8,515 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Desk.Gist.API.System.Linq.Enumerable
{
public class ToLookUpGist
{
class Package
{
public string Company { get; set; }
public double Weight { get; set; }
public long TrackingNumber { get; set; }
}
public static void ToLookupGist()
{
// Create a list of Packages.
List<Package> packages =
new List<Package>
{ new Package { Company = "Coho Vineyard",
Weight = 25.2, TrackingNumber = 89453312L },
new Package { Company = "Lucerne Publishing",
Weight = 18.7, TrackingNumber = 89112755L },
new Package { Company = "Wingtip Toys",
Weight = 6.0, TrackingNumber = 299456122L },
new Package { Company = "Contoso Pharmaceuticals",
Weight = 9.3, TrackingNumber = 670053128L },
new Package { Company = "Wide World Importers",
Weight = 33.8, TrackingNumber = 4665518773L } };
// Create a Lookup to organize the packages.
// Use the first character of Company as the key value.
// Select Company appended to TrackingNumber
// as the element values of the Lookup.
ILookup<char, string> lookup =
packages
.ToLookup(p => Convert.ToChar(p.Company.Substring(0, 1)),
p => p.Company + " " + p.TrackingNumber);
// Iterate through each IGrouping in the Lookup.
foreach (IGrouping<char, string> packageGroup in lookup)
{
// Print the key value of the IGrouping.
Console.WriteLine(packageGroup.Key);
// Iterate through each value in the
// IGrouping and print its value.
foreach (string str in packageGroup)
Console.WriteLine(" {0}", str);
}
}
public static void ToLookupGist2()
{
var ticketlist = GetList();
var dic = ticketlist.ToLookup(i => i.OrderID);
foreach (var item in dic)
{
Console.WriteLine("订单号:" + item.Key);
foreach (var item1 in item)
{
Console.WriteLine("\t\t" + item1.TicketNo + " " + item1.Description);
}
}
}
private static List<Ticket> GetList()
{
return new List<Ticket>()
{
new Ticket(){ TicketNo="999-12311",OrderID=79121281,Description="改签"},
new Ticket(){ TicketNo="999-24572",OrderID=29321289,Description="退票"},
new Ticket(){ TicketNo="999-68904",OrderID=19321289,Description="成交"},
new Ticket(){ TicketNo="999-24172",OrderID=64321212,Description="未使用"},
new Ticket(){ TicketNo="999-24579",OrderID=19321289,Description="退票"},
new Ticket(){ TicketNo="999-21522",OrderID=79121281,Description="未使用"},
new Ticket(){ TicketNo="999-24902",OrderID=79121281,Description="退票"},
new Ticket(){ TicketNo="999-04571",OrderID=29321289,Description="改签"},
new Ticket(){ TicketNo="999-23572",OrderID=96576289,Description="改签"},
new Ticket(){ TicketNo="999-24971",OrderID=99321289,Description="成交"}
};
}
class Ticket
{
/// <summary>
/// 票号
/// </summary>
public string TicketNo { get; set; }
/// <summary>
/// 订单号
/// </summary>
public int OrderID { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Description { get; set; }
}
}
}
| 38.461538 | 90 | 0.51425 | [
"MIT"
] | zhaobingwang/Desk | Gist/src/Desk.Gist/API/System/Linq/Enumerable/ToLookUpGist.cs | 4,066 | C# |
namespace TaxiDinamica.Web.Tests
{
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
public class SeleniumServerFactory<TStartup> : WebApplicationFactory<TStartup>
where TStartup : class
{
private readonly Process process;
private IWebHost host;
public SeleniumServerFactory()
{
this.ClientOptions.BaseAddress = new Uri("https://localhost"); // will follow redirects by default
this.process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "selenium-standalone",
Arguments = "start",
UseShellExecute = true,
},
};
this.process.Start();
}
public string RootUri { get; set; } // Save this use by tests
protected override TestServer CreateServer(IWebHostBuilder builder)
{
// Real TCP port
this.host = builder.Build();
this.host.Start();
this.RootUri = this.host.ServerFeatures.Get<IServerAddressesFeature>().Addresses.LastOrDefault(); // Last is https://localhost:5001!
// Fake Server we won't use...this is lame. Should be cleaner, or a utility class
return new TestServer(new WebHostBuilder().UseStartup<FakeStartup>());
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.host.Dispose();
this.process.CloseMainWindow(); // Be sure to stop Selenium Standalone
}
}
public class FakeStartup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure()
{
}
}
}
}
| 32.309859 | 144 | 0.536181 | [
"MIT"
] | jarvandev/cero-filas | src/Tests/TaxiDinamica.Web.Tests/SeleniumServerFactory.cs | 2,296 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace AssistidCollector1.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, UIWindow forWindow)
{
return UIInterfaceOrientationMask.Portrait;
//return UIInterfaceOrientationMask.PortraitUpsideDown;
}
}
}
| 36.473684 | 131 | 0.691198 | [
"MIT"
] | miyamot0/AssistidCollector1 | AssistidCollector1/AssistidCollector1.iOS/AppDelegate.cs | 1,388 | C# |
using Godot;
using System;
public class GraphBullet : Bullet
{
protected float amplitude = 100.0f;
protected float frequency = 10.0f;
protected float phase = 0.0f;
private bool textureRotating = true;
private Vector2 startPos;
private Vector2 startDir;
protected float speed;
public GraphBullet() { }
public GraphBullet(float[] additionalArgs) : base(additionalArgs)
{
amplitude = additionalArgs[0];
frequency = additionalArgs[1];
phase = additionalArgs[2];
textureRotating = Convert.ToBoolean(additionalArgs[3]);
}
public override void Process(float delta)
{
Vector2 oldPosition = position;
position = startPos + speed * startDir * currentTime + startDir.Rotated(Mathf.Pi/2)*amplitude*getFunctionResult();
if (textureRotating) rotation = (position-oldPosition).Angle();
}
public virtual float getFunctionResult() {
return 0.0f;
}
public override void Ready()
{
base.Ready();
startPos = position;
startDir = velocity.Normalized();
speed = velocity.Length();
}
} | 29.868421 | 122 | 0.651982 | [
"MIT"
] | bogi000/bullet-hell-test | bullets/types/GraphBullet.cs | 1,135 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using TMPro;
public class Movin : MonoBehaviour
{
NavMeshAgent agent;
public Transform spot;
private Vector3 destination = new Vector3(0,0,0);
private Vector3 destinationToo = Vector3.zero;
public float energy;
//timer stuffsa
private float timer = 0;
private float timerCheck = 0;
public float TimeTillSpwn = 5f;
public float pos;
public float food;
public GameObject agent1;
//for more clones
private float corner1;
private float pos1;
public bool live;
//how many mans counter
public float people;
public TextMeshProUGUI countText;
// Start is called before the first frame update
void Start()
{
people = GameObject.FindGameObjectsWithTag("Player").Length;
food = 0;
population();
}
// Update is called once per frame
void Update()
{
if (energy >= 3){
randoSpot();
}
if (energy <= 2){
spawn();
}
timer += Time.deltaTime;
if (timer >= TimeTillSpwn && energy > 0)
{
timer = 0;
moving();
energy--;
}
if (energy == 0){
parent();
}
if (live == true){
reset();
}
people = GameObject.FindGameObjectsWithTag("Player").Length;
population();
}
void randoSpot(){
var destination = new Vector3(Random.Range(-11f,11f), 0.5f, Random.Range(-11f,11f));
if (energy <= 3){
spawn();
}
spot.position = destination;
}
void moving(){
agent = this.GetComponent<NavMeshAgent>();
agent.SetDestination(spot.position);
}
void spawn ()
{
var corner = Random.value;
pos = Random.Range(-11.5f,11.5f);
if (corner >= .75){
var destination = new Vector3(11f, 0.5f, pos);
spot.position = destination;
}
if (corner < .75 && corner >= .5){
var destination = new Vector3(-11F, 0.5f, pos);
spot.position = destination;
}
if (corner < .5 && corner >= .25){
var destination = new Vector3(pos, 0.5f, 11f);
spot.position = destination;
}
if (corner < .25){
var destination = new Vector3(pos, 0.5f, -11f);
spot.position = destination;
}
}
void OnTriggerEnter(Collider other)
{
Debug.Log("I hit stuff");
if(other.gameObject.CompareTag ("food")) {
food = food + 1;
other.gameObject.SetActive (false);
}
}
void parent(){
timerCheck += Time.deltaTime;
if (timerCheck >= 8 && live == false)
{
//if no food
if (food == 0){
people = people - 1;
population();
agent1.SetActive(false);
}
if (food == 1){
live = true;
food = 0;
}
//mucho food
if (food >= 2){
live = true;
egg();
reset();
food = 0;
}
}
}
void egg ()
{
//clones the agent
corner1 = Random.value;
people = people + 1;
pos1 = Random.Range(-11.5f,11.5f);
if (corner1 >= .75){
Instantiate(agent, new Vector3(11f, 0.5f, pos1), Quaternion.identity);
}
if (corner1 < .75 && corner1 >= .5){
Instantiate(agent, new Vector3(-11F, 0.5f, pos1), Quaternion.identity);
}
if (corner1 < .5 && corner1 >= .25){
Instantiate(agent, new Vector3(pos1, 0.5f, 11f), Quaternion.identity);
}
if (corner1 > .25){
Instantiate(agent, new Vector3(pos1, 0.5f, -11f), Quaternion.identity);
}
}
void reset()
{
live = false;
energy = 4;
}
void population()
{
countText.text = "population: " + people.ToString();
}
}
| 24.593583 | 93 | 0.450098 | [
"MIT"
] | Kingkiwwi/evolution-git | Evolution/Assets/Code/Movin.cs | 4,599 | C# |
namespace FastFood.Web.Controllers
{
using Microsoft.AspNetCore.Mvc;
using System;
using AutoMapper;
using System.Linq;
using AutoMapper.QueryableExtensions;
using Data;
using FastFood.Models;
using ViewModels.Employees;
public class EmployeesController : Controller
{
private readonly FastFoodContext context;
private readonly IMapper mapper;
public EmployeesController(FastFoodContext context, IMapper mapper)
{
this.context = context;
this.mapper = mapper;
}
//GET
public IActionResult Register()
{
var positions = this.context
.Positions
.ProjectTo<RegisterEmployeeViewModel>(this.mapper.ConfigurationProvider)
.ToList();
return this.View(positions);
}
//POST
[HttpPost]
public IActionResult Register(RegisterEmployeeInputModel model)
{
if (!ModelState.IsValid)
{
return this.RedirectToAction("Error", "Home");
}
var employee = this.mapper.Map<Employee>(model);
this.context.Employees.Add(employee);
this.context.SaveChanges();
return this.RedirectToAction("All", "Employees");
}
public IActionResult All()
{
var employees = this.context
.Employees
.ProjectTo<EmployeesAllViewModel>(this.mapper.ConfigurationProvider)
.ToList();
return this.View(employees);
}
}
}
| 25.46875 | 88 | 0.574233 | [
"MIT"
] | bodyquest/SoftwareUniversity-Bulgaria | Entity Framework Core Oct2019/7.Auto Mapping Objects/AutoMappingObjects-Exercise/FastFood.Web/Controllers/EmployeesController.cs | 1,632 | C# |
//*********************************************************************
//Docify
//Copyright(C) 2020 Xarial Pty Limited
//Product URL: https://docify.net
//License: https://docify.net/license/
//*********************************************************************
using System;
namespace Xarial.Docify.Core.Exceptions
{
public class LibraryItemLoadException : UserMessageException
{
public LibraryItemLoadException(string itemName, string loc, Exception inner)
: base($"Failed to load library item: '{itemName}' from '{loc}'", inner)
{
}
}
}
| 29.7 | 85 | 0.510101 | [
"MIT"
] | EddyAlleman/docify | src/Core/Exceptions/LibraryItemLoadException.cs | 596 | C# |
using System;
using HotChocolate;
using Nikcio.UHeadless.UmbracoElements.Properties.Bases.Models;
using Nikcio.UHeadless.UmbracoElements.Properties.Commands;
namespace Nikcio.UHeadless.UmbracoElements.Properties.EditorsValues.DatePicker.Models {
/// <summary>
/// Represents a date time property value
/// </summary>
[GraphQLDescription("Represents a date time property value.")]
public class BasicDateTimePicker : PropertyValue {
/// <summary>
/// Gets the value of the property
/// </summary>
[GraphQLDescription("Gets the value of the property.")]
public virtual DateTime? Value { get; set; }
/// <inheritdoc/>
public BasicDateTimePicker(CreatePropertyValue createPropertyValue) : base(createPropertyValue) {
var value = createPropertyValue.Property.GetValue(createPropertyValue.Culture);
if (value != null) {
Value = (DateTime) value;
if (Value == default(DateTime)) {
Value = null;
}
}
}
}
}
| 36.4 | 105 | 0.634615 | [
"MIT"
] | nikcio/Nikcio.UHeadless | src/Nikcio.UHeadless/UmbracoElements/Properties/EditorsValues/DateTimePicker/Models/BasicDateTimePicker.cs | 1,094 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2018 Bambora, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using Newtonsoft.Json;
/// <summary>
/// Details on a transaction that has been adjusted.
/// </summary>
namespace Bambora.NA.SDK
{
public class Adjustment
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "approval")]
public string Approval { get; set; }
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
[JsonProperty(PropertyName = "amount")]
public string Amount { get; set; }
[JsonProperty(PropertyName = "created")]
public DateTime Created { get; set; }
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
}
} | 35.8 | 80 | 0.691722 | [
"MIT"
] | TacitInnovations/bambora-na-dotnet | BamboraSDK/Domain/Adjustment.cs | 1,971 | C# |
using System.Data.Entity;
using Moe.Lib.Data;
namespace Jinyinmao.MessageWorker.Domain.Entity
{
/// <summary>
/// SmsMessageDbContext. This class cannot be inherited.
/// </summary>
public sealed class SmsMessageDbContext : DbContextBase
{
/// <summary>
/// Initializes a new instance of the <see cref="SmsMessageDbContext"/> class.
/// </summary>
public SmsMessageDbContext()
: base("name=SmsMessageDbContext")
{
}
/// <summary>
/// Gets or sets the SMS messages.
/// </summary>
/// <value>The SMS messages.</value>
public DbSet<SmsMessage> SmsMessages { get; set; }
/// <summary>
/// Called when [model creating].
/// </summary>
/// <param name="modelBuilder">The model builder.</param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new SmsMessageMap());
}
}
} | 29.823529 | 86 | 0.588757 | [
"MIT"
] | QiuRyan/Bak | Goverment/MessageManager/Source/MessageWorker.Domain.Entity/SmsMessageDbContext.cs | 1,014 | C# |
using Neutronium.Core.Infra;
using Neutronium.Core.Navigation;
using Neutronium.Core.WebBrowserEngine.JavascriptObject;
using Neutronium.MVVMComponents;
using Neutronium.MVVMComponents.Relay;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Neutronium.BuildingBlocks.SetUp
{
/// <summary>
/// Set-up viewModel
/// </summary>
public class SetUpViewModel : IDisposable
{
/// <summary>
/// View uri
/// </summary>
public Uri Uri => _ApplicationSetUp.Uri;
/// <summary>
/// True if debug mode
/// </summary>
public bool Debug => _ApplicationSetUp.Debug;
/// <summary>
/// Application mode
/// </summary>
public ApplicationMode Mode => _ApplicationSetUp.Mode;
/// <summary>
/// Commands to be injected to the Neutronium components
/// Including "To Live" and "Reload" commands
/// </summary>
public IDictionary<string, ICommand<ICompleteWebViewComponent>> DebugCommands { get; } = new Dictionary<string, ICommand<ICompleteWebViewComponent>>();
private readonly ApplicationSetUpBuilder _Builder;
private ApplicationSetUp _ApplicationSetUp;
public SetUpViewModel(ApplicationSetUpBuilder builder)
{
_Builder = builder;
}
private async void GoLive(ICompleteWebViewComponent viewControl)
{
await ChangeMode(viewControl, ApplicationMode.Live, "to live");
}
private async Task ChangeMode(IWebViewComponent viewControl, ApplicationMode destination, string change)
{
if (Mode == destination)
return;
var resourceLoader = GetResourceReader();
var createOverlay = resourceLoader.Load("loading.js");
viewControl.ExecuteJavascript(createOverlay);
var cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;
DebugCommands.Clear();
DebugCommands[$"Cancel {change}"] = new RelayToogleCommand<ICompleteWebViewComponent>
(_ =>
{
cancellationTokenSource.Cancel();
UpdateCommands();
});
try
{
await Task.Run(() => DoChange(viewControl, destination, token), token);
}
catch (TaskCanceledException)
{
var removeOverlay = resourceLoader.Load("removeOverlay.js");
viewControl.ExecuteJavascript(removeOverlay);
return;
}
await viewControl.SwitchViewAsync(Uri);
}
private async Task DoChange(IWebViewComponent viewControl, ApplicationMode destination, CancellationToken token)
{
var resourceLoader = GetResourceReader();
var updateOverlay = resourceLoader.Load("update.js");
void OnNpmLog(string information)
{
if (information == null)
return;
var text = JavascriptNamer.GetCreateExpression(information);
var code = updateOverlay.Replace("{information}", text);
viewControl.ExecuteJavascript(code);
}
UpdateSetUp(await _Builder.BuildFromMode(destination, token, OnNpmLog));
}
private ResourceReader GetResourceReader() => new ResourceReader("script", this);
public async Task InitFromArgs(string[] args)
{
var setup = await _Builder.BuildFromApplicationArguments(args).ConfigureAwait(false);
UpdateSetUp(setup);
}
public void InitForProduction()
{
UpdateSetUp(_Builder.BuildForProduction());
}
private void UpdateSetUp(ApplicationSetUp applicationSetUp)
{
_ApplicationSetUp = applicationSetUp;
UpdateCommands();
}
private void UpdateCommands()
{
DebugCommands.Clear();
switch (Mode)
{
case ApplicationMode.Live:
DebugCommands["Reload"] = new RelayToogleCommand<ICompleteWebViewComponent>(htmlView => htmlView.ReloadAsync());
break;
case ApplicationMode.Dev:
DebugCommands["To Live"] = new RelayToogleCommand<ICompleteWebViewComponent>(GoLive);
break;
}
}
public override string ToString()
{
return _ApplicationSetUp?.ToString() ?? "Not initialized";
}
public void Dispose()
{
_Builder.Dispose();
}
}
}
| 32.313333 | 159 | 0.59707 | [
"MIT"
] | NeutroniumCore/Neutronium.BuildingBlocks | Neutronium.BuildingBlocks.SetUp/SetUpViewModel.cs | 4,849 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
public class Team
{
public Vector2 MeanPosition;
public Vector2 Direction = new Vector2(1, 0);
private List<Boid> Members = new List<Boid>();
public void AddMember(Boid member)
{
member.Team = this;
member.Direction = Direction;
Members.Add(member);
}
public void RemoveMember(Boid member)
{
member.Team = null;
Members.Remove(member);
}
public void PreUpdate()
{
if (Members.Count == 0)
return;
foreach (var boid in Members)
{
MeanPosition += boid.Position;
}
MeanPosition /= Members.Count;
}
public void Update()
{
foreach (var boid in Members)
{
boid.LogicUpdate();
}
}
}
| 19.282609 | 50 | 0.570462 | [
"MIT"
] | iWoz/path_follow_steer | Assets/Scripts/Team.cs | 889 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.Organizations
{
public static class GetOrganizationalUnits
{
/// <summary>
/// Get all direct child organizational units under a parent organizational unit. This only provides immediate children, not all children.
///
/// {{% examples %}}
/// {{% /examples %}}
/// </summary>
public static Task<GetOrganizationalUnitsResult> InvokeAsync(GetOrganizationalUnitsArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetOrganizationalUnitsResult>("aws:organizations/getOrganizationalUnits:getOrganizationalUnits", args ?? new GetOrganizationalUnitsArgs(), options.WithVersion());
}
public sealed class GetOrganizationalUnitsArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The parent ID of the organizational unit.
/// </summary>
[Input("parentId", required: true)]
public string ParentId { get; set; } = null!;
public GetOrganizationalUnitsArgs()
{
}
}
[OutputType]
public sealed class GetOrganizationalUnitsResult
{
/// <summary>
/// List of child organizational units, which have the following attributes:
/// </summary>
public readonly ImmutableArray<Outputs.GetOrganizationalUnitsChildrenResult> Childrens;
/// <summary>
/// id is the provider-assigned unique ID for this managed resource.
/// </summary>
public readonly string Id;
public readonly string ParentId;
[OutputConstructor]
private GetOrganizationalUnitsResult(
ImmutableArray<Outputs.GetOrganizationalUnitsChildrenResult> childrens,
string id,
string parentId)
{
Childrens = childrens;
Id = id;
ParentId = parentId;
}
}
}
| 33.393939 | 216 | 0.649728 | [
"ECL-2.0",
"Apache-2.0"
] | johnktims/pulumi-aws | sdk/dotnet/Organizations/GetOrganizationalUnits.cs | 2,204 | C# |
using System;
namespace WSCT.Core.APDU
{
/// <summary>
/// Interface for generic R-APDU, ie response of smartcard.
/// </summary>
public interface ICardResponse
{
/// <summary>
/// Parses a raw response <paramref name="rAPDU"/> coming from the smartcard.
/// </summary>
/// <param name="rAPDU">R-APDU received from the smartcard.</param>
/// <returns>An instance of the <see cref="ICardResponse"/> representation of the R-APDU (<c>this</c>).</returns>
ICardResponse Parse(byte[] rAPDU);
/// <summary>
/// Parses part of a raw response <paramref name="rAPDU"/> coming from the smartcard.
/// </summary>
/// <param name="rAPDU">R-APDU received from the smartcard.</param>
/// <param name="size">Number of bytes from <paramref name="rAPDU"/> to parse.</param>
/// <returns>An instance of the <see cref="ICardResponse"/> representation of the R-APDU (<c>this</c>).</returns>
ICardResponse Parse(byte[] rAPDU, UInt32 size);
/// <summary>
/// Parses part of a raw hexa string response <paramref name="rAPDU"/> coming from the smartcard.
/// </summary>
/// <param name="rAPDU">R-APDU received from the smartcard, represented by a <see cref="string"/> of hexadecimal values.</param>
/// <returns>An instance of the <see cref="ICardResponse"/> representation of the R-APDU (<c>this</c>).</returns>
ICardResponse Parse(string rAPDU);
}
} | 47.0625 | 136 | 0.619522 | [
"MIT"
] | wsct/WSCT-Core | WSCT/Core/APDU/ICardResponse.cs | 1,506 | C# |
namespace StephanHooft.HybridUpdate
{
/// <summary>
/// An interface for <see cref="HybridUpdater"/>s.
/// </summary>
public interface IHybridUpdater
{
#region Properties
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
#region Methods
/// <summary>
/// Reports a FixedUpdate call to the <see cref="IHybridUpdater"/>.
/// </summary>
void ReportFixedUpdateCall();
/// <summary>
/// Registers an object to the <see cref="IHybridUpdater"/> and receives a
/// <see cref="HybridUpdateCallback"/> in return. The object must hang on to this reference so it can
/// unregister itself at a later point.
/// </summary>
/// <param name="callback">The "HybridUpdate" method that the <see cref="IHybridUpdater"/> will call
/// whenever it pushes the object to update.</param>
/// <param name="type">The <see cref="System.Type"/> of the registering object.</param>
/// <param name="priority">The relative priority of the registering object type.</param>
/// <returns>A <see cref="HybridUpdateCallback"/> that must be used to report Update and FixedUpdate calls.
/// </returns>
HybridUpdateCallback Register(System.Type type, int priority, System.Action<float> callback);
/// <summary>
/// Unregisters an object from the <see cref="IHybridUpdater"/>, preventing further callbacks to it.
/// </summary>
/// <param name="callback">The "HybridUpdate" method to unregister.</param>
void Unregister(HybridUpdateCallback? callback);
/// <summary>
/// Reports an Update call to the <see cref="IHybridUpdater"/>.
/// </summary>
/// <param name="deltaTime">Pass the current value of <see cref="UnityEngine.Time.deltaTime"/> here.</param>
void ReportUpdateCall(float deltaTime);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
}
}
| 44.645833 | 120 | 0.55343 | [
"MIT"
] | StephanHooft/unity-extensions | Runtime/HybridUpdate/Interfaces/IHybridUpdater.cs | 2,143 | C# |
using AutoMapper;
using ITJakub.Web.Hub.Options;
using Vokabular.MainService.DataContracts.Contracts.Type;
namespace ITJakub.Web.Hub.AutoMapperProfiles
{
public class PortalTypeProfile : Profile
{
public PortalTypeProfile()
{
CreateMap<PortalType, PortalTypeContract>();
}
}
} | 23.285714 | 57 | 0.693252 | [
"BSD-3-Clause"
] | RIDICS/ITJakub | UJCSystem/ITJakub.Web.Hub/AutoMapperProfiles/PortalTypeProfile.cs | 328 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.Bot.Schema
{
using System;
using Newtonsoft.Json;
/// <summary>
/// Supplies monetary amounts.
/// </summary>
[Obsolete("Bot Framework no longer supports payments.")]
public partial class PaymentCurrencyAmount
{
/// <summary>
/// Initializes a new instance of the <see cref="PaymentCurrencyAmount"/> class.
/// </summary>
public PaymentCurrencyAmount()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the <see cref="PaymentCurrencyAmount"/> class.
/// </summary>
/// <param name="currency">A currency identifier.</param>
/// <param name="value">Decimal monetary value.</param>
/// <param name="currencySystem">Currency system.</param>
public PaymentCurrencyAmount(string currency = default, string value = default, string currencySystem = default)
{
Currency = currency;
Value = value;
CurrencySystem = currencySystem;
CustomInit();
}
/// <summary>
/// Gets or sets a currency identifier.
/// </summary>
/// <value>The currency.</value>
[JsonProperty(PropertyName = "currency")]
public string Currency { get; set; }
/// <summary>
/// Gets or sets decimal monetary value.
/// </summary>
/// <value>The decimal monetary value.</value>
[JsonProperty(PropertyName = "value")]
public string Value { get; set; }
/// <summary>
/// Gets or sets currency system.
/// </summary>
/// <value>The currency system.</value>
[JsonProperty(PropertyName = "currencySystem")]
public string CurrencySystem { get; set; }
/// <summary>
/// An initialization method that performs custom operations like setting defaults.
/// </summary>
partial void CustomInit();
}
}
| 32.46875 | 120 | 0.580366 | [
"MIT"
] | Arsh-Kashyap/botbuilder-dotnet | libraries/Microsoft.Bot.Schema/PaymentCurrencyAmount.cs | 2,080 | C# |
using System;
using UnityEngine;
using UnityUtility.MathExt;
using UnityUtilityTools;
namespace UnityUtility.NumericEntities
{
[Serializable]
public struct FilledFloat : IFilledEntity<float>, IEquatable<FilledFloat>
{
[SerializeField, HideInInspector]
private float m_threshold;
[SerializeField, HideInInspector]
private float m_filler;
public float CurValue => m_filler.Clamp(0f, m_threshold);
public float Threshold => m_threshold;
public bool FilledFully => m_filler >= m_threshold;
public bool IsEmpty => m_filler == 0f;
public float Ratio => m_filler.CutAfter(m_threshold) / m_threshold;
public float Excess => (m_filler - m_threshold).CutBefore(0f);
public FilledFloat(float threshold)
{
if (threshold < 0f)
throw Errors.NegativeParameter(nameof(threshold));
m_threshold = threshold;
m_filler = 0f;
}
public void Fill(float addValue)
{
if (addValue < 0f)
throw Errors.NegativeParameter(nameof(addValue));
m_filler += addValue;
}
public void FillFully()
{
if (m_filler < m_threshold)
m_filler = m_threshold;
}
public void Remove(float removeValue)
{
if (removeValue < 0f)
throw Errors.NegativeParameter(nameof(removeValue));
m_filler -= removeValue.CutAfter(m_filler);
}
public void RemoveAll()
{
m_filler = 0f;
}
public void RemoveTillExcess()
{
m_filler = Excess;
}
public void Resize(float value, ResizeType resizeType = ResizeType.NewValue)
{
switch (resizeType)
{
case ResizeType.NewValue:
if (value < 0f)
throw Errors.NegativeParameter(nameof(value));
m_threshold = value;
break;
case ResizeType.Delta:
m_threshold = (m_threshold + value).CutBefore(0f);
break;
default:
throw new UnsupportedValueException(resizeType);
}
}
// -- //
public override bool Equals(object obj)
{
return obj is FilledFloat other && Equals(other);
}
public bool Equals(FilledFloat other)
{
return m_filler == other.m_filler && m_threshold == other.m_threshold;
}
public override int GetHashCode()
{
return Helper.GetHashCode(m_filler.GetHashCode(), m_threshold.GetHashCode());
}
}
}
| 27.534653 | 89 | 0.549802 | [
"MIT"
] | oleghcp/UnityUtility | Code/Runtime/UnityUtility/NumericEntities/FilledFloat.cs | 2,783 | 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 devops-guru-2020-12-01.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net;
using Amazon.DevOpsGuru.Model;
using Amazon.DevOpsGuru.Model.Internal.MarshallTransformations;
using Amazon.DevOpsGuru.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.DevOpsGuru
{
/// <summary>
/// Implementation for accessing DevOpsGuru
///
/// Amazon DevOps Guru is a fully managed service that helps you identify anomalous behavior
/// in business critical operational applications. You specify the AWS resources that
/// you want DevOps Guru to cover, then the Amazon CloudWatch metrics and AWS CloudTrail
/// events related to those resources are analyzed. When anomalous behavior is detected,
/// DevOps Guru creates an <i>insight</i> that includes recommendations, related events,
/// and related metrics that can help you improve your operational applications. For more
/// information, see <a href="https://docs.aws.amazon.com/devops-guru/latest/userguide/welcome.html">What
/// is Amazon DevOps Guru</a>.
///
///
/// <para>
/// You can specify 1 or 2 Amazon Simple Notification Service topics so you are notified
/// every time a new insight is created. You can also enable DevOps Guru to generate an
/// OpsItem in AWS Systems Manager for each insight to help you manage and track your
/// work addressing insights.
/// </para>
///
/// <para>
/// To learn about the DevOps Guru workflow, see <a href="https://docs.aws.amazon.com/devops-guru/latest/userguide/welcome.html#how-it-works">How
/// DevOps Guru works</a>. To learn about DevOps Guru concepts, see <a href="https://docs.aws.amazon.com/devops-guru/latest/userguide/concepts.html">Concepts
/// in DevOps Guru</a>.
/// </para>
/// </summary>
public partial class AmazonDevOpsGuruClient : AmazonServiceClient, IAmazonDevOpsGuru
{
private static IServiceMetadata serviceMetadata = new AmazonDevOpsGuruMetadata();
private IDevOpsGuruPaginatorFactory _paginators;
/// <summary>
/// Paginators for the service
/// </summary>
public IDevOpsGuruPaginatorFactory Paginators
{
get
{
if (this._paginators == null)
{
this._paginators = new DevOpsGuruPaginatorFactory(this);
}
return this._paginators;
}
}
#region Constructors
/// <summary>
/// Constructs AmazonDevOpsGuruClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonDevOpsGuruClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonDevOpsGuruConfig()) { }
/// <summary>
/// Constructs AmazonDevOpsGuruClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonDevOpsGuruClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonDevOpsGuruConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonDevOpsGuruClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonDevOpsGuruClient Configuration Object</param>
public AmazonDevOpsGuruClient(AmazonDevOpsGuruConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonDevOpsGuruClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonDevOpsGuruClient(AWSCredentials credentials)
: this(credentials, new AmazonDevOpsGuruConfig())
{
}
/// <summary>
/// Constructs AmazonDevOpsGuruClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonDevOpsGuruClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonDevOpsGuruConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonDevOpsGuruClient with AWS Credentials and an
/// AmazonDevOpsGuruClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonDevOpsGuruClient Configuration Object</param>
public AmazonDevOpsGuruClient(AWSCredentials credentials, AmazonDevOpsGuruConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonDevOpsGuruClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonDevOpsGuruClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonDevOpsGuruConfig())
{
}
/// <summary>
/// Constructs AmazonDevOpsGuruClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonDevOpsGuruClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonDevOpsGuruConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonDevOpsGuruClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonDevOpsGuruClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonDevOpsGuruClient Configuration Object</param>
public AmazonDevOpsGuruClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonDevOpsGuruConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonDevOpsGuruClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonDevOpsGuruClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDevOpsGuruConfig())
{
}
/// <summary>
/// Constructs AmazonDevOpsGuruClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonDevOpsGuruClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDevOpsGuruConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonDevOpsGuruClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonDevOpsGuruClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonDevOpsGuruClient Configuration Object</param>
public AmazonDevOpsGuruClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonDevOpsGuruConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region AddNotificationChannel
/// <summary>
/// Adds a notification channel to DevOps Guru. A notification channel is used to notify
/// you about important DevOps Guru events, such as when an insight is generated.
///
///
/// <para>
/// If you use an Amazon SNS topic in another account, you must attach a policy to it
/// that grants DevOps Guru permission to it notifications. DevOps Guru adds the required
/// policy on your behalf to send notifications using Amazon SNS in your account. For
/// more information, see <a href="https://docs.aws.amazon.com/devops-guru/latest/userguide/sns-required-permissions.html">Permissions
/// for cross account Amazon SNS topics</a>.
/// </para>
///
/// <para>
/// If you use an Amazon SNS topic that is encrypted by an AWS Key Management Service
/// customer-managed key (CMK), then you must add permissions to the CMK. For more information,
/// see <a href="https://docs.aws.amazon.com/devops-guru/latest/userguide/sns-kms-permissions.html">Permissions
/// for AWS KMS–encrypted Amazon SNS topics</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AddNotificationChannel service method.</param>
///
/// <returns>The response from the AddNotificationChannel service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ConflictException">
/// An exception that is thrown when a conflict occurs.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ServiceQuotaExceededException">
/// The request contains a value that exceeds a maximum quota.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/AddNotificationChannel">REST API Reference for AddNotificationChannel Operation</seealso>
public virtual AddNotificationChannelResponse AddNotificationChannel(AddNotificationChannelRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AddNotificationChannelRequestMarshaller.Instance;
options.ResponseUnmarshaller = AddNotificationChannelResponseUnmarshaller.Instance;
return Invoke<AddNotificationChannelResponse>(request, options);
}
/// <summary>
/// Adds a notification channel to DevOps Guru. A notification channel is used to notify
/// you about important DevOps Guru events, such as when an insight is generated.
///
///
/// <para>
/// If you use an Amazon SNS topic in another account, you must attach a policy to it
/// that grants DevOps Guru permission to it notifications. DevOps Guru adds the required
/// policy on your behalf to send notifications using Amazon SNS in your account. For
/// more information, see <a href="https://docs.aws.amazon.com/devops-guru/latest/userguide/sns-required-permissions.html">Permissions
/// for cross account Amazon SNS topics</a>.
/// </para>
///
/// <para>
/// If you use an Amazon SNS topic that is encrypted by an AWS Key Management Service
/// customer-managed key (CMK), then you must add permissions to the CMK. For more information,
/// see <a href="https://docs.aws.amazon.com/devops-guru/latest/userguide/sns-kms-permissions.html">Permissions
/// for AWS KMS–encrypted Amazon SNS topics</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AddNotificationChannel service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AddNotificationChannel service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ConflictException">
/// An exception that is thrown when a conflict occurs.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ServiceQuotaExceededException">
/// The request contains a value that exceeds a maximum quota.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/AddNotificationChannel">REST API Reference for AddNotificationChannel Operation</seealso>
public virtual Task<AddNotificationChannelResponse> AddNotificationChannelAsync(AddNotificationChannelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = AddNotificationChannelRequestMarshaller.Instance;
options.ResponseUnmarshaller = AddNotificationChannelResponseUnmarshaller.Instance;
return InvokeAsync<AddNotificationChannelResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeAccountHealth
/// <summary>
/// Returns the number of open reactive insights, the number of open proactive insights,
/// and the number of metrics analyzed in your AWS account. Use these numbers to gauge
/// the health of operations in your AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeAccountHealth service method.</param>
///
/// <returns>The response from the DescribeAccountHealth service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeAccountHealth">REST API Reference for DescribeAccountHealth Operation</seealso>
public virtual DescribeAccountHealthResponse DescribeAccountHealth(DescribeAccountHealthRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeAccountHealthRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeAccountHealthResponseUnmarshaller.Instance;
return Invoke<DescribeAccountHealthResponse>(request, options);
}
/// <summary>
/// Returns the number of open reactive insights, the number of open proactive insights,
/// and the number of metrics analyzed in your AWS account. Use these numbers to gauge
/// the health of operations in your AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeAccountHealth service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeAccountHealth service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeAccountHealth">REST API Reference for DescribeAccountHealth Operation</seealso>
public virtual Task<DescribeAccountHealthResponse> DescribeAccountHealthAsync(DescribeAccountHealthRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeAccountHealthRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeAccountHealthResponseUnmarshaller.Instance;
return InvokeAsync<DescribeAccountHealthResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeAccountOverview
/// <summary>
/// For the time range passed in, returns the number of open reactive insight that were
/// created, the number of open proactive insights that were created, and the Mean Time
/// to Recover (MTTR) for all closed reactive insights.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeAccountOverview service method.</param>
///
/// <returns>The response from the DescribeAccountOverview service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeAccountOverview">REST API Reference for DescribeAccountOverview Operation</seealso>
public virtual DescribeAccountOverviewResponse DescribeAccountOverview(DescribeAccountOverviewRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeAccountOverviewRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeAccountOverviewResponseUnmarshaller.Instance;
return Invoke<DescribeAccountOverviewResponse>(request, options);
}
/// <summary>
/// For the time range passed in, returns the number of open reactive insight that were
/// created, the number of open proactive insights that were created, and the Mean Time
/// to Recover (MTTR) for all closed reactive insights.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeAccountOverview service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeAccountOverview service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeAccountOverview">REST API Reference for DescribeAccountOverview Operation</seealso>
public virtual Task<DescribeAccountOverviewResponse> DescribeAccountOverviewAsync(DescribeAccountOverviewRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeAccountOverviewRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeAccountOverviewResponseUnmarshaller.Instance;
return InvokeAsync<DescribeAccountOverviewResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeAnomaly
/// <summary>
/// Returns details about an anomaly that you specify using its ID.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeAnomaly service method.</param>
///
/// <returns>The response from the DescribeAnomaly service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeAnomaly">REST API Reference for DescribeAnomaly Operation</seealso>
public virtual DescribeAnomalyResponse DescribeAnomaly(DescribeAnomalyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeAnomalyRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeAnomalyResponseUnmarshaller.Instance;
return Invoke<DescribeAnomalyResponse>(request, options);
}
/// <summary>
/// Returns details about an anomaly that you specify using its ID.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeAnomaly service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeAnomaly service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeAnomaly">REST API Reference for DescribeAnomaly Operation</seealso>
public virtual Task<DescribeAnomalyResponse> DescribeAnomalyAsync(DescribeAnomalyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeAnomalyRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeAnomalyResponseUnmarshaller.Instance;
return InvokeAsync<DescribeAnomalyResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeFeedback
/// <summary>
/// Returns the most recent feedback submitted in the current AWS account and Region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeFeedback service method.</param>
///
/// <returns>The response from the DescribeFeedback service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeFeedback">REST API Reference for DescribeFeedback Operation</seealso>
public virtual DescribeFeedbackResponse DescribeFeedback(DescribeFeedbackRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeFeedbackRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeFeedbackResponseUnmarshaller.Instance;
return Invoke<DescribeFeedbackResponse>(request, options);
}
/// <summary>
/// Returns the most recent feedback submitted in the current AWS account and Region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeFeedback service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeFeedback service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeFeedback">REST API Reference for DescribeFeedback Operation</seealso>
public virtual Task<DescribeFeedbackResponse> DescribeFeedbackAsync(DescribeFeedbackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeFeedbackRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeFeedbackResponseUnmarshaller.Instance;
return InvokeAsync<DescribeFeedbackResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeInsight
/// <summary>
/// Returns details about an insight that you specify using its ID.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeInsight service method.</param>
///
/// <returns>The response from the DescribeInsight service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeInsight">REST API Reference for DescribeInsight Operation</seealso>
public virtual DescribeInsightResponse DescribeInsight(DescribeInsightRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeInsightRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeInsightResponseUnmarshaller.Instance;
return Invoke<DescribeInsightResponse>(request, options);
}
/// <summary>
/// Returns details about an insight that you specify using its ID.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeInsight service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeInsight service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeInsight">REST API Reference for DescribeInsight Operation</seealso>
public virtual Task<DescribeInsightResponse> DescribeInsightAsync(DescribeInsightRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeInsightRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeInsightResponseUnmarshaller.Instance;
return InvokeAsync<DescribeInsightResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeResourceCollectionHealth
/// <summary>
/// Returns the number of open proactive insights, open reactive insights, and the Mean
/// Time to Recover (MTTR) for all closed insights in resource collections in your account.
/// You specify the type of AWS resources collection. The one type of AWS resource collection
/// supported is AWS CloudFormation stacks. DevOps Guru can be configured to analyze only
/// the AWS resources that are defined in the stacks.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeResourceCollectionHealth service method.</param>
///
/// <returns>The response from the DescribeResourceCollectionHealth service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeResourceCollectionHealth">REST API Reference for DescribeResourceCollectionHealth Operation</seealso>
public virtual DescribeResourceCollectionHealthResponse DescribeResourceCollectionHealth(DescribeResourceCollectionHealthRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeResourceCollectionHealthRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeResourceCollectionHealthResponseUnmarshaller.Instance;
return Invoke<DescribeResourceCollectionHealthResponse>(request, options);
}
/// <summary>
/// Returns the number of open proactive insights, open reactive insights, and the Mean
/// Time to Recover (MTTR) for all closed insights in resource collections in your account.
/// You specify the type of AWS resources collection. The one type of AWS resource collection
/// supported is AWS CloudFormation stacks. DevOps Guru can be configured to analyze only
/// the AWS resources that are defined in the stacks.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeResourceCollectionHealth service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeResourceCollectionHealth service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeResourceCollectionHealth">REST API Reference for DescribeResourceCollectionHealth Operation</seealso>
public virtual Task<DescribeResourceCollectionHealthResponse> DescribeResourceCollectionHealthAsync(DescribeResourceCollectionHealthRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeResourceCollectionHealthRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeResourceCollectionHealthResponseUnmarshaller.Instance;
return InvokeAsync<DescribeResourceCollectionHealthResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeServiceIntegration
/// <summary>
/// Returns the integration status of services that are integrated with DevOps Guru.
/// The one service that can be integrated with DevOps Guru is AWS Systems Manager, which
/// can be used to create an OpsItem for each generated insight.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeServiceIntegration service method.</param>
///
/// <returns>The response from the DescribeServiceIntegration service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeServiceIntegration">REST API Reference for DescribeServiceIntegration Operation</seealso>
public virtual DescribeServiceIntegrationResponse DescribeServiceIntegration(DescribeServiceIntegrationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeServiceIntegrationRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeServiceIntegrationResponseUnmarshaller.Instance;
return Invoke<DescribeServiceIntegrationResponse>(request, options);
}
/// <summary>
/// Returns the integration status of services that are integrated with DevOps Guru.
/// The one service that can be integrated with DevOps Guru is AWS Systems Manager, which
/// can be used to create an OpsItem for each generated insight.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeServiceIntegration service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeServiceIntegration service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/DescribeServiceIntegration">REST API Reference for DescribeServiceIntegration Operation</seealso>
public virtual Task<DescribeServiceIntegrationResponse> DescribeServiceIntegrationAsync(DescribeServiceIntegrationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeServiceIntegrationRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeServiceIntegrationResponseUnmarshaller.Instance;
return InvokeAsync<DescribeServiceIntegrationResponse>(request, options, cancellationToken);
}
#endregion
#region GetResourceCollection
/// <summary>
/// Returns lists AWS resources that are of the specified resource collection type. The
/// one type of AWS resource collection supported is AWS CloudFormation stacks. DevOps
/// Guru can be configured to analyze only the AWS resources that are defined in the stacks.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetResourceCollection service method.</param>
///
/// <returns>The response from the GetResourceCollection service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/GetResourceCollection">REST API Reference for GetResourceCollection Operation</seealso>
public virtual GetResourceCollectionResponse GetResourceCollection(GetResourceCollectionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetResourceCollectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetResourceCollectionResponseUnmarshaller.Instance;
return Invoke<GetResourceCollectionResponse>(request, options);
}
/// <summary>
/// Returns lists AWS resources that are of the specified resource collection type. The
/// one type of AWS resource collection supported is AWS CloudFormation stacks. DevOps
/// Guru can be configured to analyze only the AWS resources that are defined in the stacks.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetResourceCollection service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetResourceCollection service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/GetResourceCollection">REST API Reference for GetResourceCollection Operation</seealso>
public virtual Task<GetResourceCollectionResponse> GetResourceCollectionAsync(GetResourceCollectionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetResourceCollectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetResourceCollectionResponseUnmarshaller.Instance;
return InvokeAsync<GetResourceCollectionResponse>(request, options, cancellationToken);
}
#endregion
#region ListAnomaliesForInsight
/// <summary>
/// Returns a list of the anomalies that belong to an insight that you specify using
/// its ID.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListAnomaliesForInsight service method.</param>
///
/// <returns>The response from the ListAnomaliesForInsight service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/ListAnomaliesForInsight">REST API Reference for ListAnomaliesForInsight Operation</seealso>
public virtual ListAnomaliesForInsightResponse ListAnomaliesForInsight(ListAnomaliesForInsightRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListAnomaliesForInsightRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListAnomaliesForInsightResponseUnmarshaller.Instance;
return Invoke<ListAnomaliesForInsightResponse>(request, options);
}
/// <summary>
/// Returns a list of the anomalies that belong to an insight that you specify using
/// its ID.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListAnomaliesForInsight service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListAnomaliesForInsight service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/ListAnomaliesForInsight">REST API Reference for ListAnomaliesForInsight Operation</seealso>
public virtual Task<ListAnomaliesForInsightResponse> ListAnomaliesForInsightAsync(ListAnomaliesForInsightRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListAnomaliesForInsightRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListAnomaliesForInsightResponseUnmarshaller.Instance;
return InvokeAsync<ListAnomaliesForInsightResponse>(request, options, cancellationToken);
}
#endregion
#region ListEvents
/// <summary>
/// Returns a list of the events emitted by the resources that are evaluated by DevOps
/// Guru. You can use filters to specify which events are returned.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListEvents service method.</param>
///
/// <returns>The response from the ListEvents service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/ListEvents">REST API Reference for ListEvents Operation</seealso>
public virtual ListEventsResponse ListEvents(ListEventsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListEventsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListEventsResponseUnmarshaller.Instance;
return Invoke<ListEventsResponse>(request, options);
}
/// <summary>
/// Returns a list of the events emitted by the resources that are evaluated by DevOps
/// Guru. You can use filters to specify which events are returned.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListEvents service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListEvents service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/ListEvents">REST API Reference for ListEvents Operation</seealso>
public virtual Task<ListEventsResponse> ListEventsAsync(ListEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListEventsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListEventsResponseUnmarshaller.Instance;
return InvokeAsync<ListEventsResponse>(request, options, cancellationToken);
}
#endregion
#region ListInsights
/// <summary>
/// Returns a list of insights in your AWS account. You can specify which insights are
/// returned by their start time and status (<code>ONGOING</code>, <code>CLOSED</code>,
/// or <code>ANY</code>).
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListInsights service method.</param>
///
/// <returns>The response from the ListInsights service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/ListInsights">REST API Reference for ListInsights Operation</seealso>
public virtual ListInsightsResponse ListInsights(ListInsightsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListInsightsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListInsightsResponseUnmarshaller.Instance;
return Invoke<ListInsightsResponse>(request, options);
}
/// <summary>
/// Returns a list of insights in your AWS account. You can specify which insights are
/// returned by their start time and status (<code>ONGOING</code>, <code>CLOSED</code>,
/// or <code>ANY</code>).
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListInsights service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListInsights service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/ListInsights">REST API Reference for ListInsights Operation</seealso>
public virtual Task<ListInsightsResponse> ListInsightsAsync(ListInsightsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListInsightsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListInsightsResponseUnmarshaller.Instance;
return InvokeAsync<ListInsightsResponse>(request, options, cancellationToken);
}
#endregion
#region ListNotificationChannels
/// <summary>
/// Returns a list of notification channels configured for DevOps Guru. Each notification
/// channel is used to notify you when DevOps Guru generates an insight that contains
/// information about how to improve your operations. The one supported notification channel
/// is Amazon Simple Notification Service (Amazon SNS).
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListNotificationChannels service method.</param>
///
/// <returns>The response from the ListNotificationChannels service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/ListNotificationChannels">REST API Reference for ListNotificationChannels Operation</seealso>
public virtual ListNotificationChannelsResponse ListNotificationChannels(ListNotificationChannelsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListNotificationChannelsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListNotificationChannelsResponseUnmarshaller.Instance;
return Invoke<ListNotificationChannelsResponse>(request, options);
}
/// <summary>
/// Returns a list of notification channels configured for DevOps Guru. Each notification
/// channel is used to notify you when DevOps Guru generates an insight that contains
/// information about how to improve your operations. The one supported notification channel
/// is Amazon Simple Notification Service (Amazon SNS).
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListNotificationChannels service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListNotificationChannels service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/ListNotificationChannels">REST API Reference for ListNotificationChannels Operation</seealso>
public virtual Task<ListNotificationChannelsResponse> ListNotificationChannelsAsync(ListNotificationChannelsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListNotificationChannelsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListNotificationChannelsResponseUnmarshaller.Instance;
return InvokeAsync<ListNotificationChannelsResponse>(request, options, cancellationToken);
}
#endregion
#region ListRecommendations
/// <summary>
/// Returns a list of a specified insight's recommendations. Each recommendation includes
/// a list of related metrics and a list of related events.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListRecommendations service method.</param>
///
/// <returns>The response from the ListRecommendations service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/ListRecommendations">REST API Reference for ListRecommendations Operation</seealso>
public virtual ListRecommendationsResponse ListRecommendations(ListRecommendationsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListRecommendationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListRecommendationsResponseUnmarshaller.Instance;
return Invoke<ListRecommendationsResponse>(request, options);
}
/// <summary>
/// Returns a list of a specified insight's recommendations. Each recommendation includes
/// a list of related metrics and a list of related events.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListRecommendations service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListRecommendations service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/ListRecommendations">REST API Reference for ListRecommendations Operation</seealso>
public virtual Task<ListRecommendationsResponse> ListRecommendationsAsync(ListRecommendationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListRecommendationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListRecommendationsResponseUnmarshaller.Instance;
return InvokeAsync<ListRecommendationsResponse>(request, options, cancellationToken);
}
#endregion
#region PutFeedback
/// <summary>
/// Collects customer feedback about the specified insight.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutFeedback service method.</param>
///
/// <returns>The response from the PutFeedback service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ConflictException">
/// An exception that is thrown when a conflict occurs.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/PutFeedback">REST API Reference for PutFeedback Operation</seealso>
public virtual PutFeedbackResponse PutFeedback(PutFeedbackRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PutFeedbackRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutFeedbackResponseUnmarshaller.Instance;
return Invoke<PutFeedbackResponse>(request, options);
}
/// <summary>
/// Collects customer feedback about the specified insight.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutFeedback service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the PutFeedback service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ConflictException">
/// An exception that is thrown when a conflict occurs.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/PutFeedback">REST API Reference for PutFeedback Operation</seealso>
public virtual Task<PutFeedbackResponse> PutFeedbackAsync(PutFeedbackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = PutFeedbackRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutFeedbackResponseUnmarshaller.Instance;
return InvokeAsync<PutFeedbackResponse>(request, options, cancellationToken);
}
#endregion
#region RemoveNotificationChannel
/// <summary>
/// Removes a notification channel from DevOps Guru. A notification channel is used to
/// notify you when DevOps Guru generates an insight that contains information about how
/// to improve your operations.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RemoveNotificationChannel service method.</param>
///
/// <returns>The response from the RemoveNotificationChannel service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ConflictException">
/// An exception that is thrown when a conflict occurs.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/RemoveNotificationChannel">REST API Reference for RemoveNotificationChannel Operation</seealso>
public virtual RemoveNotificationChannelResponse RemoveNotificationChannel(RemoveNotificationChannelRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RemoveNotificationChannelRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemoveNotificationChannelResponseUnmarshaller.Instance;
return Invoke<RemoveNotificationChannelResponse>(request, options);
}
/// <summary>
/// Removes a notification channel from DevOps Guru. A notification channel is used to
/// notify you when DevOps Guru generates an insight that contains information about how
/// to improve your operations.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RemoveNotificationChannel service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the RemoveNotificationChannel service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ConflictException">
/// An exception that is thrown when a conflict occurs.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ResourceNotFoundException">
/// A requested resource could not be found
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/RemoveNotificationChannel">REST API Reference for RemoveNotificationChannel Operation</seealso>
public virtual Task<RemoveNotificationChannelResponse> RemoveNotificationChannelAsync(RemoveNotificationChannelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = RemoveNotificationChannelRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemoveNotificationChannelResponseUnmarshaller.Instance;
return InvokeAsync<RemoveNotificationChannelResponse>(request, options, cancellationToken);
}
#endregion
#region SearchInsights
/// <summary>
/// Returns a list of insights in your AWS account. You can specify which insights are
/// returned by their start time, one or more statuses (<code>ONGOING</code>, <code>CLOSED</code>,
/// and <code>CLOSED</code>), one or more severities (<code>LOW</code>, <code>MEDIUM</code>,
/// and <code>HIGH</code>), and type (<code>REACTIVE</code> or <code>PROACTIVE</code>).
///
///
///
/// <para>
/// Use the <code>Filters</code> parameter to specify status and severity search parameters.
/// Use the <code>Type</code> parameter to specify <code>REACTIVE</code> or <code>PROACTIVE</code>
/// in your search.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the SearchInsights service method.</param>
///
/// <returns>The response from the SearchInsights service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/SearchInsights">REST API Reference for SearchInsights Operation</seealso>
public virtual SearchInsightsResponse SearchInsights(SearchInsightsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = SearchInsightsRequestMarshaller.Instance;
options.ResponseUnmarshaller = SearchInsightsResponseUnmarshaller.Instance;
return Invoke<SearchInsightsResponse>(request, options);
}
/// <summary>
/// Returns a list of insights in your AWS account. You can specify which insights are
/// returned by their start time, one or more statuses (<code>ONGOING</code>, <code>CLOSED</code>,
/// and <code>CLOSED</code>), one or more severities (<code>LOW</code>, <code>MEDIUM</code>,
/// and <code>HIGH</code>), and type (<code>REACTIVE</code> or <code>PROACTIVE</code>).
///
///
///
/// <para>
/// Use the <code>Filters</code> parameter to specify status and severity search parameters.
/// Use the <code>Type</code> parameter to specify <code>REACTIVE</code> or <code>PROACTIVE</code>
/// in your search.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the SearchInsights service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the SearchInsights service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/SearchInsights">REST API Reference for SearchInsights Operation</seealso>
public virtual Task<SearchInsightsResponse> SearchInsightsAsync(SearchInsightsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = SearchInsightsRequestMarshaller.Instance;
options.ResponseUnmarshaller = SearchInsightsResponseUnmarshaller.Instance;
return InvokeAsync<SearchInsightsResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateResourceCollection
/// <summary>
/// Updates the collection of resources that DevOps Guru analyzes. The one type of AWS
/// resource collection supported is AWS CloudFormation stacks. DevOps Guru can be configured
/// to analyze only the AWS resources that are defined in the stacks. This method also
/// creates the IAM role required for you to use DevOps Guru.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateResourceCollection service method.</param>
///
/// <returns>The response from the UpdateResourceCollection service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ConflictException">
/// An exception that is thrown when a conflict occurs.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/UpdateResourceCollection">REST API Reference for UpdateResourceCollection Operation</seealso>
public virtual UpdateResourceCollectionResponse UpdateResourceCollection(UpdateResourceCollectionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateResourceCollectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateResourceCollectionResponseUnmarshaller.Instance;
return Invoke<UpdateResourceCollectionResponse>(request, options);
}
/// <summary>
/// Updates the collection of resources that DevOps Guru analyzes. The one type of AWS
/// resource collection supported is AWS CloudFormation stacks. DevOps Guru can be configured
/// to analyze only the AWS resources that are defined in the stacks. This method also
/// creates the IAM role required for you to use DevOps Guru.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateResourceCollection service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateResourceCollection service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ConflictException">
/// An exception that is thrown when a conflict occurs.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/UpdateResourceCollection">REST API Reference for UpdateResourceCollection Operation</seealso>
public virtual Task<UpdateResourceCollectionResponse> UpdateResourceCollectionAsync(UpdateResourceCollectionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateResourceCollectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateResourceCollectionResponseUnmarshaller.Instance;
return InvokeAsync<UpdateResourceCollectionResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateServiceIntegration
/// <summary>
/// Enables or disables integration with a service that can be integrated with DevOps
/// Guru. The one service that can be integrated with DevOps Guru is AWS Systems Manager,
/// which can be used to create an OpsItem for each generated insight.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateServiceIntegration service method.</param>
///
/// <returns>The response from the UpdateServiceIntegration service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ConflictException">
/// An exception that is thrown when a conflict occurs.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/UpdateServiceIntegration">REST API Reference for UpdateServiceIntegration Operation</seealso>
public virtual UpdateServiceIntegrationResponse UpdateServiceIntegration(UpdateServiceIntegrationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateServiceIntegrationRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateServiceIntegrationResponseUnmarshaller.Instance;
return Invoke<UpdateServiceIntegrationResponse>(request, options);
}
/// <summary>
/// Enables or disables integration with a service that can be integrated with DevOps
/// Guru. The one service that can be integrated with DevOps Guru is AWS Systems Manager,
/// which can be used to create an OpsItem for each generated insight.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateServiceIntegration service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateServiceIntegration service method, as returned by DevOpsGuru.</returns>
/// <exception cref="Amazon.DevOpsGuru.Model.AccessDeniedException">
/// You don't have permissions to perform the requested operation. The user or role that
/// is making the request must have at least one IAM permissions policy attached that
/// grants the required permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html">Access
/// Management</a> in the <i>IAM User Guide</i>.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ConflictException">
/// An exception that is thrown when a conflict occurs.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.InternalServerException">
/// An internal failure in an Amazon service occurred.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ThrottlingException">
/// The request was denied due to a request throttling.
/// </exception>
/// <exception cref="Amazon.DevOpsGuru.Model.ValidationException">
/// Contains information about data passed in to a field during a request that is not
/// valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/devops-guru-2020-12-01/UpdateServiceIntegration">REST API Reference for UpdateServiceIntegration Operation</seealso>
public virtual Task<UpdateServiceIntegrationResponse> UpdateServiceIntegrationAsync(UpdateServiceIntegrationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateServiceIntegrationRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateServiceIntegrationResponseUnmarshaller.Instance;
return InvokeAsync<UpdateServiceIntegrationResponse>(request, options, cancellationToken);
}
#endregion
}
} | 58.655449 | 239 | 0.673734 | [
"Apache-2.0"
] | diegodias/aws-sdk-net | sdk/src/Services/DevOpsGuru/Generated/_bcl45/AmazonDevOpsGuruClient.cs | 109,807 | C# |
using CSharpSpeed;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using static System.Math;
namespace InstrumentedLibrary
{
/// <summary>
/// The normalize two vectors tests class.
/// </summary>
[DisplayName("Normalize two 3D Vectors Tests")]
[Description("Normalizes two 3D Vectors.")]
[SourceCodeLocationProvider]
public static class NormalizeTwoVectors3DTests
{
/// <summary>
/// Test the harness.
/// </summary>
/// <returns>The <see cref="List{T}"/>.</returns>
[DisplayName(nameof(NormalizeTwoVectors3DTests))]
public static List<SpeedTester> TestHarness()
{
var trials = 10000;
var tests = new Dictionary<object[], TestCaseResults> {
{ new object[] { 0d, 1d, 0d, 1d, 2d, 0d }, new TestCaseResults(description: "", trials: trials, expectedReturnValue:(0d, 1d), epsilon: double.Epsilon) },
};
var results = new List<SpeedTester>();
foreach (var method in HelperExtensions.ListStaticMethodsWithAttribute(MethodBase.GetCurrentMethod().DeclaringType, typeof(SourceCodeLocationProviderAttribute)))
{
var methodDescription = ((DescriptionAttribute)method.GetCustomAttribute(typeof(DescriptionAttribute)))?.Description;
results.Add(new SpeedTester(method, methodDescription, tests));
}
return results;
}
/// <summary>
///
/// </summary>
/// <param name="aI"></param>
/// <param name="aJ"></param>
/// <param name="aK"></param>
/// <param name="bI"></param>
/// <param name="bJ"></param>
/// <param name="bK"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[Signature]
public static (double I, double J, double K) Normalize(double aI, double aJ, double aK, double bI, double bJ, double bK)
=> Normalize0(aI, aJ, aK, bI, bJ, bK);
/// <summary>
/// Find the Normal of Two points.
/// </summary>
/// <param name="aI">The x component of the first Point.</param>
/// <param name="aJ">The y component of the first Point.</param>
/// <param name="aK">The z component of the first Point.</param>
/// <param name="bI">The x component of the second Point.</param>
/// <param name="bJ">The y component of the second Point.</param>
/// <param name="bK">The z component of the second Point.</param>
/// <returns>The Normal of two Points</returns>
/// <acknowledgment>
/// http://www.fundza.com/vectors/normalize/
/// </acknowledgment>
[DisplayName("Normalize two 3D Vectors")]
[Description("Normalize two 3D Vectors.")]
[Acknowledgment("http://www.fundza.com/vectors/normalize/")]
[SourceCodeLocationProvider]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static (double I, double J, double K) Normalize0(
double aI, double aJ, double aK,
double bI, double bJ, double bK)
{
return (
aI / Sqrt((aI * bI) + (aJ * bJ) + (aK * bK)),
aJ / Sqrt((aI * bI) + (aJ * bJ) + (aK * bK)),
aK / Sqrt((aI * bI) + (aJ * bJ) + (aK * bK))
);
}
}
}
| 41.069767 | 173 | 0.582673 | [
"MIT"
] | Shkyrockett/CSharpSpeed | InstrumentedLibrary/Mathmatics/Vectors/NormalizeTwoVectors3DTests.cs | 3,534 | 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.ComponentModel;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public sealed unsafe partial class HttpListenerContext
{
private string? _mutualAuthentication;
internal HttpListenerSession ListenerSession { get; private set; }
internal HttpListenerContext(HttpListenerSession session, RequestContextBase memoryBlob)
{
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(
this,
$"httpListener {session.Listener} requestBlob={((IntPtr)memoryBlob.RequestBlob)}"
);
_listener = session.Listener;
ListenerSession = session;
Request = new HttpListenerRequest(this, memoryBlob);
AuthenticationSchemes = _listener.AuthenticationSchemes;
ExtendedProtectionPolicy = _listener.ExtendedProtectionPolicy;
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(
this,
$"HttpListener: {_listener} HttpListenerRequest: {Request}"
);
}
// Call this right after construction, and only once! Not after it's been handed to a user.
internal void SetIdentity(IPrincipal principal, string? mutualAuthentication)
{
_mutualAuthentication = mutualAuthentication;
_user = principal;
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(
this,
$"mutual: {(mutualAuthentication == null ? "<null>" : mutualAuthentication)}, Principal: {principal}"
);
}
// This can be used to cache the results of HttpListener.ExtendedProtectionSelectorDelegate.
internal ExtendedProtectionPolicy ExtendedProtectionPolicy { get; set; }
internal string? MutualAuthentication => _mutualAuthentication;
internal HttpListener? Listener => _listener;
internal SafeHandle RequestQueueHandle => ListenerSession.RequestQueueHandle;
internal ThreadPoolBoundHandle RequestQueueBoundHandle =>
ListenerSession.RequestQueueBoundHandle;
internal ulong RequestId => Request.RequestId;
public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(
string? subProtocol,
int receiveBufferSize,
TimeSpan keepAliveInterval
)
{
HttpWebSocket.ValidateOptions(
subProtocol,
receiveBufferSize,
HttpWebSocket.MinSendBufferSize,
keepAliveInterval
);
ArraySegment<byte> internalBuffer = WebSocketBuffer.CreateInternalBufferArraySegment(
receiveBufferSize,
HttpWebSocket.MinSendBufferSize,
true
);
return this.AcceptWebSocketAsync(
subProtocol,
receiveBufferSize,
keepAliveInterval,
internalBuffer
);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(
string? subProtocol,
int receiveBufferSize,
TimeSpan keepAliveInterval,
ArraySegment<byte> internalBuffer
)
{
return HttpWebSocket.AcceptWebSocketAsync(
this,
subProtocol,
receiveBufferSize,
keepAliveInterval,
internalBuffer
);
}
internal void Close()
{
try
{
_response?.Close();
}
finally
{
try
{
Request.Close();
}
finally
{
IDisposable? user = _user == null ? null : _user.Identity as IDisposable;
// For unsafe connection ntlm auth we dont dispose this identity as yet since its cached
if (
(user != null)
&& (_user!.Identity!.AuthenticationType != NegotiationInfoClass.NTLM)
&& (!_listener!.UnsafeConnectionNtlmAuthentication)
)
{
user.Dispose();
}
}
}
}
internal void Abort()
{
ForceCancelRequest(RequestQueueHandle, Request.RequestId);
try
{
Request.Close();
}
finally
{
(_user?.Identity as IDisposable)?.Dispose();
}
}
internal Interop.HttpApi.HTTP_VERB GetKnownMethod()
{
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(this, $"Visited {nameof(GetKnownMethod)}()");
return Interop.HttpApi.GetKnownVerb(Request.RequestBuffer, Request.OriginalBlobAddress);
}
// This is only called while processing incoming requests. We don't have to worry about cancelling
// any response writes.
internal static void CancelRequest(SafeHandle requestQueueHandle, ulong requestId)
{
// It is safe to ignore the return value on a cancel operation because the connection is being closed
Interop.HttpApi.HttpCancelHttpRequest(requestQueueHandle, requestId, IntPtr.Zero);
}
// The request is being aborted, but large writes may be in progress. Cancel them.
internal void ForceCancelRequest(SafeHandle requestQueueHandle, ulong requestId)
{
uint statusCode = Interop.HttpApi.HttpCancelHttpRequest(
requestQueueHandle,
requestId,
IntPtr.Zero
);
// Either the connection has already dropped, or the last write is in progress.
// The requestId becomes invalid as soon as the last Content-Length write starts.
// The only way to cancel now is with CancelIoEx.
if (statusCode == Interop.HttpApi.ERROR_CONNECTION_INVALID)
{
_response!.CancelLastWrite(requestQueueHandle);
}
}
internal void SetAuthenticationHeaders()
{
Listener!.SetAuthenticationHeaders(this);
}
}
}
| 36.159574 | 121 | 0.5787 | [
"MIT"
] | belav/runtime | src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs | 6,798 | C# |
using System;
using System.Collections.Generic;
using System.IO;
namespace Umbrella.Utilities.Mime
{
/// <summary>
/// A utility to lookup MIME Types.
/// </summary>
/// <seealso cref="IMimeTypeUtility" />
public class MimeTypeUtility : IMimeTypeUtility
{
#region Private Constants
private const string _defaultMimeType = "application/octet-stream";
#endregion
#region Private Static Members
private static readonly Dictionary<string, string> _mimeTypeDictionary = new Dictionary<string, string>
{
["ez"] = "application/andrew-inset",
["aw"] = "application/applixware",
["atom"] = "application/atom+xml",
["atomcat"] = "application/atomcat+xml",
["atomsvc"] = "application/atomsvc+xml",
["ccxml"] = "application/ccxml+xml",
["cdmia"] = "application/cdmi-capability",
["cdmic"] = "application/cdmi-container",
["cdmid"] = "application/cdmi-domain",
["cdmio"] = "application/cdmi-object",
["cdmiq"] = "application/cdmi-queue",
["cu"] = "application/cu-seeme",
["davmount"] = "application/davmount+xml",
["dbk"] = "application/docbook+xml",
["dssc"] = "application/dssc+der",
["xdssc"] = "application/dssc+xml",
["ecma"] = "application/ecmascript",
["emma"] = "application/emma+xml",
["epub"] = "application/epub+zip",
["exi"] = "application/exi",
["pfr"] = "application/font-tdpfr",
["woff"] = "application/font-woff",
["woff2"] = "application/font-woff2",
["gml"] = "application/gml+xml",
["gpx"] = "application/gpx+xml",
["gxf"] = "application/gxf",
["stk"] = "application/hyperstudio",
["ink"] = "application/inkml+xml",
["ipfix"] = "application/ipfix",
["jar"] = "application/java-archive",
["ser"] = "application/java-serialized-object",
["class"] = "application/java-vm",
["js"] = "application/javascript",
["json"] = "application/json",
["jsonml"] = "application/jsonml+json",
["lostxml"] = "application/lost+xml",
["hqx"] = "application/mac-binhex40",
["cpt"] = "application/mac-compactpro",
["mads"] = "application/mads+xml",
["mrc"] = "application/marc",
["mrcx"] = "application/marcxml+xml",
["ma"] = "application/mathematica",
["mathml"] = "application/mathml+xml",
["mbox"] = "application/mbox",
["mscml"] = "application/mediaservercontrol+xml",
["metalink"] = "application/metalink+xml",
["meta4"] = "application/metalink4+xml",
["mets"] = "application/mets+xml",
["mods"] = "application/mods+xml",
["m21"] = "application/mp21",
["mp4s"] = "application/mp4",
["doc"] = "application/msword",
["mxf"] = "application/mxf",
["bin"] = "application/octet-stream",
["oda"] = "application/oda",
["opf"] = "application/oebps-package+xml",
["ogx"] = "application/ogg",
["omdoc"] = "application/omdoc+xml",
["onetoc"] = "application/onenote",
["oxps"] = "application/oxps",
["xer"] = "application/patch-ops-error+xml",
["pdf"] = "application/pdf",
["pgp"] = "application/pgp-encrypted",
["asc"] = "application/pgp-signature",
["prf"] = "application/pics-rules",
["p10"] = "application/pkcs10",
["p7m"] = "application/pkcs7-mime",
["p7s"] = "application/pkcs7-signature",
["p8"] = "application/pkcs8",
["ac"] = "application/pkix-attr-cert",
["cer"] = "application/pkix-cert",
["crl"] = "application/pkix-crl",
["pkipath"] = "application/pkix-pkipath",
["pki"] = "application/pkixcmp",
["pls"] = "application/pls+xml",
["ai"] = "application/postscript",
["cww"] = "application/prs.cww",
["pskcxml"] = "application/pskc+xml",
["rdf"] = "application/rdf+xml",
["rif"] = "application/reginfo+xml",
["rnc"] = "application/relax-ng-compact-syntax",
["rl"] = "application/resource-lists+xml",
["rld"] = "application/resource-lists-diff+xml",
["rs"] = "application/rls-services+xml",
["gbr"] = "application/rpki-ghostbusters",
["mft"] = "application/rpki-manifest",
["roa"] = "application/rpki-roa",
["rsd"] = "application/rsd+xml",
["rss"] = "application/rss+xml",
["rtf"] = "application/rtf",
["sbml"] = "application/sbml+xml",
["scq"] = "application/scvp-cv-request",
["scs"] = "application/scvp-cv-response",
["spq"] = "application/scvp-vp-request",
["spp"] = "application/scvp-vp-response",
["sdp"] = "application/sdp",
["setpay"] = "application/set-payment-initiation",
["setreg"] = "application/set-registration-initiation",
["shf"] = "application/shf+xml",
["smi"] = "application/smil+xml",
["rq"] = "application/sparql-query",
["srx"] = "application/sparql-results+xml",
["gram"] = "application/srgs",
["grxml"] = "application/srgs+xml",
["sru"] = "application/sru+xml",
["ssdl"] = "application/ssdl+xml",
["ssml"] = "application/ssml+xml",
["tei"] = "application/tei+xml",
["tfi"] = "application/thraud+xml",
["tsd"] = "application/timestamped-data",
["plb"] = "application/vnd.3gpp.pic-bw-large",
["psb"] = "application/vnd.3gpp.pic-bw-small",
["pvb"] = "application/vnd.3gpp.pic-bw-var",
["tcap"] = "application/vnd.3gpp2.tcap",
["pwn"] = "application/vnd.3m.post-it-notes",
["aso"] = "application/vnd.accpac.simply.aso",
["imp"] = "application/vnd.accpac.simply.imp",
["acu"] = "application/vnd.acucobol",
["atc"] = "application/vnd.acucorp",
["air"] = "application/vnd.adobe.air-application-installer-package+zip",
["fcdt"] = "application/vnd.adobe.formscentral.fcdt",
["fxp"] = "application/vnd.adobe.fxp",
["xdp"] = "application/vnd.adobe.xdp+xml",
["xfdf"] = "application/vnd.adobe.xfdf",
["ahead"] = "application/vnd.ahead.space",
["azf"] = "application/vnd.airzip.filesecure.azf",
["azs"] = "application/vnd.airzip.filesecure.azs",
["azw"] = "application/vnd.amazon.ebook",
["acc"] = "application/vnd.americandynamics.acc",
["ami"] = "application/vnd.amiga.ami",
["apk"] = "application/vnd.android.package-archive",
["cii"] = "application/vnd.anser-web-certificate-issue-initiation",
["fti"] = "application/vnd.anser-web-funds-transfer-initiation",
["atx"] = "application/vnd.antix.game-component",
["mpkg"] = "application/vnd.apple.installer+xml",
["m3u8"] = "application/vnd.apple.mpegurl",
["swi"] = "application/vnd.aristanetworks.swi",
["iota"] = "application/vnd.astraea-software.iota",
["aep"] = "application/vnd.audiograph",
["mpm"] = "application/vnd.blueice.multipass",
["bmi"] = "application/vnd.bmi",
["rep"] = "application/vnd.businessobjects",
["cdxml"] = "application/vnd.chemdraw+xml",
["mmd"] = "application/vnd.chipnuts.karaoke-mmd",
["cdy"] = "application/vnd.cinderella",
["cla"] = "application/vnd.claymore",
["rp9"] = "application/vnd.cloanto.rp9",
["c4g"] = "application/vnd.clonk.c4group",
["c11amc"] = "application/vnd.cluetrust.cartomobile-config",
["c11amz"] = "application/vnd.cluetrust.cartomobile-config-pkg",
["csp"] = "application/vnd.commonspace",
["cdbcmsg"] = "application/vnd.contact.cmsg",
["cmc"] = "application/vnd.cosmocaller",
["clkx"] = "application/vnd.crick.clicker",
["clkk"] = "application/vnd.crick.clicker.keyboard",
["clkp"] = "application/vnd.crick.clicker.palette",
["clkt"] = "application/vnd.crick.clicker.template",
["clkw"] = "application/vnd.crick.clicker.wordbank",
["wbs"] = "application/vnd.criticaltools.wbs+xml",
["pml"] = "application/vnd.ctc-posml",
["ppd"] = "application/vnd.cups-ppd",
["car"] = "application/vnd.curl.car",
["pcurl"] = "application/vnd.curl.pcurl",
["dart"] = "application/vnd.dart",
["rdz"] = "application/vnd.data-vision.rdz",
["uvf"] = "application/vnd.dece.data",
["uvt"] = "application/vnd.dece.ttml+xml",
["uvx"] = "application/vnd.dece.unspecified",
["uvz"] = "application/vnd.dece.zip",
["fe_launch"] = "application/vnd.denovo.fcselayout-link",
["dna"] = "application/vnd.dna",
["mlp"] = "application/vnd.dolby.mlp",
["dpg"] = "application/vnd.dpgraph",
["dfac"] = "application/vnd.dreamfactory",
["kpxx"] = "application/vnd.ds-keypoint",
["ait"] = "application/vnd.dvb.ait",
["svc"] = "application/vnd.dvb.service",
["geo"] = "application/vnd.dynageo",
["mag"] = "application/vnd.ecowin.chart",
["nml"] = "application/vnd.enliven",
["esf"] = "application/vnd.epson.esf",
["msf"] = "application/vnd.epson.msf",
["qam"] = "application/vnd.epson.quickanime",
["slt"] = "application/vnd.epson.salt",
["ssf"] = "application/vnd.epson.ssf",
["es3"] = "application/vnd.eszigno3+xml",
["ez2"] = "application/vnd.ezpix-album",
["ez3"] = "application/vnd.ezpix-package",
["fdf"] = "application/vnd.fdf",
["mseed"] = "application/vnd.fdsn.mseed",
["seed"] = "application/vnd.fdsn.seed",
["gph"] = "application/vnd.flographit",
["ftc"] = "application/vnd.fluxtime.clip",
["fm"] = "application/vnd.framemaker",
["fnc"] = "application/vnd.frogans.fnc",
["ltf"] = "application/vnd.frogans.ltf",
["fsc"] = "application/vnd.fsc.weblaunch",
["oas"] = "application/vnd.fujitsu.oasys",
["oa2"] = "application/vnd.fujitsu.oasys2",
["oa3"] = "application/vnd.fujitsu.oasys3",
["fg5"] = "application/vnd.fujitsu.oasysgp",
["bh2"] = "application/vnd.fujitsu.oasysprs",
["ddd"] = "application/vnd.fujixerox.ddd",
["xdw"] = "application/vnd.fujixerox.docuworks",
["xbd"] = "application/vnd.fujixerox.docuworks.binder",
["fzs"] = "application/vnd.fuzzysheet",
["txd"] = "application/vnd.genomatix.tuxedo",
["ggb"] = "application/vnd.geogebra.file",
["ggt"] = "application/vnd.geogebra.tool",
["gex"] = "application/vnd.geometry-explorer",
["gxt"] = "application/vnd.geonext",
["g2w"] = "application/vnd.geoplan",
["g3w"] = "application/vnd.geospace",
["gmx"] = "application/vnd.gmx",
["kml"] = "application/vnd.google-earth.kml+xml",
["kmz"] = "application/vnd.google-earth.kmz",
["gqf"] = "application/vnd.grafeq",
["gac"] = "application/vnd.groove-account",
["ghf"] = "application/vnd.groove-help",
["gim"] = "application/vnd.groove-identity-message",
["grv"] = "application/vnd.groove-injector",
["gtm"] = "application/vnd.groove-tool-message",
["tpl"] = "application/vnd.groove-tool-template",
["vcg"] = "application/vnd.groove-vcard",
["hal"] = "application/vnd.hal+xml",
["zmm"] = "application/vnd.handheld-entertainment+xml",
["hbci"] = "application/vnd.hbci",
["les"] = "application/vnd.hhe.lesson-player",
["hpgl"] = "application/vnd.hp-hpgl",
["hpid"] = "application/vnd.hp-hpid",
["hps"] = "application/vnd.hp-hps",
["jlt"] = "application/vnd.hp-jlyt",
["pcl"] = "application/vnd.hp-pcl",
["pclxl"] = "application/vnd.hp-pclxl",
["sfd-hdstx"] = "application/vnd.hydrostatix.sof-data",
["mpy"] = "application/vnd.ibm.minipay",
["afp"] = "application/vnd.ibm.modcap",
["irm"] = "application/vnd.ibm.rights-management",
["sc"] = "application/vnd.ibm.secure-container",
["icc"] = "application/vnd.iccprofile",
["igl"] = "application/vnd.igloader",
["ivp"] = "application/vnd.immervision-ivp",
["ivu"] = "application/vnd.immervision-ivu",
["igm"] = "application/vnd.insors.igm",
["xpw"] = "application/vnd.intercon.formnet",
["i2g"] = "application/vnd.intergeo",
["qbo"] = "application/vnd.intu.qbo",
["qfx"] = "application/vnd.intu.qfx",
["rcprofile"] = "application/vnd.ipunplugged.rcprofile",
["irp"] = "application/vnd.irepository.package+xml",
["xpr"] = "application/vnd.is-xpr",
["fcs"] = "application/vnd.isac.fcs",
["jam"] = "application/vnd.jam",
["rms"] = "application/vnd.jcp.javame.midlet-rms",
["jisp"] = "application/vnd.jisp",
["joda"] = "application/vnd.joost.joda-archive",
["ktz"] = "application/vnd.kahootz",
["karbon"] = "application/vnd.kde.karbon",
["chrt"] = "application/vnd.kde.kchart",
["kfo"] = "application/vnd.kde.kformula",
["flw"] = "application/vnd.kde.kivio",
["kon"] = "application/vnd.kde.kontour",
["kpr"] = "application/vnd.kde.kpresenter",
["ksp"] = "application/vnd.kde.kspread",
["kwd"] = "application/vnd.kde.kword",
["htke"] = "application/vnd.kenameaapp",
["kia"] = "application/vnd.kidspiration",
["kne"] = "application/vnd.kinar",
["skp"] = "application/vnd.koan",
["sse"] = "application/vnd.kodak-descriptor",
["lasxml"] = "application/vnd.las.las+xml",
["lbd"] = "application/vnd.llamagraphics.life-balance.desktop",
["lbe"] = "application/vnd.llamagraphics.life-balance.exchange+xml",
["123"] = "application/vnd.lotus-1-2-3",
["apr"] = "application/vnd.lotus-approach",
["pre"] = "application/vnd.lotus-freelance",
["nsf"] = "application/vnd.lotus-notes",
["org"] = "application/vnd.lotus-organizer",
["scm"] = "application/vnd.lotus-screencam",
["lwp"] = "application/vnd.lotus-wordpro",
["portpkg"] = "application/vnd.macports.portpkg",
["mcd"] = "application/vnd.mcd",
["mc1"] = "application/vnd.medcalcdata",
["cdkey"] = "application/vnd.mediastation.cdkey",
["mwf"] = "application/vnd.mfer",
["mfm"] = "application/vnd.mfmp",
["flo"] = "application/vnd.micrografx.flo",
["igx"] = "application/vnd.micrografx.igx",
["mif"] = "application/vnd.mif",
["daf"] = "application/vnd.mobius.daf",
["dis"] = "application/vnd.mobius.dis",
["mbk"] = "application/vnd.mobius.mbk",
["mqy"] = "application/vnd.mobius.mqy",
["msl"] = "application/vnd.mobius.msl",
["plc"] = "application/vnd.mobius.plc",
["txf"] = "application/vnd.mobius.txf",
["mpn"] = "application/vnd.mophun.application",
["mpc"] = "application/vnd.mophun.certificate",
["xul"] = "application/vnd.mozilla.xul+xml",
["cil"] = "application/vnd.ms-artgalry",
["cab"] = "application/vnd.ms-cab-compressed",
["xls"] = "application/vnd.ms-excel",
["xlam"] = "application/vnd.ms-excel.addin.macroenabled.12",
["xlsb"] = "application/vnd.ms-excel.sheet.binary.macroenabled.12",
["xlsm"] = "application/vnd.ms-excel.sheet.macroenabled.12",
["xltm"] = "application/vnd.ms-excel.template.macroenabled.12",
["eot"] = "application/vnd.ms-fontobject",
["chm"] = "application/vnd.ms-htmlhelp",
["ims"] = "application/vnd.ms-ims",
["lrm"] = "application/vnd.ms-lrm",
["thmx"] = "application/vnd.ms-officetheme",
["cat"] = "application/vnd.ms-pki.seccat",
["stl"] = "application/vnd.ms-pki.stl",
["ppt"] = "application/vnd.ms-powerpoint",
["ppam"] = "application/vnd.ms-powerpoint.addin.macroenabled.12",
["pptm"] = "application/vnd.ms-powerpoint.presentation.macroenabled.12",
["sldm"] = "application/vnd.ms-powerpoint.slide.macroenabled.12",
["ppsm"] = "application/vnd.ms-powerpoint.slideshow.macroenabled.12",
["potm"] = "application/vnd.ms-powerpoint.template.macroenabled.12",
["mpp"] = "application/vnd.ms-project",
["docm"] = "application/vnd.ms-word.document.macroenabled.12",
["dotm"] = "application/vnd.ms-word.template.macroenabled.12",
["wps"] = "application/vnd.ms-works",
["wpl"] = "application/vnd.ms-wpl",
["xps"] = "application/vnd.ms-xpsdocument",
["mseq"] = "application/vnd.mseq",
["mus"] = "application/vnd.musician",
["msty"] = "application/vnd.muvee.style",
["taglet"] = "application/vnd.mynfc",
["nlu"] = "application/vnd.neurolanguage.nlu",
["ntf"] = "application/vnd.nitf",
["nnd"] = "application/vnd.noblenet-directory",
["nns"] = "application/vnd.noblenet-sealer",
["nnw"] = "application/vnd.noblenet-web",
["ngdat"] = "application/vnd.nokia.n-gage.data",
["n-gage"] = "application/vnd.nokia.n-gage.symbian.install",
["rpst"] = "application/vnd.nokia.radio-preset",
["rpss"] = "application/vnd.nokia.radio-presets",
["edm"] = "application/vnd.novadigm.edm",
["edx"] = "application/vnd.novadigm.edx",
["ext"] = "application/vnd.novadigm.ext",
["odc"] = "application/vnd.oasis.opendocument.chart",
["otc"] = "application/vnd.oasis.opendocument.chart-template",
["odb"] = "application/vnd.oasis.opendocument.database",
["odf"] = "application/vnd.oasis.opendocument.formula",
["odft"] = "application/vnd.oasis.opendocument.formula-template",
["odg"] = "application/vnd.oasis.opendocument.graphics",
["otg"] = "application/vnd.oasis.opendocument.graphics-template",
["odi"] = "application/vnd.oasis.opendocument.image",
["oti"] = "application/vnd.oasis.opendocument.image-template",
["odp"] = "application/vnd.oasis.opendocument.presentation",
["otp"] = "application/vnd.oasis.opendocument.presentation-template",
["ods"] = "application/vnd.oasis.opendocument.spreadsheet",
["ots"] = "application/vnd.oasis.opendocument.spreadsheet-template",
["odt"] = "application/vnd.oasis.opendocument.text",
["odm"] = "application/vnd.oasis.opendocument.text-master",
["ott"] = "application/vnd.oasis.opendocument.text-template",
["oth"] = "application/vnd.oasis.opendocument.text-web",
["xo"] = "application/vnd.olpc-sugar",
["dd2"] = "application/vnd.oma.dd2+xml",
["oxt"] = "application/vnd.openofficeorg.extension",
["pptx"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
["sldx"] = "application/vnd.openxmlformats-officedocument.presentationml.slide",
["ppsx"] = "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
["potx"] = "application/vnd.openxmlformats-officedocument.presentationml.template",
["xlsx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
["xltx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
["docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
["dotx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
["mgp"] = "application/vnd.osgeo.mapguide.package",
["dp"] = "application/vnd.osgi.dp",
["esa"] = "application/vnd.osgi.subsystem",
["pdb"] = "application/vnd.palm",
["paw"] = "application/vnd.pawaafile",
["str"] = "application/vnd.pg.format",
["ei6"] = "application/vnd.pg.osasli",
["efif"] = "application/vnd.picsel",
["wg"] = "application/vnd.pmi.widget",
["plf"] = "application/vnd.pocketlearn",
["pbd"] = "application/vnd.powerbuilder6",
["box"] = "application/vnd.previewsystems.box",
["mgz"] = "application/vnd.proteus.magazine",
["qps"] = "application/vnd.publishare-delta-tree",
["ptid"] = "application/vnd.pvi.ptid1",
["qxd"] = "application/vnd.quark.quarkxpress",
["bed"] = "application/vnd.realvnc.bed",
["mxl"] = "application/vnd.recordare.musicxml",
["musicxml"] = "application/vnd.recordare.musicxml+xml",
["cryptonote"] = "application/vnd.rig.cryptonote",
["cod"] = "application/vnd.rim.cod",
["rm"] = "application/vnd.rn-realmedia",
["rmvb"] = "application/vnd.rn-realmedia-vbr",
["link66"] = "application/vnd.route66.link66+xml",
["st"] = "application/vnd.sailingtracker.track",
["see"] = "application/vnd.seemail",
["sema"] = "application/vnd.sema",
["semd"] = "application/vnd.semd",
["semf"] = "application/vnd.semf",
["ifm"] = "application/vnd.shana.informed.formdata",
["itp"] = "application/vnd.shana.informed.formtemplate",
["iif"] = "application/vnd.shana.informed.interchange",
["ipk"] = "application/vnd.shana.informed.package",
["twd"] = "application/vnd.simtech-mindmapper",
["mmf"] = "application/vnd.smaf",
["teacher"] = "application/vnd.smart.teacher",
["sdkm"] = "application/vnd.solent.sdkm+xml",
["dxp"] = "application/vnd.spotfire.dxp",
["sfs"] = "application/vnd.spotfire.sfs",
["sdc"] = "application/vnd.stardivision.calc",
["sda"] = "application/vnd.stardivision.draw",
["sdd"] = "application/vnd.stardivision.impress",
["smf"] = "application/vnd.stardivision.math",
["sdw"] = "application/vnd.stardivision.writer",
["sgl"] = "application/vnd.stardivision.writer-global",
["smzip"] = "application/vnd.stepmania.package",
["sm"] = "application/vnd.stepmania.stepchart",
["sxc"] = "application/vnd.sun.xml.calc",
["stc"] = "application/vnd.sun.xml.calc.template",
["sxd"] = "application/vnd.sun.xml.draw",
["std"] = "application/vnd.sun.xml.draw.template",
["sxi"] = "application/vnd.sun.xml.impress",
["sti"] = "application/vnd.sun.xml.impress.template",
["sxm"] = "application/vnd.sun.xml.math",
["sxw"] = "application/vnd.sun.xml.writer",
["sxg"] = "application/vnd.sun.xml.writer.global",
["stw"] = "application/vnd.sun.xml.writer.template",
["sus"] = "application/vnd.sus-calendar",
["svd"] = "application/vnd.svd",
["sis"] = "application/vnd.symbian.install",
["xsm"] = "application/vnd.syncml+xml",
["bdm"] = "application/vnd.syncml.dm+wbxml",
["xdm"] = "application/vnd.syncml.dm+xml",
["tao"] = "application/vnd.tao.intent-module-archive",
["pcap"] = "application/vnd.tcpdump.pcap",
["tmo"] = "application/vnd.tmobile-livetv",
["tpt"] = "application/vnd.trid.tpt",
["mxs"] = "application/vnd.triscape.mxs",
["tra"] = "application/vnd.trueapp",
["ufd"] = "application/vnd.ufdl",
["utz"] = "application/vnd.uiq.theme",
["umj"] = "application/vnd.umajin",
["unity3d"] = "application/vnd.unity3d",
["unityweb"] = "application/vnd.unity",
["uoml"] = "application/vnd.uoml+xml",
["vcx"] = "application/vnd.vcx",
["vsd"] = "application/vnd.visio",
["vis"] = "application/vnd.visionary",
["vsf"] = "application/vnd.vsf",
["wbxml"] = "application/vnd.wap.wbxml",
["wmlc"] = "application/vnd.wap.wmlc",
["wmlsc"] = "application/vnd.wap.wmlscriptc",
["wtb"] = "application/vnd.webturbo",
["nbp"] = "application/vnd.wolfram.player",
["wpd"] = "application/vnd.wordperfect",
["wqd"] = "application/vnd.wqd",
["stf"] = "application/vnd.wt.stf",
["xar"] = "application/vnd.xara",
["xfdl"] = "application/vnd.xfdl",
["hvd"] = "application/vnd.yamaha.hv-dic",
["hvs"] = "application/vnd.yamaha.hv-script",
["hvp"] = "application/vnd.yamaha.hv-voice",
["osf"] = "application/vnd.yamaha.openscoreformat",
["osfpvg"] = "application/vnd.yamaha.openscoreformat.osfpvg+xml",
["saf"] = "application/vnd.yamaha.smaf-audio",
["spf"] = "application/vnd.yamaha.smaf-phrase",
["cmp"] = "application/vnd.yellowriver-custom-menu",
["zir"] = "application/vnd.zul",
["zaz"] = "application/vnd.zzazz.deck+xml",
["vxml"] = "application/voicexml+xml",
["wgt"] = "application/widget",
["hlp"] = "application/winhlp",
["wsdl"] = "application/wsdl+xml",
["wspolicy"] = "application/wspolicy+xml",
["7z"] = "application/x-7z-compressed",
["abw"] = "application/x-abiword",
["ace"] = "application/x-ace-compressed",
["dmg"] = "application/x-apple-diskimage",
["aab"] = "application/x-authorware-bin",
["aam"] = "application/x-authorware-map",
["aas"] = "application/x-authorware-seg",
["bcpio"] = "application/x-bcpio",
["torrent"] = "application/x-bittorrent",
["blb"] = "application/x-blorb",
["bz"] = "application/x-bzip",
["bz2"] = "application/x-bzip2",
["cbr"] = "application/x-cbr",
["vcd"] = "application/x-cdlink",
["cfs"] = "application/x-cfs-compressed",
["chat"] = "application/x-chat",
["pgn"] = "application/x-chess-pgn",
["nsc"] = "application/x-conference",
["cpio"] = "application/x-cpio",
["csh"] = "application/x-csh",
["deb"] = "application/x-debian-package",
["dgc"] = "application/x-dgc-compressed",
["dir"] = "application/x-director",
["wad"] = "application/x-doom",
["ncx"] = "application/x-dtbncx+xml",
["dtb"] = "application/x-dtbook+xml",
["res"] = "application/x-dtbresource+xml",
["dvi"] = "application/x-dvi",
["evy"] = "application/x-envoy",
["eva"] = "application/x-eva",
["bdf"] = "application/x-font-bdf",
["gsf"] = "application/x-font-ghostscript",
["psf"] = "application/x-font-linux-psf",
["otf"] = "application/x-font-otf",
["pcf"] = "application/x-font-pcf",
["snf"] = "application/x-font-snf",
["ttf"] = "application/x-font-ttf",
["pfa"] = "application/x-font-type1",
["arc"] = "application/x-freearc",
["spl"] = "application/x-futuresplash",
["gca"] = "application/x-gca-compressed",
["ulx"] = "application/x-glulx",
["gnumeric"] = "application/x-gnumeric",
["gramps"] = "application/x-gramps-xml",
["gtar"] = "application/x-gtar",
["hdf"] = "application/x-hdf",
["install"] = "application/x-install-instructions",
["iso"] = "application/x-iso9660-image",
["jnlp"] = "application/x-java-jnlp-file",
["latex"] = "application/x-latex",
["lzh"] = "application/x-lzh-compressed",
["mie"] = "application/x-mie",
["prc"] = "application/x-mobipocket-ebook",
["application"] = "application/x-ms-application",
["lnk"] = "application/x-ms-shortcut",
["wmd"] = "application/x-ms-wmd",
["wmz"] = "application/x-ms-wmz",
["xbap"] = "application/x-ms-xbap",
["mdb"] = "application/x-msaccess",
["obd"] = "application/x-msbinder",
["crd"] = "application/x-mscardfile",
["clp"] = "application/x-msclip",
["exe"] = "application/x-msdownload",
["mvb"] = "application/x-msmediaview",
["wmf"] = "application/x-msmetafile",
["mny"] = "application/x-msmoney",
["pub"] = "application/x-mspublisher",
["scd"] = "application/x-msschedule",
["trm"] = "application/x-msterminal",
["wri"] = "application/x-mswrite",
["nc"] = "application/x-netcdf",
["nzb"] = "application/x-nzb",
["p12"] = "application/x-pkcs12",
["p7b"] = "application/x-pkcs7-certificates",
["p7r"] = "application/x-pkcs7-certreqresp",
["rar"] = "application/x-rar-compressed",
["ris"] = "application/x-research-info-systems",
["sh"] = "application/x-sh",
["shar"] = "application/x-shar",
["swf"] = "application/x-shockwave-flash",
["xap"] = "application/x-silverlight-app",
["sql"] = "application/x-sql",
["sit"] = "application/x-stuffit",
["sitx"] = "application/x-stuffitx",
["srt"] = "application/x-subrip",
["sv4cpio"] = "application/x-sv4cpio",
["sv4crc"] = "application/x-sv4crc",
["t3"] = "application/x-t3vm-image",
["gam"] = "application/x-tads",
["tar"] = "application/x-tar",
["tcl"] = "application/x-tcl",
["tex"] = "application/x-tex",
["tfm"] = "application/x-tex-tfm",
["texinfo"] = "application/x-texinfo",
["obj"] = "application/x-tgif",
["ustar"] = "application/x-ustar",
["src"] = "application/x-wais-source",
["der"] = "application/x-x509-ca-cert",
["fig"] = "application/x-xfig",
["xlf"] = "application/x-xliff+xml",
["xpi"] = "application/x-xpinstall",
["xz"] = "application/x-xz",
["z1"] = "application/x-zmachine",
["xaml"] = "application/xaml+xml",
["xdf"] = "application/xcap-diff+xml",
["xenc"] = "application/xenc+xml",
["xhtml"] = "application/xhtml+xml",
["xml"] = "application/xml",
["dtd"] = "application/xml-dtd",
["xop"] = "application/xop+xml",
["xpl"] = "application/xproc+xml",
["xslt"] = "application/xslt+xml",
["xspf"] = "application/xspf+xml",
["mxml"] = "application/xv+xml",
["yang"] = "application/yang",
["yin"] = "application/yin+xml",
["zip"] = "application/zip",
["adp"] = "audio/adpcm",
["au"] = "audio/basic",
["mid"] = "audio/midi",
["m4a"] = "audio/mp4",
["mpga"] = "audio/mpeg",
["oga"] = "audio/ogg",
["s3m"] = "audio/s3m",
["sil"] = "audio/silk",
["uva"] = "audio/vnd.dece.audio",
["eol"] = "audio/vnd.digital-winds",
["dra"] = "audio/vnd.dra",
["dts"] = "audio/vnd.dts",
["dtshd"] = "audio/vnd.dts.hd",
["lvp"] = "audio/vnd.lucent.voice",
["pya"] = "audio/vnd.ms-playready.media.pya",
["ecelp4800"] = "audio/vnd.nuera.ecelp4800",
["ecelp7470"] = "audio/vnd.nuera.ecelp7470",
["ecelp9600"] = "audio/vnd.nuera.ecelp9600",
["rip"] = "audio/vnd.rip",
["weba"] = "audio/webm",
["aac"] = "audio/x-aac",
["aif"] = "audio/x-aiff",
["caf"] = "audio/x-caf",
["flac"] = "audio/x-flac",
["mka"] = "audio/x-matroska",
["m3u"] = "audio/x-mpegurl",
["wax"] = "audio/x-ms-wax",
["wma"] = "audio/x-ms-wma",
["ram"] = "audio/x-pn-realaudio",
["rmp"] = "audio/x-pn-realaudio-plugin",
["wav"] = "audio/x-wav",
["xm"] = "audio/xm",
["cdx"] = "chemical/x-cdx",
["cif"] = "chemical/x-cif",
["cmdf"] = "chemical/x-cmdf",
["cml"] = "chemical/x-cml",
["csml"] = "chemical/x-csml",
["xyz"] = "chemical/x-xyz",
["bmp"] = "image/bmp",
["cgm"] = "image/cgm",
["g3"] = "image/g3fax",
["gif"] = "image/gif",
["ief"] = "image/ief",
["jpeg"] = "image/jpeg",
["jpg"] = "image/jpeg",
["ktx"] = "image/ktx",
["png"] = "image/png",
["btif"] = "image/prs.btif",
["sgi"] = "image/sgi",
["svg"] = "image/svg+xml",
["tiff"] = "image/tiff",
["psd"] = "image/vnd.adobe.photoshop",
["uvi"] = "image/vnd.dece.graphic",
["djvu"] = "image/vnd.djvu",
["sub"] = "image/vnd.dvb.subtitle",
["dwg"] = "image/vnd.dwg",
["dxf"] = "image/vnd.dxf",
["fbs"] = "image/vnd.fastbidsheet",
["fpx"] = "image/vnd.fpx",
["fst"] = "image/vnd.fst",
["mmr"] = "image/vnd.fujixerox.edmics-mmr",
["rlc"] = "image/vnd.fujixerox.edmics-rlc",
["mdi"] = "image/vnd.ms-modi",
["wdp"] = "image/vnd.ms-photo",
["npx"] = "image/vnd.net-fpx",
["wbmp"] = "image/vnd.wap.wbmp",
["xif"] = "image/vnd.xiff",
["webp"] = "image/webp",
["3ds"] = "image/x-3ds",
["ras"] = "image/x-cmu-raster",
["cmx"] = "image/x-cmx",
["fh"] = "image/x-freehand",
["ico"] = "image/x-icon",
["sid"] = "image/x-mrsid-image",
["pcx"] = "image/x-pcx",
["pic"] = "image/x-pict",
["pnm"] = "image/x-portable-anymap",
["pbm"] = "image/x-portable-bitmap",
["pgm"] = "image/x-portable-graymap",
["ppm"] = "image/x-portable-pixmap",
["rgb"] = "image/x-rgb",
["tga"] = "image/x-tga",
["xbm"] = "image/x-xbitmap",
["xpm"] = "image/x-xpixmap",
["xwd"] = "image/x-xwindowdump",
["eml"] = "message/rfc822",
["igs"] = "model/iges",
["msh"] = "model/mesh",
["dae"] = "model/vnd.collada+xml",
["dwf"] = "model/vnd.dwf",
["gdl"] = "model/vnd.gdl",
["gtw"] = "model/vnd.gtw",
["mts"] = "model/vnd.mts",
["vtu"] = "model/vnd.vtu",
["wrl"] = "model/vrml",
["x3db"] = "model/x3d+binary",
["x3dv"] = "model/x3d+vrml",
["x3d"] = "model/x3d+xml",
["appcache"] = "text/cache-manifest",
["ics"] = "text/calendar",
["css"] = "text/css",
["csv"] = "text/csv",
["html"] = "text/html",
["n3"] = "text/n3",
["txt"] = "text/plain",
["dsc"] = "text/prs.lines.tag",
["rtx"] = "text/richtext",
["sgml"] = "text/sgml",
["tsv"] = "text/tab-separated-values",
["t"] = "text/troff",
["ttl"] = "text/turtle",
["uri"] = "text/uri-list",
["vcard"] = "text/vcard",
["curl"] = "text/vnd.curl",
["dcurl"] = "text/vnd.curl.dcurl",
["mcurl"] = "text/vnd.curl.mcurl",
["scurl"] = "text/vnd.curl.scurl",
["fly"] = "text/vnd.fly",
["flx"] = "text/vnd.fmi.flexstor",
["gv"] = "text/vnd.graphviz",
["3dml"] = "text/vnd.in3d.3dml",
["spot"] = "text/vnd.in3d.spot",
["jad"] = "text/vnd.sun.j2me.app-descriptor",
["wml"] = "text/vnd.wap.wml",
["wmls"] = "text/vnd.wap.wmlscript",
["s"] = "text/x-asm",
["c"] = "text/x-c",
["f"] = "text/x-fortran",
["java"] = "text/x-java-source",
["nfo"] = "text/x-nfo",
["opml"] = "text/x-opml",
["p"] = "text/x-pascal",
["etx"] = "text/x-setext",
["sfv"] = "text/x-sfv",
["uu"] = "text/x-uuencode",
["vcs"] = "text/x-vcalendar",
["vcf"] = "text/x-vcard",
["3gp"] = "video/3gpp",
["3g2"] = "video/3gpp2",
["h261"] = "video/h261",
["h263"] = "video/h263",
["h264"] = "video/h264",
["jpgv"] = "video/jpeg",
["jpm"] = "video/jpm",
["mj2"] = "video/mj2",
["mp4"] = "video/mp4",
["mpeg"] = "video/mpeg",
["ogv"] = "video/ogg",
["qt"] = "video/quicktime",
["uvh"] = "video/vnd.dece.hd",
["uvm"] = "video/vnd.dece.mobile",
["uvp"] = "video/vnd.dece.pd",
["uvs"] = "video/vnd.dece.sd",
["uvv"] = "video/vnd.dece.video",
["dvb"] = "video/vnd.dvb.file",
["fvt"] = "video/vnd.fvt",
["mxu"] = "video/vnd.mpegurl",
["pyv"] = "video/vnd.ms-playready.media.pyv",
["uvu"] = "video/vnd.uvvu.mp4",
["viv"] = "video/vnd.vivo",
["webm"] = "video/webm",
["f4v"] = "video/x-f4v",
["fli"] = "video/x-fli",
["flv"] = "video/x-flv",
["m4v"] = "video/x-m4v",
["mkv"] = "video/x-matroska",
["mng"] = "video/x-mng",
["asf"] = "video/x-ms-asf",
["vob"] = "video/x-ms-vob",
["wm"] = "video/x-ms-wm",
["wmv"] = "video/x-ms-wmv",
["wmx"] = "video/x-ms-wmx",
["wvx"] = "video/x-ms-wvx",
["avi"] = "video/x-msvideo",
["movie"] = "video/x-sgi-movie",
["smv"] = "video/x-smv",
["ice"] = "x-conference/x-cooltalk",
["cr2"] = "image/x-canon-cr2",
["mov"] = "video/quicktime"
};
#endregion
#region Constructors
// TODO V3: Add a ctor that accepts a logger and wrap the public method bodies in try...catch.
#endregion
#region IMimeTypeUtility Members
/// <summary>
/// Gets the MIME Type of the specified filename or extension.
/// If the extension cannot be identified then the default type of application/octet-stream will be returned.
/// </summary>
/// <param name="fileNameOrExtension">The file name or extension.</param>
public virtual string GetMimeType(string fileNameOrExtension)
{
Guard.ArgumentNotNullOrWhiteSpace(fileNameOrExtension, nameof(fileNameOrExtension));
fileNameOrExtension = fileNameOrExtension.Trim().ToLowerInvariant();
//Assume the filename is the extension
//If it contains any . chars run it through the Path utility method.
fileNameOrExtension = fileNameOrExtension.IndexOf('.') == -1 ? fileNameOrExtension : Path.GetExtension(fileNameOrExtension).TrimStart('.');
if (string.IsNullOrWhiteSpace(fileNameOrExtension))
return _defaultMimeType;
if (_mimeTypeDictionary.TryGetValue(fileNameOrExtension, out string mimeType))
return mimeType;
return _defaultMimeType;
}
#endregion
}
} | 41.558394 | 142 | 0.61178 | [
"MIT"
] | Zinofi/umbrella | Core/src/Umbrella.Utilities/Mime/MimeTypeUtility.cs | 34,163 | 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.
#nullable enable
namespace System.Runtime.InteropServices.ComTypes
{
[StructLayout(LayoutKind.Sequential)]
public struct FILETIME
{
public int dwLowDateTime;
public int dwHighDateTime;
}
[Guid("0000000f-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IMoniker
{
// IPersist portion
void GetClassID(out Guid pClassID);
// IPersistStream portion
[PreserveSig]
int IsDirty();
void Load(IStream pStm);
void Save(IStream pStm, [MarshalAs(UnmanagedType.Bool)] bool fClearDirty);
void GetSizeMax(out long pcbSize);
// IMoniker portion
void BindToObject(IBindCtx pbc, IMoniker? pmkToLeft, [In()] ref Guid riidResult, [MarshalAs(UnmanagedType.Interface)] out object ppvResult);
void BindToStorage(IBindCtx pbc, IMoniker? pmkToLeft, [In()] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObj);
void Reduce(IBindCtx pbc, int dwReduceHowFar, ref IMoniker? ppmkToLeft, out IMoniker? ppmkReduced);
void ComposeWith(IMoniker pmkRight, [MarshalAs(UnmanagedType.Bool)] bool fOnlyIfNotGeneric, out IMoniker? ppmkComposite);
void Enum([MarshalAs(UnmanagedType.Bool)] bool fForward, out IEnumMoniker? ppenumMoniker);
[PreserveSig]
int IsEqual(IMoniker pmkOtherMoniker);
void Hash(out int pdwHash);
[PreserveSig]
int IsRunning(IBindCtx pbc, IMoniker? pmkToLeft, IMoniker? pmkNewlyRunning);
void GetTimeOfLastChange(IBindCtx pbc, IMoniker? pmkToLeft, out FILETIME pFileTime);
void Inverse(out IMoniker ppmk);
void CommonPrefixWith(IMoniker pmkOther, out IMoniker? ppmkPrefix);
void RelativePathTo(IMoniker pmkOther, out IMoniker? ppmkRelPath);
void GetDisplayName(IBindCtx pbc, IMoniker? pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] out string ppszDisplayName);
void ParseDisplayName(IBindCtx pbc, IMoniker pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, out int pchEaten, out IMoniker ppmkOut);
[PreserveSig]
int IsSystemMoniker(out int pdwMksys);
}
}
| 47.333333 | 161 | 0.71541 | [
"MIT"
] | AfsanehR-zz/corefx | src/Common/src/CoreLib/System/Runtime/InteropServices/ComTypes/IMoniker.cs | 2,414 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MovilShopStock
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 24.25 | 99 | 0.589347 | [
"MIT"
] | emachado9202/sales_system | MovilShopStock/App_Start/RouteConfig.cs | 584 | C# |
// <auto-generated />
using System;
using BlindDating.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace BlindDating.Migrations
{
[DbContext(typeof(SecurityContext))]
partial class SecurityContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.14-servicing-32113")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider")
.HasMaxLength(128);
b.Property<string>("Name")
.HasMaxLength(128);
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 36 | 126 | 0.471513 | [
"MIT"
] | erne51795/BlindDating.Part1 | SecurityContextModelSnapshot.cs | 8,462 | C# |
namespace Showcase.Data.Common.Models
{
using System;
public interface IAuditInfo
{
DateTime CreatedOn { get; set; }
bool PreserveCreatedOn { get; set; }
DateTime? ModifiedOn { get; set; }
}
}
| 16.928571 | 44 | 0.603376 | [
"MIT"
] | TelerikAcademy/ShowcaseSystem | Source/Data/Showcase.Data.Common/Models/IAuditInfo.cs | 239 | C# |
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
namespace MoqHttp.Interfaces
{
public interface IHttpResponse
{
string Body { get; set; }
Dictionary<string, string> Headers { get; set; }
int StatusCode { get; set; }
Action<HttpContext> Handler { get; set; }
}
}
| 21.375 | 56 | 0.649123 | [
"MIT"
] | KamRon-67/MoqHttp | MoqHttp/Interfaces/IHttpResponse.cs | 344 | C# |
/*
* Todo MVC backend style API
*
* This is a simple API
*
* The version of the OpenAPI document: 1.0.0
* Contact: you@your-company.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
namespace Todos.Client
{
/// <summary>
/// Http methods supported by swagger
/// </summary>
public enum HttpMethod
{
/// <summary>HTTP GET request.</summary>
Get,
/// <summary>HTTP POST request.</summary>
Post,
/// <summary>HTTP PUT request.</summary>
Put,
/// <summary>HTTP DELETE request.</summary>
Delete,
/// <summary>HTTP HEAD request.</summary>
Head,
/// <summary>HTTP OPTIONS request.</summary>
Options,
/// <summary>HTTP PATCH request.</summary>
Patch
}
}
| 23.428571 | 70 | 0.576829 | [
"MIT"
] | wallymathieu/immutable-csharp-studies | openapi/src/Todos/Client/HttpMethod.cs | 820 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace CryptoMining.ApplicationCore.Pool
{
public class ZergAPI
{
/// <summary>
/// Load coin mining data from zerg pool
/// </summary>
/// <returns></returns>
/// <exception cref="Exception">Get data from zergpool web api failed.</exception>
public CryptoCurrency LoadCurrency()
{
try
{
using (var client = new System.Net.Http.HttpClient())
{
// HTTP POST
client.BaseAddress = new Uri("http://api.zergpool.com:8080");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("/api/currencies").Result;
string res = "";
using (HttpContent content = response.Content)
{
// ... Read the string.
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
res = res.Replace("24h_blocks", "h24_blocks").Replace("24h_btc", "h24_btc");
CryptoCurrency coins = JsonConvert.DeserializeObject<CryptoCurrency>(res);
return coins;
}
}
}
catch (Exception err)
{
throw new Exception("Get data from zergpool web api failed.", err);
}
}
/// <summary>
/// Load algorithm status from zerg pool
/// </summary>
/// <returns></returns>
/// <exception cref="Exception">Get data from zergpool web api failed.</exception>
public Algorithm LoadAlgorithm()
{
try
{
using (var client = new System.Net.Http.HttpClient())
{
// HTTP POST
client.BaseAddress = new Uri("http://api.zergpool.com:8080");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("/api/status").Result;
string res = "";
using (HttpContent content = response.Content)
{
// ... Read the string.
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
res = res.Replace("argon2d-dyn", "argon2d_dyn").Replace("myr-gr", "myr_gr").Replace("scrypt-ld", "scrypt_ld");
Algorithm algor = JsonConvert.DeserializeObject<Algorithm>(res);
return algor;
}
}
}
catch (Exception err)
{
throw new Exception("Get algorithm status from zergpool web api failed. [http://api.zergpool.com:8080/api/status]", err);
}
}
}
}
| 39.740741 | 137 | 0.504815 | [
"Apache-2.0"
] | soemsri/HeroMining | ApplicationCore/Pool/ZergAPI.cs | 3,221 | C# |
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace brewjournal.Application.Common.Behaviours
{
public class UnhandledExceptionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly ILogger<TRequest> _logger;
public UnhandledExceptionBehaviour(ILogger<TRequest> logger)
{
_logger = logger;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
try
{
return await next();
}
catch (Exception ex)
{
var requestName = typeof(TRequest).Name;
_logger.LogError(ex, "brewjournal Request: Unhandled Exception for Request {Name} {@Request}", requestName, request);
throw;
}
}
}
}
| 28.171429 | 138 | 0.624746 | [
"MIT"
] | matt-goldman/brewjournal | src/Application/Common/Behaviours/UnhandledExceptionBehaviour.cs | 988 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*============================================================
**
**
** Purpose: Serves as a hint to ngen that the decorated method
** (and its statically determinable call graph) should be
** prepared (as for Constrained Execution Region use). This
** is primarily useful in the scenario where the method in
** question will be prepared explicitly at runtime and the
** author of the method knows this and wishes to avoid the
** overhead of runtime preparation.
**
**
===========================================================*/
namespace System.Runtime.ConstrainedExecution
{
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
public sealed class PrePrepareMethodAttribute : Attribute
{
public PrePrepareMethodAttribute()
{
}
}
}
| 32.21875 | 101 | 0.646945 | [
"MIT"
] | 1Crazymoney/cs2cpp | CoreLib/System/Runtime/Reliability/PrePrepareMethodAttribute.cs | 1,031 | C# |
using MyFilesWin10App.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Foundation.Metadata;
using Windows.UI.Core;
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;
namespace MyFilesWin10App
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
public ObservableCollection<MyFilesModel> Items { get; set; }
public List<MyFilesModel> NavigationStack { get; set; }
public List<MyFilesModel> FileItems
{
get { return Items.Where(i => i.Type != "Folder").ToList(); }
}
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
//initialize the navigation stack
NavigationStack = new List<MyFilesModel>();
(App.Current as App).NavigationStack.Add(new MyFilesModel() { Id = String.Empty, Name = "OneDrive Images" });
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
}
private void MainPage_BackRequested(object sender, BackRequestedEventArgs e)
{
var frame = Window.Current.Content as Frame;
if (frame.CanGoBack)
{
//go back in frame
(App.Current as App).NavigationStack.RemoveAt((App.Current as App).NavigationStack.Count - 1);
frame.GoBack();
e.Handled = true;
}
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
rootFrame.Navigated += (s, a) =>
{
Windows.UI.Core.SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
(rootFrame.CanGoBack) ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
};
Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested += MainPage_BackRequested;
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| 39.520833 | 121 | 0.625901 | [
"MIT"
] | HydAu/WebDevCamp | Presentation/12. Connecting to the Cloud/Demos/OneDrive/MyFilesWin10App/App.xaml.cs | 5,693 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Redis.V1.Snippets
{
// [START redis_v1_generated_CloudRedis_ImportInstance_sync_flattened]
using Google.Cloud.Redis.V1;
using Google.LongRunning;
public sealed partial class GeneratedCloudRedisClientSnippets
{
/// <summary>Snippet for ImportInstance</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void ImportInstance()
{
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
string name = "";
InputConfig inputConfig = new InputConfig();
// Make the request
Operation<Instance, OperationMetadata> response = cloudRedisClient.ImportInstance(name, inputConfig);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = cloudRedisClient.PollOnceImportInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
}
}
// [END redis_v1_generated_CloudRedis_ImportInstance_sync_flattened]
}
| 43.084746 | 126 | 0.68096 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Redis.V1/Google.Cloud.Redis.V1.GeneratedSnippets/CloudRedisClient.ImportInstanceSnippet.g.cs | 2,542 | C# |
using Essensoft.AspNetCore.Payment.WeChatPay.V3.Response;
namespace Essensoft.AspNetCore.Payment.WeChatPay.V3.Request
{
/// <summary>
/// 基础支付 - JSAPI支付、APP支付、H5支付、Native支付、小程序支付 - 申请资金账单
/// </summary>
/// <remarks>
/// <para><a href="https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_7.shtml">JSAPI支付 - 申请资金账单API</a> - 最新更新时间:2019.09.16</para>
/// <para><a href="https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_2_7.shtml">APP支付 - 申请资金账单API</a> - 最新更新时间:2019.09.16</para>
/// <para><a href="https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_3_7.shtml">H5支付 - 申请资金账单API</a> - 最新更新时间:2019.09.16</para>
/// <para><a href="https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_4_7.shtml">Native支付 - 申请资金账单API</a> - 最新更新时间:2019.09.16</para>
/// <para><a href="https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_5_7.shtml">小程序支付 - 申请资金账单API</a> - 最新更新时间:2019.09.16</para>
/// </remarks>
public class WeChatPayBillFundflowBillRequest : IWeChatPayGetRequest<WeChatPayBillFundflowBillResponse>
{
private WeChatPayObject queryModel;
public string GetRequestUrl()
{
return "https://api.mch.weixin.qq.com/v3/bill/fundflowbill";
}
public WeChatPayObject GetQueryModel()
{
return queryModel;
}
public void SetQueryModel(WeChatPayObject queryModel)
{
this.queryModel = queryModel;
}
}
}
| 42 | 140 | 0.656463 | [
"MIT"
] | lzw316/payment | src/Essensoft.AspNetCore.Payment.WeChatPay/V3/Request/WeChatPayBillFundflowBillRequest.cs | 1,682 | C# |
// Copyright © 2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.IO;
using System.Net;
namespace CefSharp.SchemeHandler
{
/// <summary>
/// FolderSchemeHandlerFactory is a very simple scheme handler that allows you
/// to map requests for urls to a folder on your file system. For example
/// creating a setting the rootFolder to c:\projects\CefSharp\CefSharp.Example\Resources
/// registering the scheme handler
/// </summary>
public class FolderSchemeHandlerFactory : ISchemeHandlerFactory
{
private readonly string rootFolder;
private readonly string defaultPage;
private readonly string schemeName;
private readonly string hostName;
private readonly FileShare resourceFileShare;
/// <summary>
/// <see cref="ResourceHandler.GetMimeType(string)"/> is being deprecated in favour of using
/// Chromiums native mimeType lookup which is accessible using Cef.GetMimeType, this method is however
/// not directly avaliable as it exists in CefSharp.Core, to get around this we set
/// this static delegate with a reference to Cef.GetMimeType when Cef.Initialize is called.
/// </summary>
public static Func<string, string> GetMimeTypeDelegate = (s) => { return ResourceHandler.GetMimeType(s); };
/// <summary>
/// Initialize a new instance of FolderSchemeHandlerFactory
/// </summary>
/// <param name="rootFolder">Root Folder where all your files exist, requests cannot be made outside of this folder</param>
/// <param name="schemeName">if not null then schemeName checking will be implemented</param>
/// <param name="hostName">if not null then hostName checking will be implemented</param>
/// <param name="defaultPage">default page if no page specified, defaults to index.html</param>
/// <param name="resourceFileShare">file share mode used to open resources, defaults to FileShare.Read</param>
public FolderSchemeHandlerFactory(string rootFolder, string schemeName = null, string hostName = null, string defaultPage = "index.html", FileShare resourceFileShare = FileShare.Read)
{
this.rootFolder = Path.GetFullPath(rootFolder);
this.defaultPage = defaultPage;
this.schemeName = schemeName;
this.hostName = hostName;
this.resourceFileShare = resourceFileShare;
if (!Directory.Exists(this.rootFolder))
{
throw new DirectoryNotFoundException(this.rootFolder);
}
}
/// <summary>
/// If the file requested is within the rootFolder then a IResourceHandler reference to the file requested will be returned
/// otherwise a 404 ResourceHandler will be returned.
/// </summary>
/// <param name="browser">the browser window that originated the
/// request or null if the request did not originate from a browser window
/// (for example, if the request came from CefURLRequest).</param>
/// <param name="frame">frame that originated the request
/// or null if the request did not originate from a browser window
/// (for example, if the request came from CefURLRequest).</param>
/// <param name="schemeName">the scheme name</param>
/// <param name="request">The request. (will not contain cookie data)</param>
/// <returns>
/// A IResourceHandler
/// </returns>
IResourceHandler ISchemeHandlerFactory.Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
if (this.schemeName != null && !schemeName.Equals(this.schemeName, StringComparison.OrdinalIgnoreCase))
{
return ResourceHandler.ForErrorMessage(string.Format("SchemeName {0} does not match the expected SchemeName of {1}.", schemeName, this.schemeName), HttpStatusCode.NotFound);
}
var uri = new Uri(request.Url);
if (this.hostName != null && !uri.Host.Equals(this.hostName, StringComparison.OrdinalIgnoreCase))
{
return ResourceHandler.ForErrorMessage(string.Format("HostName {0} does not match the expected HostName of {1}.", uri.Host, this.hostName), HttpStatusCode.NotFound);
}
//Get the absolute path and remove the leading slash
var asbolutePath = uri.AbsolutePath.Substring(1);
if (string.IsNullOrEmpty(asbolutePath))
{
asbolutePath = defaultPage;
}
var filePath = WebUtility.UrlDecode(Path.GetFullPath(Path.Combine(rootFolder, asbolutePath)));
//Check the file requested is within the specified path and that the file exists
if (filePath.StartsWith(rootFolder, StringComparison.OrdinalIgnoreCase) && File.Exists(filePath))
{
var fileExtension = Path.GetExtension(filePath);
var mimeType = GetMimeTypeDelegate(fileExtension);
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, resourceFileShare);
return ResourceHandler.FromStream(stream, mimeType);
}
return ResourceHandler.ForErrorMessage("File Not Found - " + filePath, HttpStatusCode.NotFound);
}
}
}
| 50.898148 | 191 | 0.662361 | [
"BSD-3-Clause"
] | Bhalddin/CefSharp | CefSharp/SchemeHandler/FolderSchemeHandlerFactory.cs | 5,498 | 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("XrnCourse.NativeServices.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XrnCourse.NativeServices.UWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | 37 | 84 | 0.745573 | [
"MIT"
] | sigged/xrnforms-nativeservices | XrnCourse.NativeServices/XrnCourse.NativeServices.UWP/Properties/AssemblyInfo.cs | 1,076 | 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.Spice.Interfaces
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Baserecordidspicereasonforscreening operations.
/// </summary>
public partial class Baserecordidspicereasonforscreening : IServiceOperations<DynamicsClient>, IBaserecordidspicereasonforscreening
{
/// <summary>
/// Initializes a new instance of the Baserecordidspicereasonforscreening class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Baserecordidspicereasonforscreening(DynamicsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DynamicsClient
/// </summary>
public DynamicsClient Client { get; private set; }
/// <summary>
/// Get baserecordid_spice_reasonforscreening from duplicaterecords
/// </summary>
/// <param name='duplicateid'>
/// key: duplicateid of duplicaterecord
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMspiceReasonforscreening>> GetWithHttpMessagesAsync(string duplicateid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (duplicateid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "duplicateid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("duplicateid", duplicateid);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duplicaterecords({duplicateid})/baserecordid_spice_reasonforscreening").ToString();
_url = _url.Replace("{duplicateid}", System.Uri.EscapeDataString(duplicateid));
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMspiceReasonforscreening>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMspiceReasonforscreening>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 42.211268 | 353 | 0.574018 | [
"Apache-2.0"
] | BrendanBeachBC/jag-spd-spice | interfaces/Dynamics-Autorest/Baserecordidspicereasonforscreening.cs | 8,991 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Cloudflare.Inputs
{
public sealed class LoadBalancerPoolOriginHeaderGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The header name.
/// </summary>
[Input("header", required: true)]
public Input<string> Header { get; set; } = null!;
[Input("values", required: true)]
private InputList<string>? _values;
/// <summary>
/// A list of string values for the header.
/// </summary>
public InputList<string> Values
{
get => _values ?? (_values = new InputList<string>());
set => _values = value;
}
public LoadBalancerPoolOriginHeaderGetArgs()
{
}
}
}
| 27.526316 | 88 | 0.608031 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-cloudflare | sdk/dotnet/Inputs/LoadBalancerPoolOriginHeaderGetArgs.cs | 1,046 | C# |
using System.IO;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.FileProviders;
namespace OpenIdConnectSample
{
public static class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel(options =>
{
// Configure SSL
var serverCertificate = LoadCertificate();
options.UseHttps(serverCertificate);
})
.UseUrls("https://localhost:44318")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
private static X509Certificate2 LoadCertificate()
{
var assembly = typeof(Startup).GetTypeInfo().Assembly;
var embeddedFileProvider = new EmbeddedFileProvider(assembly, "OpenIdConnectSample");
var certificateFileInfo = embeddedFileProvider.GetFileInfo("compiler/resources/cert.pfx");
using (var certificateStream = certificateFileInfo.CreateReadStream())
{
byte[] certificatePayload;
using (var memoryStream = new MemoryStream())
{
certificateStream.CopyTo(memoryStream);
certificatePayload = memoryStream.ToArray();
}
return new X509Certificate2(certificatePayload, "testPassword");
}
}
}
}
| 34.3125 | 102 | 0.574378 | [
"Apache-2.0"
] | bigfont/Security | samples/OpenIdConnectSample/Program.cs | 1,649 | C# |
/*******************************************************
*
* 作者:胡庆访
* 创建时间:2011
* 说明:此文件只包含一个类,具体内容见类型注释。
* 运行环境:.NET 4.0
* 版本号:1.0.0
*
* 历史记录:
* 创建文件 胡庆访 2011 13:30
*
*******************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows;
using System.Reflection;
using System.Windows.Controls;
namespace Rafy.WPF
{
public static class WPFExtension
{
#region Trees
/// <summary>
/// Returns the first visual child from parent based on T
/// </summary>
public static T GetVisualChild<T>(this Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
var visualChild = (Visual)VisualTreeHelper.GetChild(parent, i);
child = visualChild as T;
if (child == null)
{
child = GetVisualChild<T>(visualChild);
}
if (child != null)
{
break;
}
}
return child;
}
/// <summary>
/// 从指定元素往可视树上方查找,找到第一个指定类型的元素时,把该元素返回。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="child"></param>
/// <returns></returns>
public static T GetVisualParent<T>(this DependencyObject child) where T : Visual
{
var parent = VisualTreeHelper.GetParent(child);
if (parent == null) return null;
if (parent is T) return parent as T;
return parent.GetVisualParent<T>();
}
/// <summary>
/// Returns the first logical child from parent based on T.
/// </summary>
public static T GetLogicalChild<T>(this DependencyObject parent) where T : Visual
{
if (parent == null) return null;
T res = default(T);
var children = LogicalTreeHelper.GetChildren(parent);
foreach (var child in children)
{
res = child as T;
if (res != null) return res;
res = GetLogicalChild<T>(child as DependencyObject);
if (res != null) return res;
}
return null;
}
/// <summary>
/// 从指定元素往可视树上方查找,找到第一个指定类型的元素时,把该元素返回。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="child"></param>
/// <returns></returns>
public static T GetLogicalParent<T>(this DependencyObject child) where T : Visual
{
var parent = LogicalTreeHelper.GetParent(child);
if (parent == null) return null;
if (parent is T) return parent as T;
return parent.GetLogicalParent<T>();
}
/// <summary>
/// 获取某个指定元素的逻辑树根对象。
/// </summary>
/// <param name="child"></param>
/// <returns></returns>
public static DependencyObject GetLogicalRoot(this DependencyObject child)
{
while (true)
{
var parent = LogicalTreeHelper.GetParent(child);
if (parent == null) { return child; }
child = parent;
}
}
/// <summary>
/// 获取某个指定元素的可视树根对象。
/// </summary>
/// <param name="child"></param>
/// <returns></returns>
public static DependencyObject GetVisualRoot(this DependencyObject child)
{
while (true)
{
var parent = VisualTreeHelper.GetParent(child);
if (parent == null) { return child; }
child = parent;
}
}
/// <summary>
/// 把某一个元素从逻辑树中移除,使用另一个新的元素在原来的位置中替换它。
/// </summary>
/// <param name="oldElement"></param>
/// <param name="newElement"></param>
public static void ReplaceInParent(this FrameworkElement oldElement, FrameworkElement newElement)
{
oldElement.RemoveFromParent(false);
SetLastParent(newElement, GetLastParent(oldElement));
SetLastIndexInParent(newElement, GetLastIndexInParent(oldElement));
newElement.AttachToLastParent();
}
/// <summary>
/// 把某个元素从逻辑树中移除
/// </summary>
/// <param name="element"></param>
public static void RemoveFromParent(this FrameworkElement element, bool recur = true)
{
if (element == null) throw new ArgumentNullException("element");
if (element.Parent == null) return;
SetLastParent(element, element.Parent as FrameworkElement);
var panel = element.Parent as Panel;
if (panel != null)
{
SetLastIndexInParent(element, panel.Children.IndexOf(element));
panel.Children.Remove(element);
if (recur)
{
if (panel.Children.Count == 0)
{
panel.RemoveFromParent(true);
}
}
return;
}
var itemsControl = element.Parent as ItemsControl;
if (itemsControl != null)
{
SetLastIndexInParent(element, itemsControl.Items.IndexOf(element));
itemsControl.Items.Remove(element);
if (recur)
{
if (itemsControl.Items.Count == 0)
{
itemsControl.RemoveFromParent(true);
}
}
return;
}
var contentControl = element.Parent as ContentControl;
if (contentControl != null)
{
contentControl.Content = null;
if (recur)
{
contentControl.RemoveFromParent(recur);
}
return;
}
throw new NotSupportedException();
}
public static void AttachToLastParent(this FrameworkElement element)
{
if (element == null) throw new ArgumentNullException("element");
if (element.Parent != null) return;
var parent = GetLastParent(element);
if (parent == null) return;
AttachToParent(element, parent);
parent.AttachToLastParent();
}
public static void AttachToParent(this FrameworkElement element, DependencyObject parent)
{
var panel = parent as Panel;
if (panel != null)
{
int index = GetLastIndexInParent(element);
if (index < panel.Children.Count)
{
panel.Children.Insert(index, element);
}
else
{
panel.Children.Add(element);
}
return;
}
var itemsControl = parent as ItemsControl;
if (itemsControl != null)
{
int index = GetLastIndexInParent(element);
if (index < panel.Children.Count)
{
itemsControl.Items.Insert(index, element);
}
else
{
itemsControl.Items.Add(element);
}
return;
}
var contentControl = parent as ContentControl;
if (contentControl != null)
{
contentControl.Content = element;
return;
}
throw new NotSupportedException();
}
#endregion
#region GetDependencyProperty
/// <summary>
/// Retrieves a <see cref="DependencyProperty"/> using reflection.
/// </summary>
/// <param name="obj"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public static DependencyProperty GetDependencyProperty(this DependencyObject obj, string propertyName)
{
DependencyProperty prop = null;
if (obj != null)
{
prop = GetDependencyProperty(obj.GetType(), propertyName);
}
return prop;
}
/// <summary>
/// Gets the dependency property according to its name.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="propertyName">Name of the property.</param>
/// <returns></returns>
private static DependencyProperty GetDependencyProperty(Type type, string propertyName)
{
DependencyProperty prop = null;
if (type != null)
{
FieldInfo fieldInfo = type.GetField(propertyName + "Property",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
if (fieldInfo != null)
{
prop = fieldInfo.GetValue(null) as DependencyProperty;
}
}
return prop;
}
#endregion
/// <summary>
/// Sets the value of the <paramref name="property"/> only if it hasn't been explicitely set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">The object.</param>
/// <param name="property">The property.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public static bool SetIfNonLocal<T>(this DependencyObject obj, DependencyProperty property, T value)
{
if (obj == null) throw new ArgumentNullException("obj");
if (property == null) throw new ArgumentNullException("property");
if (DependencyPropertyHelper.GetValueSource(obj, property).BaseValueSource != BaseValueSource.Local)
{
obj.SetValue(property, value);
return true;
}
return false;
}
/// <summary>
/// 判断某个属性当前的值是否为本地值。
/// </summary>
/// <param name="obj"></param>
/// <param name="property"></param>
/// <returns></returns>
public static bool IsLocalValue(this DependencyObject obj, DependencyProperty property)
{
return DependencyPropertyHelper.GetValueSource(obj, property).BaseValueSource == BaseValueSource.Local;
}
internal static FrameworkElement LoadContent(this FrameworkElementFactory visualTree)
{
var template = new ControlTemplate()
{
VisualTree = visualTree
};
template.Seal();
return template.LoadContent() as FrameworkElement;
}
#region ListenLayoutUpdatedOnce
/// <summary>
/// 只监听目标对象的一次 LayoutUpdated 事件。
/// </summary>
/// <param name="element"></param>
/// <param name="handler"></param>
public static void ListenLayoutUpdatedOnce(this UIElement element, EventHandler handler)
{
new ListenLayoutUpdatedOnceHelper
{
element = element,
handler = handler
}.Listen();
}
private class ListenLayoutUpdatedOnceHelper
{
public UIElement element;
public EventHandler handler;
public void Listen()
{
element.LayoutUpdated += element_LayoutUpdated;
}
void element_LayoutUpdated(object sender, EventArgs e)
{
element.LayoutUpdated -= element_LayoutUpdated;
handler(sender, e);
}
}
#endregion
#region LastParent
public static readonly DependencyProperty LastParentProperty =
DependencyProperty.RegisterAttached("LastParent", typeof(FrameworkElement), typeof(WPFExtension));
public static void SetLastParent(FrameworkElement d, FrameworkElement value)
{
d.SetValue(LastParentProperty, value);
}
public static FrameworkElement GetLastParent(FrameworkElement d)
{
return d.GetValue(LastParentProperty) as FrameworkElement;
}
#endregion
#region LastIndexInParent
public static readonly DependencyProperty LastIndexInParentProperty =
DependencyProperty.RegisterAttached("LastIndexInParent", typeof(int), typeof(WPFExtension));
public static void SetLastIndexInParent(FrameworkElement d, int value)
{
d.SetValue(LastIndexInParentProperty, value);
}
public static int GetLastIndexInParent(FrameworkElement d)
{
return (int)d.GetValue(LastIndexInParentProperty);
}
#endregion
}
}
| 32.007075 | 116 | 0.505121 | [
"MIT"
] | zgynhqf/trunk | Rafy/WPF/Rafy.WPF.Controls/WPFExtension.cs | 14,039 | 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 organizations-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Organizations.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Organizations.Model.Internal.MarshallTransformations
{
/// <summary>
/// DescribeAccount Request Marshaller
/// </summary>
public class DescribeAccountRequestMarshaller : IMarshaller<IRequest, DescribeAccountRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DescribeAccountRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DescribeAccountRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Organizations");
string target = "AWSOrganizationsV20161128.DescribeAccount";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28";
request.HttpMethod = "POST";
request.ResourcePath = "/";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetAccountId())
{
context.Writer.WritePropertyName("AccountId");
context.Writer.Write(publicRequest.AccountId);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static DescribeAccountRequestMarshaller _instance = new DescribeAccountRequestMarshaller();
internal static DescribeAccountRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeAccountRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.407767 | 145 | 0.636413 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/Organizations/Generated/Model/Internal/MarshallTransformations/DescribeAccountRequestMarshaller.cs | 3,647 | 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("BackIn30Minutes")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("BackIn30Minutes")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
[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("6229c12f-8610-406c-be97-32a0e62f6c70")]
// 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.405405 | 84 | 0.749472 | [
"MIT"
] | AlexanderPetrovv/Tech-Module-SoftUni | Programming Fundamentals - May 2017/CondStatementsAndLoops/BackIn30Minutes/Properties/AssemblyInfo.cs | 1,424 | C# |
using System;
using BuckarooSdk.DataTypes.ParameterGroups.CreditManagement3;
namespace BuckarooSdk.Services.CreditManagement.TransactionRequest
{
public class CreditManagementInvoiceRequest
{
/// <summary>
/// The VAT amount of the invoice
/// </summary>
public decimal InvoiceAmountVat { get; set; }
/// <summary>
/// required = true.
/// The date corresponding to the invoice
/// </summary>
public DateTime InvoiceDate { get; set; }
/// <summary>
/// The maximum step index that is to be used in the credit management scheme.
/// </summary>
public int? MaxStepIndex { get; set; }
/// <summary>
/// The date that the invoice is due for payment. If not paid, the invoice will be put to the next
/// step in the creditmanagement scheme.
/// </summary>
public DateTime DueDate { get; set; }
/// <summary>
/// The key of the scheme that is to be used for this invoice.
/// </summary>
public string SchemeKey { get; set; }
/// <summary>
/// The amount of the invoice that has to be created
/// </summary>
public decimal InvoiceAmount { get; set; }
/// <summary>
/// The services that are not allowed to be used when paying this invoice.
/// </summary>
public string DisallowedServices { get; set; }
/// <summary>
/// The services that are allowed to be used when paying this invoice
/// </summary>
public string AllowedServices { get; set; }
/// <summary>
/// Parameter group Debtor
/// </summary>
public Debtor Debtor { get; set; }
/// <summary>
/// Parameter group Person
/// </summary>
public Person Person { get; set; }
/// <summary>
/// Parameter group Address
/// </summary>
public Address Address { get; set; }
/// <summary>
/// Parameter group Email
/// </summary>
public EmailAddress Email { get; set; }
/// <summary>
/// Parameter group Phone
/// </summary>
public Phone Phone { get; set; }
}
}
| 29.96875 | 100 | 0.652763 | [
"MIT"
] | FrostAndFlame/BuckarooSdk_DotNet | BuckarooSdk/Services/CreditManagement/TransactionRequest/CreditManagementInvoiceRequest.cs | 1,920 | C# |
namespace Mutators.Tests.FunctionalTests.SecondOuterContract
{
public class Street
{
public string[] StreetAndNumberOrPostBoxIdentifier { get; set; }
}
} | 24.714286 | 72 | 0.722543 | [
"MIT"
] | RGleb/GrobExp.Mutators | Mutators.Tests/FunctionalTests/SecondOuterContract/Street.cs | 173 | 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 HanoiWpfApp.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.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;
}
}
}
}
| 39.481481 | 151 | 0.581614 | [
"MIT"
] | pvoosten/WpfExampleHanoi | HanoiWpfApp/Properties/Settings.Designer.cs | 1,068 | C# |
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Style", "IDE2003:C#", Justification = "<Pending>", Scope = "member", Target = "~M:AddUp.CommonLogging.Factory.AbstractLogger.FormatMessageCallbackFormattedMessage.ToString~System.String")]
[assembly: SuppressMessage("Style", "IDE0045:Convert to conditional expression", Justification = "<Pending>", Scope = "member", Target = "~M:AddUp.CommonLogging.Factory.AbstractLogger.FormatMessageCallbackFormattedMessage.FormatMessage(System.String,System.Object[])~System.String")]
[assembly: SuppressMessage("Style", "IDE0045:Convert to conditional expression", Justification = "<Pending>", Scope = "member", Target = "~M:AddUp.CommonLogging.ConfigurationSectionHandler.ReadConfiguration(System.Xml.XmlNode)~AddUp.CommonLogging.Configuration.LogSetting")]
[assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "<Pending>", Scope = "member", Target = "~M:AddUp.CommonLogging.Simple.NoOpLoggerFactoryAdapter.#ctor(AddUp.CommonLogging.Configuration.NameValueCollection)")]
[assembly: SuppressMessage("Minor Code Smell", "S3963:\"static\" fields should be initialized inline", Justification = "<Pending>", Scope = "member", Target = "~M:AddUp.CommonLogging.Configuration.ArgUtils.#cctor")]
[assembly: SuppressMessage("Critical Code Smell", "S2346:Flags enumerations zero-value members should be named \"None\"", Justification = "<Pending>", Scope = "type", Target = "~T:AddUp.CommonLogging.LogLevel")]
[assembly: SuppressMessage("Major Code Smell", "S3925:\"ISerializable\" should be implemented correctly", Justification = "<Pending>", Scope = "type", Target = "~T:AddUp.CommonLogging.Configuration.NameValueCollection")]
| 130.666667 | 283 | 0.779592 | [
"Apache-2.0"
] | addupsolutions/AddUp.CommonLogging | src/AddUp.CommonLogging/GlobalSuppressions.cs | 1,962 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.ElasticCloud.Inputs
{
public sealed class GetDeploymentsIntegrationsServerArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Overall health status of the deployment.
/// </summary>
[Input("healthy")]
public string? Healthy { get; set; }
[Input("status")]
public string? Status { get; set; }
[Input("version")]
public string? Version { get; set; }
public GetDeploymentsIntegrationsServerArgs()
{
}
}
}
| 26.21875 | 88 | 0.64124 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-ec | sdk/dotnet/Inputs/GetDeploymentsIntegrationsServer.cs | 839 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.Documents.Client;
using System.Linq;
using Tasks.FunctionApp.Exceptions;
namespace Tasks.FunctionApp.Functions.Note;
public class Remove : Base
{
[FunctionName("RemoveNote")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "notes/{id}")]
HttpRequest req,
[CosmosDB(ConnectionStringSetting = "CosmosDBConnection")]
DocumentClient client,
ILogger log,
string id)
{
log.LogInformation("Deleting a note from list item.");
try
{
Uri collectionUri = UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName);
var document = client.CreateDocumentQuery(collectionUri).Where(t => t.Id == id)
.AsEnumerable().FirstOrDefault();
if (document == null)
{
return new NotFoundResult();
}
await client.DeleteDocumentAsync(document.SelfLink);
log.LogInformation($"Note deleted successfully with ID {id}.");
return new OkResult();
}
catch (NoteException exception)
{
log?.LogInformation(exception.ToString());
}
return new BadRequestResult();
}
}
| 30.56 | 101 | 0.645942 | [
"MIT"
] | FernandoCalmet/DOTNET-6-Azure-FunctionApp-CosmosDB-CRUD | Tasks.FunctionApp/Functions/Note/Remove.cs | 1,528 | C# |
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using Process.NET.Applied;
using Process.NET.Native;
using Process.NET.Native.Types;
namespace Process.NET.Windows
{
public delegate IntPtr WindowProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
public abstract class WindowProcHook : IApplied
{
// ReSharper disable once InconsistentNaming
private const int GWL_WNDPROC = -4;
private WindowProc _newCallback;
private IntPtr _oldCallback;
protected WindowProcHook(IntPtr handle, string identifier = "")
{
if (string.IsNullOrEmpty(identifier))
{
identifier = "WindowProcHook - " + handle.ToString("X");
}
Identifier = identifier;
Handle = handle;
}
protected WindowProcHook(string procName, int index = 0)
{
var processesByName = System.Diagnostics.Process.GetProcessesByName(procName).ToList();
if (processesByName == null)
{
throw new NullReferenceException($"Could not find a process by the name of {procName}");
}
var process = index == 0 ? processesByName.First() : processesByName[index];
Identifier = $"WndProc hook - {process.MainWindowTitle}";
Handle = process.MainWindowHandle;
}
protected IntPtr Handle { get; set; }
public void Enable()
{
_newCallback = OnWndProc;
_oldCallback = Kernel32.SetWindowLongPtr(Handle, GWL_WNDPROC,
Marshal.GetFunctionPointerForDelegate(_newCallback));
if (_oldCallback == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
IsEnabled = true;
}
public string Identifier { get; }
public bool IsDisposed { get; protected set; }
public bool IsEnabled { get; protected set; }
public bool MustBeDisposed { get; set; } = true;
public void Disable()
{
if (_newCallback == null)
{
return;
}
Kernel32.SetWindowLongPtr(Handle, GWL_WNDPROC, _oldCallback);
_newCallback = null;
IsEnabled = false;
}
public void Dispose()
{
if (IsDisposed)
{
return;
}
IsDisposed = true;
if (IsEnabled)
{
Disable();
}
GC.SuppressFinalize(this);
}
protected virtual IntPtr OnWndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
{
return Kernel32.CallWindowProc(_oldCallback, hWnd, msg, wParam, lParam);
}
~WindowProcHook()
{
if (MustBeDisposed)
{
Dispose();
}
}
public override string ToString()
{
return Identifier;
}
}
} | 26.008403 | 104 | 0.549273 | [
"MIT"
] | TimothyByrd/ChaosHelper | Process.NET/Windows/WndProcHook.cs | 3,097 | 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;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class QueryTests : CompilingTestBase
{
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void DegenerateQueryExpression()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from i in c select i;
if (ReferenceEquals(c, r)) throw new Exception();
// List1<int> r = c.Select(i => i);
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4, 5, 6, 7]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void FromClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c select i')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: '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)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void QueryContinuation()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from i in c select i into q select q;
if (ReferenceEquals(c, r)) throw new Exception();
// List1<int> r = c.Select(i => i);
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4, 5, 6, 7]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void QueryContinuation_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c select i into q select q/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c ... q select q')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select q')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'select i')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: '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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'q')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'q')
ReturnedValue:
IParameterReferenceOperation: q (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'q')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void Select()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from i in c select i+1;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[2, 3, 4, 5, 6, 7, 8]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void SelectClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c select i+1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c select i+1')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i+1')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i+1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i+1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i+1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i+1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i+1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i+1')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void GroupBy01()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
var r = from i in c group i by i % 2;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[1, 3, 5, 7], 0:[2, 4, 6]]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void GroupByClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c group i by i % 2/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Linq.IGrouping<System.Int32, System.Int32>>) (Syntax: 'from i in c ... i by i % 2')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<System.Int32, System.Int32>> System.Linq.Enumerable.GroupBy<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> keySelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Linq.IGrouping<System.Int32, System.Int32>>, IsImplicit) (Syntax: 'group i by i % 2')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i % 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i % 2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i % 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i % 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i % 2')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Remainder) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i % 2')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void GroupBy02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
var r = from i in c group 10+i by i % 2;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[11, 13, 15, 17], 0:[12, 14, 16]]");
}
[Fact]
public void Cast()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<object> c = new List1<object>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from int i in c select i;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4, 5, 6, 7]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void CastInFromClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<object> c = new List<object>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from int i in c select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int i in c select i')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int i in c')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int i in c')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Object>) (Syntax: '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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: '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)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void Where()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<object> c = new List1<object>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from int i in c where i < 5 select i;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void WhereClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<object> c = new List<object>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from int i in c where i < 5 select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int i ... 5 select i')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Where<System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Boolean> predicate)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'where i < 5')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int i in c')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int i in c')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Object>) (Syntax: '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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i < 5')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Boolean>, IsImplicit) (Syntax: 'i < 5')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i < 5')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i < 5')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i < 5')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void FromJoinSelect()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(10, 30, 40, 50, 60, 70);
List1<int> r = from x1 in c1
join x2 in c2 on x1 equals x2/10
select x1+x2;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 33, 44, 55, 77]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void FromJoinSelect_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>() {1, 2, 3, 4, 5, 6, 7};
List<int> c2 = new List<int>() {10, 30, 40, 50, 60, 70};
var r = /*<bind>*/from x1 in c1
join x2 in c2 on x1 equals x2/10
select x1+x2/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from x1 in ... elect x1+x2')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Join<System.Int32, System.Int32, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> outer, System.Collections.Generic.IEnumerable<System.Int32> inner, System.Func<System.Int32, System.Int32> outerKeySelector, System.Func<System.Int32, System.Int32> innerKeySelector, System.Func<System.Int32, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'join x2 in ... quals x2/10')
Instance Receiver:
null
Arguments(5):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outer) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x1 in c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x1 in c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1')
ReturnedValue:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x2/10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x2/10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x2/10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x2/10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x2/10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x2/10')
Left:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1+x2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, System.Int32>, IsImplicit) (Syntax: 'x1+x2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1+x2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1+x2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1+x2')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x1+x2')
Left:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
Right:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void OrderBy()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(28, 51, 27, 84, 27, 27, 72, 64, 55, 46, 39);
var r =
from i in c
orderby i/10 descending, i%10
select i;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[84, 72, 64, 51, 55, 46, 39, 27, 27, 27, 28]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void OrderByClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c
orderby i/10 descending, i%10
select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Linq.IOrderedEnumerable<System.Int32>) (Syntax: 'from i in c ... select i')
Expression:
IInvocationOperation (System.Linq.IOrderedEnumerable<System.Int32> System.Linq.Enumerable.ThenBy<System.Int32, System.Int32>(this System.Linq.IOrderedEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> keySelector)) (OperationKind.Invocation, Type: System.Linq.IOrderedEnumerable<System.Int32>, IsImplicit) (Syntax: 'i%10')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i/10 descending')
IInvocationOperation (System.Linq.IOrderedEnumerable<System.Int32> System.Linq.Enumerable.OrderByDescending<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> keySelector)) (OperationKind.Invocation, Type: System.Linq.IOrderedEnumerable<System.Int32>, IsImplicit) (Syntax: 'i/10 descending')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i/10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i/10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i/10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i/10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i/10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i/10')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i%10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i%10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i%10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i%10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i%10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Remainder) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i%10')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '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)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void GroupJoin()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(12, 34, 42, 51, 52, 66, 75);
List1<string> r =
from x1 in c1
join x2 in c2 on x1 equals x2 / 10 into g
select x1 + "":"" + g.ToString();
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[12], 2:[], 3:[34], 4:[42], 5:[51, 52], 7:[75]]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void GroupJoinClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{12, 34, 42, 51, 52, 66, 75};
var r =
/*<bind>*/from x1 in c1
join x2 in c2 on x1 equals x2 / 10 into g
select x1 + "":"" + g.ToString()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from x1 in ... .ToString()')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.GroupJoin<System.Int32, System.Int32, System.Int32, System.String>(this System.Collections.Generic.IEnumerable<System.Int32> outer, System.Collections.Generic.IEnumerable<System.Int32> inner, System.Func<System.Int32, System.Int32> outerKeySelector, System.Func<System.Int32, System.Int32> innerKeySelector, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>, System.String> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'join x2 in ... / 10 into g')
Instance Receiver:
null
Arguments(5):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outer) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x1 in c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x1 in c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1')
ReturnedValue:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x2 / 10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x2 / 10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x2 / 10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x2 / 10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x2 / 10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x2 / 10')
Left:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>, System.String>, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'x1 + "":"" + g.ToString()')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'x1 + "":""')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'x1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "":"") (Syntax: '"":""')
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'g.ToString()')
Instance Receiver:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'g')
Arguments(0)
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void SelectMany01()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> c2 = new List1<int>(10, 20, 30);
List1<int> r = from x in c1 from y in c2 select x + y;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 21, 31, 12, 22, 32, 13, 23, 33]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void SelectMany_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{12, 34, 42, 51, 52, 66, 75};
var r = /*<bind>*/from x in c1 from y in c2 select x + y/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from x in c ... elect x + y')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.SelectMany<System.Int32, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<System.Int32, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from y in c2')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x in c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c2')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, System.Int32>, IsImplicit) (Syntax: 'x + y')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void SelectMany02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> c2 = new List1<int>(10, 20, 30);
List1<int> r = from x in c1 from int y in c2 select x + y;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 21, 31, 12, 22, 32, 13, 23, 33]");
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void Let01()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> r1 =
from int x in c1
let g = x * 10
let z = g + x*100
select x + z;
System.Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[111, 222, 333]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void LetClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
var r = /*<bind>*/from int x in c1
let g = x * 10
let z = g + x*100
select x + z/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int x ... elect x + z')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>> source, System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select x + z')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let z = g + x*100')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>> System.Linq.Enumerable.Select<<anonymous type: System.Int32 x, System.Int32 g>, <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 g>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 g>, <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'let z = g + x*100')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let g = x * 10')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 g>> System.Linq.Enumerable.Select<System.Int32, <anonymous type: System.Int32 x, System.Int32 g>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, <anonymous type: System.Int32 x, System.Int32 g>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 g>>, IsImplicit) (Syntax: 'let g = x * 10')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int x in c1')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int x in c1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x * 10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, <anonymous type: System.Int32 x, System.Int32 g>>, IsImplicit) (Syntax: 'x * 10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x * 10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x * 10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x * 10')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * 10')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * ... elect x + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * 10')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * 10')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * 10')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * 10')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x * 10')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * 10')
Right:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x * 10')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'g + x*100')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 g>, <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'g + x*100')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'g + x*100')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'g + x*100')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'g + x*100')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let z = g + x*100')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * ... elect x + z')
Left:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 g> <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let z = g + x*100')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let z = g + x*100')
Right:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let z = g + x*100')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let z = g + x*100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'g + x*100')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let z = g + x*100')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'g + x*100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'g')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'g')
Right:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x*100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, System.Int32>, IsImplicit) (Syntax: 'x + z')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + z')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 g> <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'z')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TransparentIdentifiers_FromLet()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C c3 = new C(100, 200, 300);
C r1 =
from int x in c1
from int y in c2
from int z in c3
let g = x + y + z
where (x + y / 10 + z / 100) < 6
select g;
Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[111, 211, 311, 121, 221, 131, 112, 212, 122, 113]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void TransparentIdentifiers_FromLet_IOperation()
{
string source = @"
using C = System.Collections.Generic.List<int>;
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
C c1 = new C{1, 2, 3};
C c2 = new C{10, 20, 30};
C c3 = new C{100, 200, 300};
var r1 =
/*<bind>*/from int x in c1
from int y in c2
from int z in c3
let g = x + y + z
where (x + y / 10 + z / 100) < 6
select g/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int x ... select g')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> source, System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select g')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'where (x + ... / 100) < 6')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> source, System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Boolean> predicate)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>, IsImplicit) (Syntax: 'where (x + ... / 100) < 6')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let g = x + y + z')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>> source, System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>, IsImplicit) (Syntax: 'let g = x + y + z')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>> System.Linq.Enumerable.SelectMany<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> System.Linq.Enumerable.SelectMany<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int x in c1')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int x in c1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c2')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from int y in c2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c3')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c3')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c3')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c3')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c3 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c3')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'from int z in c3')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from int z in c3')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int z in c3')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int z in c3')
Right:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int z in c3')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int z in c3')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int z in c3')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>, IsImplicit) (Syntax: 'x + y + z')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y + z')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'let g = x + y + z')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let g = x + y + z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'let g = x + y + z')
Right:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let g = x + y + z')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let g = x + y + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x + y + z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'let g = x + y + z')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y + z')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'y')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'z')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Boolean>, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: '(x + y / 10 ... / 100) < 6')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y / 10 + z / 100')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y / 10')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'x')
Right:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'y / 10')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'z / 100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'z')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'g')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Int32>, IsImplicit) (Syntax: 'g')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'g')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'g')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'g')
ReturnedValue:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'g')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: '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)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TransparentIdentifiers_Join01()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C r1 =
from int x in c1
join y in c2 on x equals y/10
let z = x+y
select z;
Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 22, 33]");
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TransparentIdentifiers_Join02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(12, 34, 42, 51, 52, 66, 75);
List1<string> r1 = from x1 in c1
join x2 in c2 on x1 equals x2 / 10 into g
where x1 < 7
select x1 + "":"" + g.ToString();
Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[12], 2:[], 3:[34], 4:[42], 5:[51, 52]]");
}
[Fact]
public void CodegenBug()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(12, 34, 42, 51, 52, 66, 75);
List1<Tuple<int, List1<int>>> r1 =
c1
.GroupJoin(c2, x1 => x1, x2 => x2 / 10, (x1, g) => new Tuple<int, List1<int>>(x1, g))
;
Func1<Tuple<int, List1<int>>, bool> condition = (Tuple<int, List1<int>> TR1) => TR1.Item1 < 7;
List1<Tuple<int, List1<int>>> r2 =
r1
.Where(condition)
;
Func1<Tuple<int, List1<int>>, string> map = (Tuple<int, List1<int>> TR1) => TR1.Item1.ToString() + "":"" + TR1.Item2.ToString();
List1<string> r3 =
r2
.Select(map)
;
string r4 = r3.ToString();
Console.WriteLine(r4);
return;
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[12], 2:[], 3:[34], 4:[42], 5:[51, 52]]");
}
[Fact]
public void RangeVariables01()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C c3 = new C(100, 200, 300);
C r1 =
from int x in c1
from int y in c2
from int z in c3
select x + y + z;
Console.WriteLine(r1);
}
}";
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[3].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.NotEqual(MethodKind.ReducedExtension, ((IMethodSymbol)info0.CastInfo.Symbol).MethodKind);
Assert.Null(info0.OperationInfo.Symbol);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
var y = model.GetDeclaredSymbol(q.Body.Clauses[0]);
Assert.Equal(SymbolKind.RangeVariable, y.Kind);
Assert.Equal("y", y.Name);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.NotEqual(MethodKind.ReducedExtension, ((IMethodSymbol)info1.OperationInfo.Symbol).MethodKind);
var info2 = model.GetQueryClauseInfo(q.Body.Clauses[1]);
var z = model.GetDeclaredSymbol(q.Body.Clauses[1]);
Assert.Equal(SymbolKind.RangeVariable, z.Kind);
Assert.Equal("z", z.Name);
Assert.Equal("Cast", info2.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info2.OperationInfo.Symbol.Name);
var info3 = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.NotNull(info3);
// what about info3's contents ???
var xPyPz = (q.Body.SelectOrGroup as SelectClauseSyntax).Expression as BinaryExpressionSyntax;
var xPy = xPyPz.Left as BinaryExpressionSyntax;
Assert.Equal(x, model.GetSemanticInfoSummary(xPy.Left).Symbol);
Assert.Equal(y, model.GetSemanticInfoSummary(xPy.Right).Symbol);
Assert.Equal(z, model.GetSemanticInfoSummary(xPyPz.Right).Symbol);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void RangeVariables_IOperation()
{
string source = @"
using C = System.Collections.Generic.List<int>;
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
C c1 = new C{1, 2, 3};
C c2 = new C{10, 20, 30};
C c3 = new C{100, 200, 300};
var r1 =
/*<bind>*/from int x in c1
from int y in c2
from int z in c3
select x + y + z/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int x ... t x + y + z')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.SelectMany<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> System.Linq.Enumerable.SelectMany<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int x in c1')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int x in c1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c2')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from int y in c2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... t x + y + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... t x + y + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c3')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c3')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c3')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c3')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c3 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c3')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, System.Int32>, IsImplicit) (Syntax: 'x + y + z')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y + z')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y + z')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'y')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void RangeVariables02()
{
var csSource = @"
using System;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
var c1 = new int[] {1, 2, 3};
var c2 = new int[] {10, 20, 30};
var c3 = new int[] {100, 200, 300};
var r1 =
from int x in c1
from int y in c2
from int z in c3
select x + y + z;
Console.WriteLine(r1);
}
}";
var compilation = CreateCompilation(csSource);
foreach (var dd in compilation.GetDiagnostics()) Console.WriteLine(dd);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[3].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.Equal(MethodKind.ReducedExtension, ((IMethodSymbol)info0.CastInfo.Symbol).MethodKind);
Assert.Null(info0.OperationInfo.Symbol);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
var y = model.GetDeclaredSymbol(q.Body.Clauses[0]);
Assert.Equal(SymbolKind.RangeVariable, y.Kind);
Assert.Equal("y", y.Name);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.Equal(MethodKind.ReducedExtension, ((IMethodSymbol)info1.OperationInfo.Symbol).MethodKind);
var info2 = model.GetQueryClauseInfo(q.Body.Clauses[1]);
var z = model.GetDeclaredSymbol(q.Body.Clauses[1]);
Assert.Equal(SymbolKind.RangeVariable, z.Kind);
Assert.Equal("z", z.Name);
Assert.Equal("Cast", info2.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info2.OperationInfo.Symbol.Name);
var info3 = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.NotNull(info3);
// what about info3's contents ???
var xPyPz = (q.Body.SelectOrGroup as SelectClauseSyntax).Expression as BinaryExpressionSyntax;
var xPy = xPyPz.Left as BinaryExpressionSyntax;
Assert.Equal(x, model.GetSemanticInfoSummary(xPy.Left).Symbol);
Assert.Equal(y, model.GetSemanticInfoSummary(xPy.Right).Symbol);
Assert.Equal(z, model.GetSemanticInfoSummary(xPyPz.Right).Symbol);
}
[Fact]
public void TestGetSemanticInfo01()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C r1 =
from int x in c1
from int y in c2
select x + y;
Console.WriteLine(r1);
}
}";
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[2].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.Null(info0.OperationInfo.Symbol);
Assert.Equal("x", model.GetDeclaredSymbol(q.FromClause).Name);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.Equal("y", model.GetDeclaredSymbol(q.Body.Clauses[0]).Name);
var info2 = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
// what about info2's contents?
}
[Fact]
public void TestGetSemanticInfo02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(28, 51, 27, 84, 27, 27, 72, 64, 55, 46, 39);
var r =
from i in c
orderby i/10 descending, i%10
select i;
Console.WriteLine(r);
}
}";
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[1].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
Assert.Null(info0.CastInfo.Symbol);
Assert.Null(info0.OperationInfo.Symbol);
Assert.Equal("i", model.GetDeclaredSymbol(q.FromClause).Name);
var i = model.GetDeclaredSymbol(q.FromClause);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
Assert.Null(info1.CastInfo.Symbol);
Assert.Null(info1.OperationInfo.Symbol);
Assert.Null(model.GetDeclaredSymbol(q.Body.Clauses[0]));
var order = q.Body.Clauses[0] as OrderByClauseSyntax;
var oinfo0 = model.GetSemanticInfoSummary(order.Orderings[0]);
Assert.Equal("OrderByDescending", oinfo0.Symbol.Name);
var oinfo1 = model.GetSemanticInfoSummary(order.Orderings[1]);
Assert.Equal("ThenBy", oinfo1.Symbol.Name);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(541774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541774")]
[Fact]
public void MultipleFromClauseIdentifierInExprNotInContext()
{
string source = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q2 = /*<bind>*/from n1 in nums
from n2 in nums
select n1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from n1 in ... select n1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from n2 in nums')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'nums')
Children(0)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'nums')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'nums')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'nums')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'nums')
Children(0)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'n1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'n1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'n1')
ReturnedValue:
IParameterReferenceOperation: n1 (OperationKind.ParameterReference, Type: ?) (Syntax: 'n1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'nums' does not exist in the current context
// var q2 = /*<bind>*/from n1 in nums
Diagnostic(ErrorCode.ERR_NameNotInContext, "nums").WithArguments("nums").WithLocation(8, 39),
// CS0103: The name 'nums' does not exist in the current context
// from n2 in nums
Diagnostic(ErrorCode.ERR_NameNotInContext, "nums").WithArguments("nums").WithLocation(9, 29)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(541906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541906")]
[Fact]
public void NullLiteralFollowingJoinInQuery()
{
string source = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from int i ... ue select i')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'join null o ... equals true')
Children(5):
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int i ... int[] { 1 }')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'new int[] { 1 }')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'new int[] { 1 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[] { 1 }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new int[] { 1 }')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1 }')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'join null o ... equals true')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'true')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'true')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'true')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'true')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'true')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'true')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: ?) (Syntax: 'i')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1031: Type expected
// var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
Diagnostic(ErrorCode.ERR_TypeExpected, "null").WithLocation(8, 66),
// CS1001: Identifier expected
// var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
Diagnostic(ErrorCode.ERR_IdentifierExpected, "null").WithLocation(8, 66),
// CS1003: Syntax error, 'in' expected
// var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
Diagnostic(ErrorCode.ERR_SyntaxError, "null").WithArguments("in", "null").WithLocation(8, 66)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(541779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541779")]
[Fact]
public void MultipleFromClauseQueryExpr()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var nums = new int[] { 3, 4 };
var q2 = from int n1 in nums
from int n2 in nums
select n1;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "3 3 4 4");
}
[WorkItem(541782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541782")]
[Fact]
public void FromSelectQueryExprOnArraysWithTypeImplicit()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var nums = new int[] { 3, 4 };
var q2 = from n1 in nums select n1;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "3 4");
}
[WorkItem(541788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541788")]
[Fact]
public void JoinClauseTest()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var q2 =
from a in Enumerable.Range(1, 13)
join b in Enumerable.Range(1, 13) on 4 * a equals b
select a;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "1 2 3");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void JoinClause_IOperation()
{
string source = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var q2 =
/*<bind>*/from a in Enumerable.Range(1, 13)
join b in Enumerable.Range(1, 13) on 4 * a equals b
select a/*</bind>*/;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from a in E ... select a')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Join<System.Int32, System.Int32, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> outer, System.Collections.Generic.IEnumerable<System.Int32> inner, System.Func<System.Int32, System.Int32> outerKeySelector, System.Func<System.Int32, System.Int32> innerKeySelector, System.Func<System.Int32, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'join b in E ... a equals b')
Instance Receiver:
null
Arguments(5):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outer) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Enumerable.Range(1, 13)')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Range(System.Int32 start, System.Int32 count)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'Enumerable.Range(1, 13)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: start) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null) (Syntax: '13')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 13) (Syntax: '13')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Enumerable.Range(1, 13)')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Range(System.Int32 start, System.Int32 count)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'Enumerable.Range(1, 13)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: start) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null) (Syntax: '13')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 13) (Syntax: '13')
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)
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '4 * a')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: '4 * a')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '4 * a')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '4 * a')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '4 * a')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: '4 * a')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Right:
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'b')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'b')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'b')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'b')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'b')
ReturnedValue:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'a')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, System.Int32>, IsImplicit) (Syntax: 'a')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'a')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'a')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'a')
ReturnedValue:
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(541789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541789")]
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void WhereClauseTest()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
where (x > 2)
select x;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "3 4");
}
[WorkItem(541942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541942")]
[Fact]
public void WhereDefinedInType()
{
var csSource = @"
using System;
class Y
{
public int Where(Func<int, bool> predicate)
{
return 45;
}
}
class P
{
static void Main()
{
var src = new Y();
var query = from x in src
where x > 0
select x;
Console.Write(query);
}
}";
CompileAndVerify(csSource, expectedOutput: "45");
}
[Fact]
public void GetInfoForSelectExpression01()
{
string sourceCode = @"
using System;
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
SelectClauseSyntax selectClause = (SelectClauseSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("select", StringComparison.Ordinal)).Parent;
var info = semanticModel.GetSemanticInfoSummary(selectClause.Expression);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
var info2 = semanticModel.GetSemanticInfoSummary(selectClause);
var m = (IMethodSymbol)info2.Symbol;
Assert.Equal("Select", m.ReducedFrom.Name);
}
[Fact]
public void GetInfoForSelectExpression02()
{
string sourceCode = @"
using System;
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x into w
select w;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
SelectClauseSyntax selectClause = (SelectClauseSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("select w", StringComparison.Ordinal)).Parent;
var info = semanticModel.GetSemanticInfoSummary(selectClause.Expression);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
}
[Fact]
public void GetInfoForSelectExpression03()
{
string sourceCode = @"
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x+1 into w
select w+1;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
compilation.VerifyDiagnostics();
var semanticModel = compilation.GetSemanticModel(tree);
var e = (IdentifierNameSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("x+1", StringComparison.Ordinal)).Parent;
var info = semanticModel.GetSemanticInfoSummary(e);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
Assert.Equal("x", info.Symbol.Name);
e = (IdentifierNameSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("w+1", StringComparison.Ordinal)).Parent;
info = semanticModel.GetSemanticInfoSummary(e);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
Assert.Equal("w", info.Symbol.Name);
var e2 = e.Parent as ExpressionSyntax; // w+1
var info2 = semanticModel.GetSemanticInfoSummary(e2);
Assert.Equal(SpecialType.System_Int32, info2.Type.SpecialType);
Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", info2.Symbol.ToTestDisplayString());
}
[WorkItem(541806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541806")]
[Fact]
public void GetDeclaredSymbolForQueryContinuation()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x into w
select w;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var queryContinuation = tree.GetRoot().FindToken(sourceCode.IndexOf("into w", StringComparison.Ordinal)).Parent;
var symbol = semanticModel.GetDeclaredSymbol(queryContinuation);
Assert.NotNull(symbol);
Assert.Equal("w", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
}
[WorkItem(541899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541899")]
[Fact]
public void ComputeQueryVariableType()
{
string sourceCode = @"
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select 5;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectExpression = tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf('5'));
var info = semanticModel.GetSpeculativeTypeInfo(selectExpression.SpanStart, SyntaxFactory.ParseExpression("x"), SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
}
[WorkItem(541893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541893")]
[Fact]
public void GetDeclaredSymbolForJoinIntoClause()
{
string sourceCode = @"
using System;
using System.Linq;
static class Test
{
static void Main()
{
var qie = from x3 in new int[] { 0 }
join x7 in (new int[] { 0 }) on 5 equals 5 into x8
select x8;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var joinInto = tree.GetRoot().FindToken(sourceCode.IndexOf("into x8", StringComparison.Ordinal)).Parent;
var symbol = semanticModel.GetDeclaredSymbol(joinInto);
Assert.NotNull(symbol);
Assert.Equal("x8", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
Assert.Equal("? x8", symbol.ToTestDisplayString());
}
[WorkItem(541982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541982")]
[WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")]
[Fact()]
public void GetDeclaredSymbolAddAccessorDeclIncompleteQuery()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var expr1 = new[] { 1, 2, 3, 4, 5 };
var query1 = from event in expr1 select event;
var query2 = from int
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var unknownAccessorDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>();
var symbols = unknownAccessorDecls.Select(decl => semanticModel.GetDeclaredSymbol(decl));
Assert.True(symbols.All(s => ReferenceEquals(s, null)));
}
[WorkItem(542235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542235")]
[Fact]
public void TwoFromClauseFollowedBySelectClause()
{
string sourceCode = @"
using System.Linq;
class Test
{
public static void Main()
{
var q2 = from num1 in new int[] { 4, 5 }
from num2 in new int[] { 4, 5 }
select num1;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SelectClause)).Single() as SelectClauseSyntax;
var fromClause1 = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => (n.IsKind(SyntaxKind.FromClause)) && (n.ToString().Contains("num1"))).Single() as FromClauseSyntax;
var fromClause2 = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => (n.IsKind(SyntaxKind.FromClause)) && (n.ToString().Contains("num2"))).Single() as FromClauseSyntax;
var symbolInfoForSelect = semanticModel.GetSemanticInfoSummary(selectClause);
var queryInfoForFrom1 = semanticModel.GetQueryClauseInfo(fromClause1);
var queryInfoForFrom2 = semanticModel.GetQueryClauseInfo(fromClause2);
Assert.Null(queryInfoForFrom1.CastInfo.Symbol);
Assert.Null(queryInfoForFrom1.OperationInfo.Symbol);
Assert.Null(queryInfoForFrom2.CastInfo.Symbol);
Assert.Equal("SelectMany", queryInfoForFrom2.OperationInfo.Symbol.Name);
Assert.Null(symbolInfoForSelect.Symbol);
Assert.Empty(symbolInfoForSelect.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfoForSelect.CandidateReason);
}
[WorkItem(528747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528747")]
[Fact]
public void SemanticInfoForOrderingClauses()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var q1 =
from x in new int[] { 4, 5 }
orderby
x descending,
x.ToString() ascending,
x descending
select x;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
int count = 0;
string[] names = { "OrderByDescending", "ThenBy", "ThenByDescending" };
foreach (var ordering in tree.GetCompilationUnitRoot().DescendantNodes().OfType<OrderingSyntax>())
{
var symbolInfo = model.GetSemanticInfoSummary(ordering);
Assert.Equal(names[count++], symbolInfo.Symbol.Name);
}
Assert.Equal(3, count);
}
[WorkItem(542266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542266")]
[Fact]
public void FromOrderBySelectQueryTranslation()
{
string sourceCode = @"
using System;
using System.Collections;
using System.Collections.Generic;
public interface IOrderedEnumerable<TElement> : IEnumerable<TElement>,
IEnumerable
{
}
public static class Extensions
{
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return null;
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector)
{
return null;
}
}
class Program
{
static void Main(string[] args)
{
var q1 = from num in new int[] { 4, 5 }
orderby num
select num;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SelectClause)).Single() as SelectClauseSyntax;
var symbolInfoForSelect = semanticModel.GetSemanticInfoSummary(selectClause);
Assert.Null(symbolInfoForSelect.Symbol);
}
[WorkItem(528756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528756")]
[Fact]
public void FromWhereSelectTranslation()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
public static class Extensions
{
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
return null;
}
}
class Program
{
static void Main(string[] args)
{
var q1 = from num in System.Linq.Enumerable.Range(4, 5).Where(n => n > 10)
select num;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
semanticModel.GetDiagnostics().Verify(
// (21,30): error CS1935: Could not find an implementation of the query pattern for source type 'System.Collections.Generic.IEnumerable<int>'. 'Select' not found. Are you missing required assembly references or a using directive for 'System.Linq'?
// var q1 = from num in System.Linq.Enumerable.Range(4, 5).Where(n => n > 10)
Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, "System.Linq.Enumerable.Range(4, 5).Where(n => n > 10)").WithArguments("System.Collections.Generic.IEnumerable<int>", "Select"));
}
[WorkItem(528760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528760")]
[Fact]
public void FromJoinSelectTranslation()
{
string sourceCode = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q1 = from num in new int[] { 4, 5 }
join x1 in new int[] { 4, 5 } on num equals x1
select x1 + 5;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SelectClause)).Single() as SelectClauseSyntax;
var symbolInfoForSelect = semanticModel.GetSemanticInfoSummary(selectClause);
Assert.Null(symbolInfoForSelect.Symbol);
}
[WorkItem(528761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528761")]
[WorkItem(544585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544585")]
[Fact]
public void OrderingSyntaxWithOverloadResolutionFailure()
{
string sourceCode = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[] { 4, 5 };
var q1 = from num in numbers.Single()
orderby (x1) => x1.ToString()
select num;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (10,30): error CS1936: Could not find an implementation of the query pattern for source type 'int'. 'OrderBy' not found.
// var q1 = from num in numbers.Single()
Diagnostic(ErrorCode.ERR_QueryNoProvider, "numbers.Single()").WithArguments("int", "OrderBy")
);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var orderingClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.AscendingOrdering)).Single() as OrderingSyntax;
var symbolInfoForOrdering = semanticModel.GetSemanticInfoSummary(orderingClause);
Assert.Null(symbolInfoForOrdering.Symbol);
}
[WorkItem(542292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542292")]
[Fact]
public void EmitIncompleteQueryWithSyntaxErrors()
{
string sourceCode = @"
using System.Linq;
class Program
{
static int Main()
{
int [] goo = new int [] {1};
var q = from x in goo
select x + 1 into z
select z.T
";
using (var output = new MemoryStream())
{
Assert.False(CreateCompilationWithMscorlib40AndSystemCore(sourceCode).Emit(output).Success);
}
}
[WorkItem(542294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542294")]
[Fact]
public void EmitQueryWithBindErrors()
{
string sourceCode = @"
using System.Linq;
class Program
{
static void Main()
{
int[] nums = { 0, 1, 2, 3, 4, 5 };
var query = from num in nums
let num = 3 // CS1930
select num;
}
}";
using (var output = new MemoryStream())
{
Assert.False(CreateCompilationWithMscorlib40AndSystemCore(sourceCode).Emit(output).Success);
}
}
[WorkItem(542372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542372")]
[Fact]
public void BindToIncompleteSelectManyDecl()
{
string sourceCode = @"
class P
{
static C<X> M2<X>(X x)
{
return new C<X>(x);
}
static void Main()
{
C<int> e1 = new C<int>(1);
var q = from x1 in M2<int>(x1)
from x2 in e1
select x1;
}
}
class C<T>
{
public C<V> SelectMany";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var diags = semanticModel.GetDiagnostics();
Assert.NotEmpty(diags);
}
[WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")]
[Fact]
public void BindIdentifierInWhereErrorTolerance()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var r = args.Where(b => b < > );
var q = from a in args
where a <>
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var diags = semanticModel.GetDiagnostics();
Assert.NotEmpty(diags);
}
[WorkItem(542460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542460")]
[Fact]
public void QueryWithMultipleParseErrorsAndScriptParseOption()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var expr1 = new int[] { 1, 2, 3, 4, 5 };
var query2 = from int namespace in expr1 select namespace;
var query25 = from i in expr1 let namespace = expr1 select i;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode, parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var queryExpr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<QueryExpressionSyntax>().Where(x => x.ToFullString() == "from i in expr1 let ").Single();
var symbolInfo = semanticModel.GetSemanticInfoSummary(queryExpr);
Assert.Null(symbolInfo.Symbol);
}
[WorkItem(542496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542496")]
[Fact]
public void QueryExpressionInFieldInitReferencingAnotherFieldWithScriptParseOption()
{
string sourceCode = @"
using System.Linq;
using System.Collections;
class P
{
double one = 1;
public IEnumerable e =
from x in new int[] { 1, 2, 3 }
select x + one;
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode, parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var queryExpr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<QueryExpressionSyntax>().Single();
var symbolInfo = semanticModel.GetSemanticInfoSummary(queryExpr);
Assert.Null(symbolInfo.Symbol);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(542559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542559")]
[ConditionalFact(typeof(DesktopOnly))]
public void StaticTypeInFromClause()
{
string source = @"
using System;
using System.Linq;
class C
{
static void Main()
{
var q2 = string.Empty.Cast<GC>().Select(x => x);
var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
}
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0718: 'GC': static types cannot be used as type arguments
// var q2 = string.Empty.Cast<GC>().Select(x => x);
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "string.Empty.Cast<GC>").WithArguments("System.GC").WithLocation(9, 18),
// CS0718: 'GC': static types cannot be used as type arguments
// var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "from GC x in string.Empty").WithArguments("System.GC").WithLocation(10, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from GC x i ... ty select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select x')
Children(2):
IInvocationOperation (System.Collections.Generic.IEnumerable<System.GC> System.Linq.Enumerable.Cast<System.GC>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.GC>, IsInvalid, IsImplicit) (Syntax: 'from GC x i ... tring.Empty')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'string.Empty')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsInvalid, IsImplicit) (Syntax: 'string.Empty')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty')
Instance Receiver:
null
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)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.GC) (Syntax: 'x')
", new DiagnosticDescription[] {
// CS0718: 'GC': static types cannot be used as type arguments
// var q2 = string.Empty.Cast<GC>().Select(x => x);
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "string.Empty.Cast<GC>").WithArguments("System.GC").WithLocation(9, 18),
// CS0718: 'GC': static types cannot be used as type arguments
// var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "from GC x in string.Empty").WithArguments("System.GC").WithLocation(10, 28)
}, parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from GC x i ... ty select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select x')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from GC x i ... tring.Empty')
Children(1):
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty')
Instance Receiver:
null
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?) (Syntax: 'x')
", new DiagnosticDescription[] {
// file.cs(9,31): error CS0718: 'GC': static types cannot be used as type arguments
// var q2 = string.Empty.Cast<GC>().Select(x => x);
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "Cast<GC>").WithArguments("System.GC").WithLocation(9, 31),
// file.cs(10,28): error CS0718: 'GC': static types cannot be used as type arguments
// var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "from GC x in string.Empty").WithArguments("System.GC").WithLocation(10, 28)
});
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(542560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542560")]
[Fact]
public void MethodGroupInFromClause()
{
string source = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var q1 = /*<bind>*/from y in Main select y/*</bind>*/;
var q2 = Main.Select(y => y);
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from y in Main select y')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select y')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from y in Main')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Main')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Main')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y')
ReturnedValue:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: ?) (Syntax: 'y')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0119: 'Program.Main()' is a method, which is not valid in the given context
// var q1 = /*<bind>*/from y in Main select y/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(9, 38),
// CS0119: 'Program.Main()' is a method, which is not valid in the given context
// var q2 = Main.Select(y => y);
Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(10, 18)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(542558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542558")]
[Fact]
public void SelectFromType01()
{
string sourceCode = @"using System;
using System.Collections.Generic;
class C
{
static void Main()
{
var q = from x in C select x;
}
static IEnumerable<T> Select<T>(Func<int, T> f) { return null; }
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "C").Single();
dynamic main = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = main.Body.Statements[0].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Null(info0.CastInfo.Symbol);
Assert.Null(info0.OperationInfo.Symbol);
var infoSelect = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.Equal("Select", infoSelect.Symbol.Name);
}
[WorkItem(542558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542558")]
[Fact]
public void SelectFromType02()
{
string sourceCode = @"using System;
using System.Collections.Generic;
class C
{
static void Main()
{
var q = from x in C select x;
}
static Func<Func<int, object>, IEnumerable<object>> Select = null;
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "C").Single();
dynamic main = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = main.Body.Statements[0].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Null(info0.CastInfo.Symbol);
Assert.Null(info0.OperationInfo.Symbol);
var infoSelect = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.Equal("Select", infoSelect.Symbol.Name);
}
[WorkItem(542624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542624")]
[Fact]
public void QueryColorColor()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
class Color
{
public static IEnumerable<T> Select<T>(Func<int, T> f) { return null; }
}
class Flavor
{
public IEnumerable<T> Select<T>(Func<int, T> f) { return null; }
}
class Program
{
Color Color;
static Flavor Flavor;
static void Main()
{
var q1 = from x in Color select x;
var q2 = from x in Flavor select x;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (17,11): warning CS0169: The field 'Program.Color' is never used
// Color Color;
Diagnostic(ErrorCode.WRN_UnreferencedField, "Color").WithArguments("Program.Color"),
// (18,19): warning CS0649: Field 'Program.Flavor' is never assigned to, and will always have its default value null
// static Flavor Flavor;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Flavor").WithArguments("Program.Flavor", "null")
);
}
[WorkItem(542704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542704")]
[Fact]
public void QueryOnSourceWithGroupByMethod()
{
string source = @"
delegate T Func<A, T>(A a);
class Y<U>
{
public U u;
public Y(U u)
{
this.u = u;
}
public string GroupBy(Func<U, string> keySelector)
{
return null;
}
}
class Test
{
static int Main()
{
Y<int> src = new Y<int>(2);
string q1 = src.GroupBy(x => x.GetType().Name); // ok
string q2 = from x in src group x by x.GetType().Name; // Roslyn CS1501
return 0;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void RangeTypeAlreadySpecified()
{
string source = @"
using System.Linq;
using System.Collections;
static class Test
{
public static void Main2()
{
var list = new CastableToArrayList();
var q = /*<bind>*/from int x in list
select x + 1/*</bind>*/;
}
}
class CastableToArrayList
{
public ArrayList Cast<T>() { return null; }
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from int x ... elect x + 1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select x + 1')
Children(2):
IInvocationOperation ( System.Collections.ArrayList CastableToArrayList.Cast<System.Int32>()) (OperationKind.Invocation, Type: System.Collections.ArrayList, IsInvalid, IsImplicit) (Syntax: 'from int x in list')
Instance Receiver:
ILocalReferenceOperation: list (OperationKind.LocalReference, Type: CastableToArrayList, IsInvalid) (Syntax: 'list')
Arguments(0)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?) (Syntax: 'x + 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1936: Could not find an implementation of the query pattern for source type 'ArrayList'. 'Select' not found.
// var q = /*<bind>*/from int x in list
Diagnostic(ErrorCode.ERR_QueryNoProvider, "list").WithArguments("System.Collections.ArrayList", "Select").WithLocation(10, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(11414, "DevDiv_Projects/Roslyn")]
[Fact]
public void InvalidQueryWithAnonTypesAndKeywords()
{
string source = @"
public class QueryExpressionTest
{
public static void Main()
{
var query7 = from i in expr1 join const in expr2 on i equals const select new { i, const };
var query8 = from int i in expr1 select new { i, const };
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
Assert.NotEmpty(compilation.GetDiagnostics());
}
[WorkItem(543787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543787")]
[ClrOnlyFact]
public void GetSymbolInfoOfSelectNodeWhenTypeOfRangeVariableIsErrorType()
{
string source = @"
using System.Linq;
class Test
{
static void V()
{
}
public static int Main()
{
var e1 = from i in V() select i;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees.First();
var index = source.IndexOf("select i", StringComparison.Ordinal);
var selectNode = tree.GetCompilationUnitRoot().FindToken(index).Parent as SelectClauseSyntax;
var model = compilation.GetSemanticModel(tree);
var symbolInfo = model.GetSymbolInfo(selectNode);
// https://github.com/dotnet/roslyn/issues/38509
// Assert.NotEqual(default, symbolInfo);
Assert.Null(symbolInfo.Symbol); // there is no select method to call because the receiver is bad
var typeInfo = model.GetTypeInfo(selectNode);
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
}
[WorkItem(543790, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543790")]
[Fact]
public void GetQueryClauseInfoForQueryWithSyntaxErrors()
{
string source = @"
using System.Linq;
class Test
{
public static void Main ()
{
var query8 = from int i in expr1 join int delegate in expr2 on i equals delegate select new { i, delegate };
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees.First();
var index = source.IndexOf("join int delegate in expr2 on i equals delegate", StringComparison.Ordinal);
var joinNode = tree.GetCompilationUnitRoot().FindToken(index).Parent as JoinClauseSyntax;
var model = compilation.GetSemanticModel(tree);
var queryInfo = model.GetQueryClauseInfo(joinNode);
// https://github.com/dotnet/roslyn/issues/38509
// Assert.NotEqual(default, queryInfo);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(545797, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545797")]
[Fact]
public void QueryOnNull()
{
string source = @"
using System;
static class C
{
static void Main()
{
var q = /*<bind>*/from x in null select x/*</bind>*/;
}
static object Select(this object x, Func<int, int> y)
{
return null;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Object, IsInvalid) (Syntax: 'from x in null select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'select x')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'from x in null')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0186: Use of null is not valid in this context
// var q = /*<bind>*/from x in null select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_NullNotValid, "select x").WithLocation(7, 42)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(545797, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545797")]
[Fact]
public void QueryOnLambda()
{
string source = @"
using System;
static class C
{
static void Main()
{
var q = /*<bind>*/from x in y => y select x/*</bind>*/;
}
static object Select(this object x, Func<int, int> y)
{
return null;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Object, IsInvalid) (Syntax: 'from x in y ... y select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'select x')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'from x in y => y')
Children(1):
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'y => y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y')
ReturnedValue:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: ?) (Syntax: 'y')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1936: Could not find an implementation of the query pattern for source type 'anonymous method'. 'Select' not found.
// var q = /*<bind>*/from x in y => y select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select x").WithArguments("anonymous method", "Select").WithLocation(7, 44)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(545444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545444")]
[Fact]
public void RefOmittedOnComCall()
{
string source = @"using System;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""A88A175D-2448-447A-B786-64682CBEF156"")]
public interface IRef1
{
int M(ref int x, int y);
}
public class Ref1Impl : IRef1
{
public int M(ref int x, int y) { return x + y; }
}
class Test
{
public static void Main()
{
IRef1 ref1 = new Ref1Impl();
Expression<Func<int, int, int>> F = (x, y) => ref1.M(x, y);
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (22,54): error CS2037: An expression tree lambda may not contain a COM call with ref omitted on arguments
// Expression<Func<int, int, int>> F = (x, y) => ref1.M(x, y);
Diagnostic(ErrorCode.ERR_ComRefCallInExpressionTree, "ref1.M(x, y)")
);
}
[Fact, WorkItem(5728, "https://github.com/dotnet/roslyn/issues/5728")]
public void RefOmittedOnComCallErr()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""A88A175D-2448-447A-B786-64682CBEF156"")]
public interface IRef1
{
long M(uint y, ref int x, int z);
long M(uint y, ref int x, int z, int q);
}
public class Ref1Impl : IRef1
{
public long M(uint y, ref int x, int z) { return x + y; }
public long M(uint y, ref int x, int z, int q) { return x + y; }
}
class Test1
{
static void Test(Expression<Action<IRef1>> e)
{
}
static void Test<U>(Expression<Func<IRef1, U>> e)
{
}
public static void Main()
{
Test(ref1 => ref1.M(1, ));
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (34,32): error CS1525: Invalid expression term ')'
// Test(ref1 => ref1.M(1, ));
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(34, 32)
);
}
[WorkItem(529350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529350")]
[Fact]
public void BindLambdaBodyWhenError()
{
string source =
@"using System.Linq;
class A
{
static void Main()
{
}
static void M(System.Reflection.Assembly[] a)
{
var q2 = a.SelectMany(assem2 => assem2.UNDEFINED, (assem2, t) => t);
var q1 = from assem1 in a
from t in assem1.UNDEFINED
select t;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (10,48): error CS1061: 'System.Reflection.Assembly' does not contain a definition for 'UNDEFINED' and no extension method 'UNDEFINED' accepting a first argument of type 'System.Reflection.Assembly' could be found (are you missing a using directive or an assembly reference?)
// var q2 = a.SelectMany(assem2 => assem2.UNDEFINED, (assem2, t) => t);
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "UNDEFINED").WithArguments("System.Reflection.Assembly", "UNDEFINED"),
// (13,35): error CS1061: 'System.Reflection.Assembly' does not contain a definition for 'UNDEFINED' and no extension method 'UNDEFINED' accepting a first argument of type 'System.Reflection.Assembly' could be found (are you missing a using directive or an assembly reference?)
// from t in assem1.UNDEFINED
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "UNDEFINED").WithArguments("System.Reflection.Assembly", "UNDEFINED")
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var assem2 =
tree.GetCompilationUnitRoot().DescendantNodes(n => n.ToString().Contains("assem2"))
.Where(e => e.ToString() == "assem2")
.OfType<ExpressionSyntax>()
.Single();
var typeInfo2 = model.GetTypeInfo(assem2);
Assert.NotEqual(TypeKind.Error, typeInfo2.Type.TypeKind);
Assert.Equal("Assembly", typeInfo2.Type.Name);
var assem1 =
tree.GetCompilationUnitRoot().DescendantNodes(n => n.ToString().Contains("assem1"))
.Where(e => e.ToString() == "assem1")
.OfType<ExpressionSyntax>()
.Single();
var typeInfo1 = model.GetTypeInfo(assem1);
Assert.NotEqual(TypeKind.Error, typeInfo1.Type.TypeKind);
Assert.Equal("Assembly", typeInfo1.Type.Name);
}
[Fact]
public void TestSpeculativeSemanticModel_GetQueryClauseInfo()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
}
}";
var speculatedSource = @"
C r1 =
from int x in c1
from int y in c2
select x + y;
";
var queryStatement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.Statements[1].Span.End, queryStatement, out speculativeModel);
Assert.True(success);
var q = (QueryExpressionSyntax)queryStatement.Declaration.Variables[0].Initializer.Value;
var info0 = speculativeModel.GetQueryClauseInfo(q.FromClause);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.Null(info0.OperationInfo.Symbol);
Assert.Equal("x", speculativeModel.GetDeclaredSymbol(q.FromClause).Name);
var info1 = speculativeModel.GetQueryClauseInfo(q.Body.Clauses[0]);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.Equal("y", speculativeModel.GetDeclaredSymbol(q.Body.Clauses[0]).Name);
}
[Fact]
public void TestSpeculativeSemanticModel_GetSemanticInfoForSelectClause()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
}
}";
var speculatedSource = @"
C r1 =
from int x in c1
select x;
";
var queryStatement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.Statements[1].Span.End, queryStatement, out speculativeModel);
Assert.True(success);
var q = (QueryExpressionSyntax)queryStatement.Declaration.Variables[0].Initializer.Value;
var x = speculativeModel.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
var selectExpression = (q.Body.SelectOrGroup as SelectClauseSyntax).Expression;
Assert.Equal(x, speculativeModel.GetSemanticInfoSummary(selectExpression).Symbol);
var selectClauseSymbolInfo = speculativeModel.GetSymbolInfo(q.Body.SelectOrGroup);
Assert.NotNull(selectClauseSymbolInfo.Symbol);
Assert.Equal("Select", selectClauseSymbolInfo.Symbol.Name);
var selectClauseTypeInfo = speculativeModel.GetTypeInfo(q.Body.SelectOrGroup);
Assert.NotNull(selectClauseTypeInfo.Type);
Assert.Equal("List1", selectClauseTypeInfo.Type.Name);
}
[Fact]
public void TestSpeculativeSemanticModel_GetDeclaredSymbolForJoinIntoClause()
{
string sourceCode = @"
public class Test
{
public static void Main()
{
}
}";
var speculatedSource = @"
var qie = from x3 in new int[] { 0 }
join x7 in (new int[] { 1 }) on 5 equals 5 into x8
select x8;
";
var queryStatement = SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Test").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.SpanStart, queryStatement, out speculativeModel);
var queryExpression = (QueryExpressionSyntax)((LocalDeclarationStatementSyntax)queryStatement).Declaration.Variables[0].Initializer.Value;
JoinIntoClauseSyntax joinInto = ((JoinClauseSyntax)queryExpression.Body.Clauses[0]).Into;
var symbol = speculativeModel.GetDeclaredSymbol(joinInto);
Assert.NotNull(symbol);
Assert.Equal("x8", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
Assert.Equal("? x8", symbol.ToTestDisplayString());
}
[Fact]
public void TestSpeculativeSemanticModel_GetDeclaredSymbolForQueryContinuation()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
}
}";
var speculatedSource = @"
var q2 = from x in nums
select x into w
select w;
";
var queryStatement = SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Test2").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.Statements[0].Span.End, queryStatement, out speculativeModel);
Assert.True(success);
var queryExpression = (QueryExpressionSyntax)((LocalDeclarationStatementSyntax)queryStatement).Declaration.Variables[0].Initializer.Value;
var queryContinuation = queryExpression.Body.Continuation;
var symbol = speculativeModel.GetDeclaredSymbol(queryContinuation);
Assert.NotNull(symbol);
Assert.Equal("w", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
}
[Fact]
public void TestSpeculativeSemanticModel_GetSymbolInfoForOrderingClauses()
{
string sourceCode = @"
using System.Linq; // Needed for speculative code.
public class QueryExpressionTest
{
public static void Main()
{
}
}";
var speculatedSource = @"
var q1 =
from x in new int[] { 4, 5 }
orderby
x descending,
x.ToString() ascending,
x descending
select x;
";
var queryStatement = SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System.Linq; // Needed for speculative code.
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Linq;"));
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "QueryExpressionTest").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.SpanStart, queryStatement, out speculativeModel);
Assert.True(success);
int count = 0;
string[] names = { "OrderByDescending", "ThenBy", "ThenByDescending" };
foreach (var ordering in queryStatement.DescendantNodes().OfType<OrderingSyntax>())
{
var symbolInfo = speculativeModel.GetSemanticInfoSummary(ordering);
Assert.Equal(names[count++], symbolInfo.Symbol.Name);
}
Assert.Equal(3, count);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void BrokenQueryPattern()
{
string source = @"
using System;
class Q<T>
{
public Q<V> SelectMany<U, V>(Func<T, U> f1, Func<T, U, V> f2) { return null; }
public Q<U> Select<U>(Func<T, U> f1) { return null; }
//public Q<T> Where(Func<T, bool> f1) { return null; }
public X Where(Func<T, bool> f1) { return null; }
}
class X
{
public X Select<U>(Func<int, U> f1) { return null; }
}
class Program
{
static void Main(string[] args)
{
Q<int> q = null;
var r =
/*<bind>*/from x in q
from y in q
where x.ToString() == y.ToString()
select x.ToString()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: X, IsInvalid) (Syntax: 'from x in q ... .ToString()')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: X, IsInvalid, IsImplicit) (Syntax: 'select x.ToString()')
Children(2):
IInvocationOperation ( X Q<<anonymous type: System.Int32 x, Q<System.Int32> y>>.Where(System.Func<<anonymous type: System.Int32 x, Q<System.Int32> y>, System.Boolean> f1)) (OperationKind.Invocation, Type: X, IsImplicit) (Syntax: 'where x.ToS ... .ToString()')
Instance Receiver:
IInvocationOperation ( Q<<anonymous type: System.Int32 x, Q<System.Int32> y>> Q<System.Int32>.SelectMany<Q<System.Int32>, <anonymous type: System.Int32 x, Q<System.Int32> y>>(System.Func<System.Int32, Q<System.Int32>> f1, System.Func<System.Int32, Q<System.Int32>, <anonymous type: System.Int32 x, Q<System.Int32> y>> f2)) (OperationKind.Invocation, Type: Q<<anonymous type: System.Int32 x, Q<System.Int32> y>>, IsImplicit) (Syntax: 'from y in q')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: Q<System.Int32>) (Syntax: 'q')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f1) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, Q<System.Int32>>, IsImplicit) (Syntax: 'q')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'q')
ReturnedValue:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: Q<System.Int32>) (Syntax: 'q')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from y in q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, Q<System.Int32>, <anonymous type: System.Int32 x, Q<System.Int32> y>>, IsImplicit) (Syntax: 'from y in q')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from y in q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from y in q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from y in q')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'from y in q')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'from y in q ... .ToString()')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, Q<System.Int32> y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in q')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'from y in q')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in q')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: Q<System.Int32>, IsInvalid, IsImplicit) (Syntax: 'from y in q ... .ToString()')
Left:
IPropertyReferenceOperation: Q<System.Int32> <anonymous type: System.Int32 x, Q<System.Int32> y>.y { get; } (OperationKind.PropertyReference, Type: Q<System.Int32>, IsImplicit) (Syntax: 'from y in q')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'from y in q')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: Q<System.Int32>, IsImplicit) (Syntax: 'from y in q')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f1) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, Q<System.Int32> y>, System.Boolean>, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x.ToString( ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Int32.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x.ToString()')
Instance Receiver:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, Q<System.Int32> y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'x')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'y.ToString()')
Instance Receiver:
IPropertyReferenceOperation: Q<System.Int32> <anonymous type: System.Int32 x, Q<System.Int32> y>.y { get; } (OperationKind.PropertyReference, Type: Q<System.Int32>) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'y')
Arguments(0)
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)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'x.ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'x.ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'x.ToString()')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.ToString()')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'x.ToString')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8016: Transparent identifier member access failed for field 'x' of 'int'. Does the data being queried implement the query pattern?
// select x.ToString()/*</bind>*/;
Diagnostic(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, "x").WithArguments("x", "int").WithLocation(27, 20)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_01()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var x01 = from a in Test select a + 1;
}
}
public class Test
{
}
public static class TestExtensions
{
public static Test Select<T>(this Test x, System.Func<int, T> selector)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (6,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Select' not found.
// var x01 = from a in Test select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select a + 1").WithArguments("Test", "Select").WithLocation(6, 34)
);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_02()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var y02 = from a in Test select a + 1;
var x02 = from a in Test where a > 0 select a + 1;
}
}
class Test
{
public static Test Select<T>(System.Func<int, T> selector)
{
return null;
}
}
static class TestExtensions
{
public static Test Where(this Test x, System.Func<int, bool> filter)
{
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (7,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Where' not found.
// var x02 = from a in Test where a > 0 select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "where a > 0").WithArguments("Test", "Where").WithLocation(7, 34),
// (7,46): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Select' not found.
// var x02 = from a in Test where a > 0 select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select a + 1").WithArguments("Test", "Select").WithLocation(7, 46)
);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_03()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var y03 = from a in Test select a + 1;
var x03 = from a in Test where a > 0 select a + 1;
}
}
class Test
{
}
static class TestExtensions
{
public static Test Select<T>(this Test x, System.Func<int, T> selector)
{
return null;
}
public static Test Where(this Test x, System.Func<int, bool> filter)
{
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (6,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Select' not found.
// var y03 = from a in Test select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select a + 1").WithArguments("Test", "Select").WithLocation(6, 34),
// (7,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Where' not found.
// var x03 = from a in Test where a > 0 select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "where a > 0").WithArguments("Test", "Where").WithLocation(7, 34)
);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_04()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var x04 = from a in Test select a + 1;
}
}
class Test
{
public static Test Select<T>(System.Func<int, T> selector)
{
System.Console.WriteLine(""Select"");
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput: "Select");
}
[WorkItem(15910, "https://github.com/dotnet/roslyn/issues/15910")]
[Fact]
public void ExpressionVariablesInQueryClause_01()
{
var csSource = @"
using System.Linq;
class Program
{
public static void Main(string[] args)
{
var a = new[] { 1, 2, 3, 4 };
var za = from x in M(a, out var q1) select x; // ok
var zc = from x in a from y in M(a, out var z) select x; // error 1
var zd = from x in a from int y in M(a, out var z) select x; // error 2
var ze = from x in a from y in M(a, out var z) where true select x; // error 3
var zf = from x in a from int y in M(a, out var z) where true select x; // error 4
var zg = from x in a let y = M(a, out var z) select x; // error 5
var zh = from x in a where M(x, out var z) == 1 select x; // error 6
var zi = from x in a join y in M(a, out var q2) on x equals y select x; // ok
var zj = from x in a join y in a on M(x, out var z) equals y select x; // error 7
var zk = from x in a join y in a on x equals M(y, out var z) select x; // error 8
var zl = from x in a orderby M(x, out var z) select x; // error 9
var zm = from x in a orderby x, M(x, out var z) select x; // error 10
var zn = from x in a group M(x, out var z) by x; // error 11
var zo = from x in a group x by M(x, out var z); // error 12
}
public static T M<T>(T x, out T z) => z = x;
}";
CreateCompilationWithMscorlib40AndSystemCore(csSource, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (10,53): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zc = from x in a from y in M(a, out var z) select x; // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(10, 53),
// (11,57): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zd = from x in a from int y in M(a, out var z) select x; // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(11, 57),
// (12,53): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var ze = from x in a from y in M(a, out var z) where true select x; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 53),
// (13,57): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zf = from x in a from int y in M(a, out var z) where true select x; // error 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(13, 57),
// (14,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zg = from x in a let y = M(a, out var z) select x; // error 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(14, 51),
// (15,49): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zh = from x in a where M(x, out var z) == 1 select x; // error 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(15, 49),
// (17,58): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zj = from x in a join y in a on M(x, out var z) equals y select x; // error 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 58),
// (18,67): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zk = from x in a join y in a on x equals M(y, out var z) select x; // error 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(18, 67),
// (19,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zl = from x in a orderby M(x, out var z) select x; // error 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(19, 51),
// (20,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zm = from x in a orderby x, M(x, out var z) select x; // error 10
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(20, 54),
// (21,49): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zn = from x in a group M(x, out var z) by x; // error 11
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(21, 49),
// (22,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zo = from x in a group x by M(x, out var z); // error 12
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(22, 54)
);
CreateCompilationWithMscorlib40AndSystemCore(csSource).VerifyDiagnostics();
}
[WorkItem(15910, "https://github.com/dotnet/roslyn/issues/15910")]
[Fact]
public void ExpressionVariablesInQueryClause_02()
{
var csSource = @"
using System.Linq;
class Program
{
public static void Main(string[] args)
{
var a = new[] { 1, 2, 3, 4 };
var za = from x in M(a, a is var q1) select x; // ok
var zc = from x in a from y in M(a, a is var z) select x; // error 1
var zd = from x in a from int y in M(a, a is var z) select x; // error 2
var ze = from x in a from y in M(a, a is var z) where true select x; // error 3
var zf = from x in a from int y in M(a, a is var z) where true select x; // error 4
var zg = from x in a let y = M(a, a is var z) select x; // error 5
var zh = from x in a where M(x, x is var z) == 1 select x; // error 6
var zi = from x in a join y in M(a, a is var q2) on x equals y select x; // ok
var zj = from x in a join y in a on M(x, x is var z) equals y select x; // error 7
var zk = from x in a join y in a on x equals M(y, y is var z) select x; // error 8
var zl = from x in a orderby M(x, x is var z) select x; // error 9
var zm = from x in a orderby x, M(x, x is var z) select x; // error 10
var zn = from x in a group M(x, x is var z) by x; // error 11
var zo = from x in a group x by M(x, x is var z); // error 12
}
public static T M<T>(T x, bool b) => x;
}";
CreateCompilationWithMscorlib40AndSystemCore(csSource, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (10,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zc = from x in a from y in M(a, a is var z) select x; // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(10, 54),
// (11,58): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zd = from x in a from int y in M(a, a is var z) select x; // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(11, 58),
// (12,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var ze = from x in a from y in M(a, a is var z) where true select x; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 54),
// (13,58): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zf = from x in a from int y in M(a, a is var z) where true select x; // error 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(13, 58),
// (14,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zg = from x in a let y = M(a, a is var z) select x; // error 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(14, 52),
// (15,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zh = from x in a where M(x, x is var z) == 1 select x; // error 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(15, 50),
// (17,59): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zj = from x in a join y in a on M(x, x is var z) equals y select x; // error 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 59),
// (18,68): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zk = from x in a join y in a on x equals M(y, y is var z) select x; // error 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(18, 68),
// (19,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zl = from x in a orderby M(x, x is var z) select x; // error 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(19, 52),
// (20,55): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zm = from x in a orderby x, M(x, x is var z) select x; // error 10
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(20, 55),
// (21,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zn = from x in a group M(x, x is var z) by x; // error 11
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(21, 50),
// (22,55): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zo = from x in a group x by M(x, x is var z); // error 12
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(22, 55)
);
CreateCompilationWithMscorlib40AndSystemCore(csSource).VerifyDiagnostics();
}
[WorkItem(15910, "https://github.com/dotnet/roslyn/issues/15910")]
[Fact]
public void ExpressionVariablesInQueryClause_03()
{
var csSource = @"
using System.Linq;
class Program
{
public static void Main(string[] args)
{
var a = new[] { (1, 2), (3, 4) };
var za = from x in M(a, (int qa, int wa) = a[0]) select x; // scoping ok
var zc = from x in a from y in M(a, (int z, int w) = x) select x; // error 1
var zd = from x in a from int y in M(a, (int z, int w) = x) select x; // error 2
var ze = from x in a from y in M(a, (int z, int w) = x) where true select x; // error 3
var zf = from x in a from int y in M(a, (int z, int w) = x) where true select x; // error 4
var zg = from x in a let y = M(x, (int z, int w) = x) select x; // error 5
var zh = from x in a where M(x, (int z, int w) = x).Item1 == 1 select x; // error 6
var zi = from x in a join y in M(a, (int qi, int wi) = a[0]) on x equals y select x; // scoping ok
var zj = from x in a join y in a on M(x, (int z, int w) = x) equals y select x; // error 7
var zk = from x in a join y in a on x equals M(y, (int z, int w) = y) select x; // error 8
var zl = from x in a orderby M(x, (int z, int w) = x) select x; // error 9
var zm = from x in a orderby x, M(x, (int z, int w) = x) select x; // error 10
var zn = from x in a group M(x, (int z, int w) = x) by x; // error 11
var zo = from x in a group x by M(x, (int z, int w) = x); // error 12
}
public static T M<T>(T x, (int, int) z) => x;
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(csSource, parseOptions: TestOptions.Regular7_2)
.GetDiagnostics()
.Where(d => d.Code != (int)ErrorCode.ERR_DeclarationExpressionNotPermitted)
.Verify(
// (10,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zc = from x in a from y in M(a, (int z, int w) = x) select x; // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(10, 50),
// (11,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zd = from x in a from int y in M(a, (int z, int w) = x) select x; // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(11, 54),
// (12,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var ze = from x in a from y in M(a, (int z, int w) = x) where true select x; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 50),
// (13,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zf = from x in a from int y in M(a, (int z, int w) = x) where true select x; // error 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(13, 54),
// (14,48): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zg = from x in a let y = M(x, (int z, int w) = x) select x; // error 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(14, 48),
// (15,46): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zh = from x in a where M(x, (int z, int w) = x).Item1 == 1 select x; // error 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(15, 46),
// (17,55): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zj = from x in a join y in a on M(x, (int z, int w) = x) equals y select x; // error 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 55),
// (18,64): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zk = from x in a join y in a on x equals M(y, (int z, int w) = y) select x; // error 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(18, 64),
// (19,48): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zl = from x in a orderby M(x, (int z, int w) = x) select x; // error 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(19, 48),
// (20,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zm = from x in a orderby x, M(x, (int z, int w) = x) select x; // error 10
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(20, 51),
// (21,46): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zn = from x in a group M(x, (int z, int w) = x) by x; // error 11
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(21, 46),
// (22,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zo = from x in a group x by M(x, (int z, int w) = x); // error 12
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(22, 51)
);
CreateCompilationWithMscorlib40AndSystemCore(csSource)
.GetDiagnostics()
.Where(d => d.Code != (int)ErrorCode.ERR_DeclarationExpressionNotPermitted)
.Verify();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(14689, "https://github.com/dotnet/roslyn/issues/14689")]
public void SelectFromNamespaceShouldGiveAnError()
{
string source = @"
using System.Linq;
using NSAlias = ParentNamespace.ConsoleApp;
namespace ParentNamespace
{
namespace ConsoleApp
{
class Program
{
static void Main()
{
var x = from c in ConsoleApp select 3;
var y = from c in ParentNamespace.ConsoleApp select 3;
var z = /*<bind>*/from c in NSAlias select 3/*</bind>*/;
}
}
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from c in N ... as select 3')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select 3')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from c in NSAlias')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'NSAlias')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '3')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0119: 'ConsoleApp' is a namespace, which is not valid in the given context
// var x = from c in ConsoleApp select 3;
Diagnostic(ErrorCode.ERR_BadSKunknown, "ConsoleApp").WithArguments("ConsoleApp", "namespace").WithLocation(13, 35),
// CS0119: 'ParentNamespace.ConsoleApp' is a namespace, which is not valid in the given context
// var y = from c in ParentNamespace.ConsoleApp select 3;
Diagnostic(ErrorCode.ERR_BadSKunknown, "ParentNamespace.ConsoleApp").WithArguments("ParentNamespace.ConsoleApp", "namespace").WithLocation(14, 35),
// CS0119: 'NSAlias' is a namespace, which is not valid in the given context
// var z = /*<bind>*/from c in NSAlias select 3/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadSKunknown, "NSAlias").WithArguments("NSAlias", "namespace").WithLocation(15, 45)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void LambdaParameterConflictsWithRangeVariable_01()
{
string source = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var res = /*<bind>*/from a in new[] { 1 }
select (Func<int, int>)(a => 1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>>, IsInvalid) (Syntax: 'from a in n ... t>)(a => 1)')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>> System.Linq.Enumerable.Select<System.Int32, System.Func<System.Int32, System.Int32>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Func<System.Int32, System.Int32>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>>, IsInvalid, IsImplicit) (Syntax: 'select (Fun ... t>)(a => 1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from a in new[] { 1 }')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from a in new[] { 1 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new[] { 1 }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[] { 1 }')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1 }')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Func<System.Int32, System.Int32>>, IsInvalid, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
ReturnedValue:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsInvalid) (Syntax: '(Func<int, int>)(a => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'a => 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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 = new DiagnosticDescription[] {
// CS0136: A local or parameter named 'a' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select (Func<int, int>)(a => 1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "a").WithArguments("a").WithLocation(10, 43)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Regular7_3);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void LambdaParameterConflictsWithRangeVariable_02()
{
string source = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var res = /*<bind>*/from a in new[] { 1 }
select (Func<int, int>)(a => 1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>>) (Syntax: 'from a in n ... t>)(a => 1)')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>> System.Linq.Enumerable.Select<System.Int32, System.Func<System.Int32, System.Int32>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Func<System.Int32, System.Int32>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>>, IsImplicit) (Syntax: 'select (Fun ... t>)(a => 1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from a in new[] { 1 }')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from a in new[] { 1 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new[] { 1 }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[] { 1 }')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1 }')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Func<System.Int32, System.Int32>>, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
ReturnedValue:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>) (Syntax: '(Func<int, int>)(a => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'a => 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void IOperationForQueryClause()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
var r = /*<bind>*/from i in c select i + 1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c select i + 1')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i + 1')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i + 1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void IOperationForRangeVariableDefinition()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
var r = /*<bind>*/from i in c select i + 1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c select i + 1')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i + 1')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i + 1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void IOperationForRangeVariableReference()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
var r = from i in c select /*<bind>*/i/*</bind>*/ + 1;
}
}
";
string expectedOperationTree = @"
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(21484, "https://github.com/dotnet/roslyn/issues/21484")]
public void QueryOnTypeExpression()
{
var code = @"
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void M<T>() where T : IEnumerable
{
var query1 = from object a in IEnumerable select 1;
var query2 = from b in IEnumerable select 2;
var query3 = from int c in IEnumerable<int> select 3;
var query4 = from d in IEnumerable<int> select 4;
var query5 = from object d in T select 5;
var query6 = from d in T select 6;
}
}
";
var comp = CreateCompilationWithMscorlib40AndSystemCore(code);
comp.VerifyDiagnostics(
// (10,22): error CS0120: An object reference is required for the non-static field, method, or property 'Enumerable.Cast<object>(IEnumerable)'
// var query1 = from object a in IEnumerable select 1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "from object a in IEnumerable").WithArguments("System.Linq.Enumerable.Cast<object>(System.Collections.IEnumerable)").WithLocation(10, 22),
// (11,32): error CS1934: Could not find an implementation of the query pattern for source type 'IEnumerable'. 'Select' not found. Consider explicitly specifying the type of the range variable 'b'.
// var query2 = from b in IEnumerable select 2;
Diagnostic(ErrorCode.ERR_QueryNoProviderCastable, "IEnumerable").WithArguments("System.Collections.IEnumerable", "Select", "b").WithLocation(11, 32),
// (13,22): error CS0120: An object reference is required for the non-static field, method, or property 'Enumerable.Cast<int>(IEnumerable)'
// var query3 = from int c in IEnumerable<int> select 3;
Diagnostic(ErrorCode.ERR_ObjectRequired, "from int c in IEnumerable<int>").WithArguments("System.Linq.Enumerable.Cast<int>(System.Collections.IEnumerable)").WithLocation(13, 22),
// (14,49): error CS1936: Could not find an implementation of the query pattern for source type 'IEnumerable<int>'. 'Select' not found.
// var query4 = from d in IEnumerable<int> select 4;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select 4").WithArguments("System.Collections.Generic.IEnumerable<int>", "Select").WithLocation(14, 49),
// (16,22): error CS0120: An object reference is required for the non-static field, method, or property 'Enumerable.Cast<object>(IEnumerable)'
// var query5 = from object d in T select 5;
Diagnostic(ErrorCode.ERR_ObjectRequired, "from object d in T").WithArguments("System.Linq.Enumerable.Cast<object>(System.Collections.IEnumerable)").WithLocation(16, 22),
// (17,32): error CS1936: Could not find an implementation of the query pattern for source type 'T'. 'Select' not found.
// var query6 = from d in T select 6;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "T").WithArguments("T", "Select").WithLocation(17, 32)
);
}
}
}
| 66.885065 | 1,332 | 0.6318 | [
"MIT"
] | 06needhamt/roslyn | src/Compilers/CSharp/Test/Semantic/Semantics/QueryTests.cs | 297,373 | C# |
#if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System.Threading;
namespace UniRx.Async.Internal
{
public static class CancellationTokenHelper
{
public static bool TrySetOrLinkCancellationToken(ref CancellationToken field, CancellationToken newCancellationToken)
{
if (newCancellationToken == CancellationToken.None)
{
return false;
}
else if (field == CancellationToken.None)
{
field = newCancellationToken;
return true;
}
else if (field == newCancellationToken)
{
return false;
}
field = CancellationTokenSource.CreateLinkedTokenSource(field, newCancellationToken).Token;
return true;
}
}
}
#endif
| 30.272727 | 126 | 0.58959 | [
"MIT"
] | cschladetsch/UniRx | Scripts/Async/Internal/CancellationTokenHelper.cs | 1,001 | C# |
using System.Collections.Generic;
using Xamarin.Forms;
namespace BindingContextChanged
{
public partial class ListPage : ContentPage
{
public ListPage ()
{
InitializeComponent ();
listView.ItemsSource = new List<string> { "Apples", "Oranges", "Pears", "Bananas", "Mangos" };
}
}
}
| 18.6875 | 97 | 0.698997 | [
"Apache-2.0"
] | HydAu/XaraminForms | UserInterface/ListView/BindingContextChanged/BindingContextChanged/ListPage.xaml.cs | 301 | C# |
using System.Runtime.Serialization;
namespace GhostSharper.Models
{
/// <summary>
/// Information about a single inventory bucket in a vendor flyout UI and how it is shown.
/// </summary>
[DataContract]
public class DestinyVendorInventoryFlyoutBucketDefinition
{
/// <summary>
/// If true, the inventory bucket should be able to be collapsed visually.
/// </summary>
[DataMember(Name = "collapsible", EmitDefaultValue = false)]
public bool Collapsible { get; set; }
/// <summary>
/// The inventory bucket whose contents should be shown.
/// </summary>
[DataMember(Name = "inventoryBucketHash", EmitDefaultValue = false)]
public uint InventoryBucketHash { get; set; }
/// <summary>
/// The methodology to use for sorting items from the flyout.
/// </summary>
[DataMember(Name = "sortItemsBy", EmitDefaultValue = false)]
public DestinyItemSortType SortItemsBy { get; set; }
public override bool Equals(object input)
{
return this.Equals(input as DestinyVendorInventoryFlyoutBucketDefinition);
}
public bool Equals(DestinyVendorInventoryFlyoutBucketDefinition input)
{
if (input == null) return false;
return
(
Collapsible == input.Collapsible ||
(Collapsible != null && Collapsible.Equals(input.Collapsible))
) &&
(
InventoryBucketHash == input.InventoryBucketHash ||
(InventoryBucketHash.Equals(input.InventoryBucketHash))
) &&
(
SortItemsBy == input.SortItemsBy ||
(SortItemsBy != null && SortItemsBy.Equals(input.SortItemsBy))
) ;
}
}
}
| 33.821429 | 94 | 0.57339 | [
"MIT",
"BSD-3-Clause"
] | joshhunt/GhostSharper | BungieNetApi/Models/DestinyVendorInventoryFlyoutBucketDefinition.cs | 1,894 | C# |
namespace AnnoSavegameViewer.Structures.Savegame.Generated {
using AnnoSavegameViewer.Serialization.Core;
using System.Collections.Generic;
public class DecreeFlags {
#region Public Properties
[BinaryContent(Name = "None", NodeType = BinaryContentTypes.Attribute)]
public List<object> None { get; set; }
#endregion Public Properties
}
} | 26 | 75 | 0.752747 | [
"MIT"
] | Veraatversus/AnnoSavegameViewer | src/AnnoSavegameViewer/GeneratedA7s/Structures/Savegame2/Generated/Content/DecreeFlags.cs | 364 | 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.DevTestLabs
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PoliciesOperations operations.
/// </summary>
public partial interface IPoliciesOperations
{
/// <summary>
/// List policies in a given policy set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='policySetName'>
/// The name of the policy set.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Policy>>> ListWithHttpMessagesAsync(string resourceGroupName, string labName, string policySetName, ODataQuery<Policy> odataQuery = default(ODataQuery<Policy>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get policy.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='policySetName'>
/// The name of the policy set.
/// </param>
/// <param name='name'>
/// The name of the policy.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example:
/// 'properties($select=description)'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Policy>> GetWithHttpMessagesAsync(string resourceGroupName, string labName, string policySetName, string name, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or replace an existing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='policySetName'>
/// The name of the policy set.
/// </param>
/// <param name='name'>
/// The name of the policy.
/// </param>
/// <param name='policy'>
/// A Policy.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Policy>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string labName, string policySetName, string name, Policy policy, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete policy.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='policySetName'>
/// The name of the policy set.
/// </param>
/// <param name='name'>
/// The name of the policy.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string labName, string policySetName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Modify properties of policies.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='policySetName'>
/// The name of the policy set.
/// </param>
/// <param name='name'>
/// The name of the policy.
/// </param>
/// <param name='policy'>
/// A Policy.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Policy>> UpdateWithHttpMessagesAsync(string resourceGroupName, string labName, string policySetName, string name, PolicyFragment policy, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List policies in a given policy set.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Policy>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 43.84507 | 324 | 0.600707 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/devtestlabs/Microsoft.Azure.Management.DevTestLabs/src/Generated/IPoliciesOperations.cs | 9,339 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Blockchain.Models.Api20180601Preview
{
using Microsoft.Azure.PowerShell.Cmdlets.Blockchain.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="ResourceProviderOperationDisplay" />
/// </summary>
public partial class ResourceProviderOperationDisplayTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="ResourceProviderOperationDisplay"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="ResourceProviderOperationDisplay" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Blockchain.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Blockchain.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="ResourceProviderOperationDisplay" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="ResourceProviderOperationDisplay" />.</param>
/// <returns>
/// an instance of <see cref="ResourceProviderOperationDisplay" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Blockchain.Models.Api20180601Preview.IResourceProviderOperationDisplay ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Blockchain.Models.Api20180601Preview.IResourceProviderOperationDisplay).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return ResourceProviderOperationDisplay.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return ResourceProviderOperationDisplay.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return ResourceProviderOperationDisplay.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 52.950704 | 251 | 0.594494 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Blockchain/generated/api/Models/Api20180601Preview/ResourceProviderOperationDisplay.TypeConverter.cs | 7,378 | C# |
/*
Copyright 2013 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Logging;
using Google.Apis.Requests;
using Google.Apis.Services;
using Google.Apis.Util;
namespace Google.Apis.Download
{
/// <summary>
/// A media downloader implementation which handles media downloads. It supports downloading a media content in
/// chunks, when each chunk size is defined by <see cref="ChunkSize"/>.
/// </summary>
public class MediaDownloader : IMediaDownloader
{
private static readonly ILogger Logger = ApplicationContext.Logger.ForType<MediaDownloader>();
/// <summary>The service which this downloader belongs to.</summary>
private readonly IClientService service;
private const int MB = 0x100000;
/// <summary>Maximum chunk size. Default value is 10*MB.</summary>
public const int MaximumChunkSize = 10 * MB;
private int chunkSize = MaximumChunkSize;
/// <summary>
/// Gets or sets the size of each chunk to download from the server.
/// Chunks can't be set to be a value bigger than <see cref="MaximumChunkSize"/>. Default value is
/// <see cref="MaximumChunkSize"/>.
/// </summary>
public int ChunkSize
{
get { return chunkSize; }
set
{
if (value > MaximumChunkSize)
{
throw new ArgumentOutOfRangeException("ChunkSize");
}
chunkSize = value;
}
}
#region Progress
/// <summary>
/// Download progress model, which contains the status of the download, the amount of bytes whose where
/// downloaded so far, and an exception in case an error had occurred.
/// </summary>
private class DownloadProgress : IDownloadProgress
{
/// <summary>Constructs a new progress instance.</summary>
/// <param name="status">The status of the download.</param>
/// <param name="bytes">The number of bytes received so far.</param>
public DownloadProgress(DownloadStatus status, long bytes)
{
Status = status;
BytesDownloaded = bytes;
}
/// <summary>Constructs a new progress instance.</summary>
/// <param name="exception">An exception which occurred during the download.</param>
/// <param name="bytes">The number of bytes received before the exception occurred.</param>
public DownloadProgress(Exception exception, long bytes)
{
Status = DownloadStatus.Failed;
BytesDownloaded = bytes;
Exception = exception;
}
/// <summary>Gets or sets the status of the download.</summary>
public DownloadStatus Status { get; private set; }
/// <summary>Gets or sets the amount of bytes that have been downloaded so far.</summary>
public long BytesDownloaded { get; private set; }
/// <summary>Gets or sets the exception which occurred during the download or <c>null</c>.</summary>
public Exception Exception { get; private set; }
}
/// <summary>
/// Updates the current progress and call the <see cref="ProgressChanged"/> event to notify listeners.
/// </summary>
private void UpdateProgress(IDownloadProgress progress)
{
var changed = ProgressChanged;
if (changed != null)
{
changed(progress);
}
}
#endregion
/// <summary>Constructs a new downloader with the given client service.</summary>
public MediaDownloader(IClientService service)
{
this.service = service;
}
#region IMediaDownloader Overrides
public event Action<IDownloadProgress> ProgressChanged;
#region Download (sync and async)
public IDownloadProgress Download(string url, Stream stream)
{
return DownloadCoreAsync(url, stream, CancellationToken.None).Result;
}
public async Task<IDownloadProgress> DownloadAsync(string url, Stream stream)
{
return await DownloadAsync(url, stream, CancellationToken.None).ConfigureAwait(false);
}
public async Task<IDownloadProgress> DownloadAsync(string url, Stream stream,
CancellationToken cancellationToken)
{
return await DownloadCoreAsync(url, stream, cancellationToken).ConfigureAwait(false);
}
#endregion
#endregion
/// <summary>
/// The core download logic. It downloads the media in parts, where each part's size is defined by
/// <see cref="ChunkSize"/> (in bytes).
/// </summary>
/// <param name="url">The URL of the resource to download.</param>
/// <param name="stream">The download will download the resource into this stream.</param>
/// <param name="cancellationToken">A cancellation token to cancel this download in the middle.</param>
/// <returns>A task with the download progress object. If an exception occurred during the download, its
/// <see cref="IDownloadProgress.Exception "/> property will contain the exception.</returns>
private async Task<IDownloadProgress> DownloadCoreAsync(string url, Stream stream,
CancellationToken cancellationToken)
{
url.ThrowIfNull("url");
stream.ThrowIfNull("stream");
if (!stream.CanWrite)
{
throw new ArgumentException("stream doesn't support write operations");
}
RequestBuilder builder = null;
var uri = new Uri(url);
if (string.IsNullOrEmpty(uri.Query))
{
builder = new RequestBuilder() { BaseUri = new Uri(url) };
}
else
{
builder = new RequestBuilder() { BaseUri = new Uri(url.Substring(0, url.IndexOf("?"))) };
// Remove '?' at the beginning.
var query = uri.Query.Substring(1);
var pairs = from parameter in query.Split('&')
select parameter.Split('=');
// Add each query parameter. each pair contains the key [0] and then its value [1].
foreach (var p in pairs)
{
builder.AddParameter(RequestParameterType.Query, p[0], p[1]);
}
}
builder.AddParameter(RequestParameterType.Query, "alt", "media");
long currentRequestFirstBytePos = 0;
try
{
// This "infinite" loop stops when the "to" byte position in the "Content-Range" header is the last
// byte of the media ("length"-1 in the "Content-Range" header).
// e.g. "Content-Range: 200-299/300" - "to"(299) = "length"(300) - 1.
while (true)
{
var currentRequestLastBytePos = currentRequestFirstBytePos + ChunkSize - 1;
// Create the request and set the Range header.
var request = builder.CreateRequest();
request.Headers.Range = new RangeHeaderValue(currentRequestFirstBytePos,
currentRequestLastBytePos);
using (var response = await service.HttpClient.SendAsync(request, cancellationToken).
ConfigureAwait(false))
{
// Read the content and copy to the parameter's stream.
var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
responseStream.CopyTo(stream);
// Read the headers and check if all the media content was already downloaded.
var contentRange = response.Content.Headers.ContentRange;
long mediaContentLength;
if (contentRange == null)
{
// Content range is null when the server doesn't adhere the media download protocol, in
// that case we got all the media in one chunk.
currentRequestFirstBytePos = mediaContentLength =
response.Content.Headers.ContentLength.Value;
}
else
{
currentRequestFirstBytePos = contentRange.To.Value + 1;
mediaContentLength = contentRange.Length.Value;
}
if (currentRequestFirstBytePos == mediaContentLength)
{
var progress = new DownloadProgress(DownloadStatus.Completed, mediaContentLength);
UpdateProgress(progress);
return progress;
}
}
UpdateProgress(new DownloadProgress(DownloadStatus.Downloading, currentRequestFirstBytePos));
}
}
catch (TaskCanceledException ex)
{
Logger.Error(ex, "Download media was canceled");
UpdateProgress(new DownloadProgress(ex, currentRequestFirstBytePos));
throw ex;
}
catch (Exception ex)
{
Logger.Error(ex, "Exception occurred while downloading media");
var progress = new DownloadProgress(ex, currentRequestFirstBytePos);
UpdateProgress(progress);
return progress;
}
}
}
}
| 42.035019 | 117 | 0.562621 | [
"Apache-2.0"
] | DJJam/google-api-dotnet-client | Src/GoogleApis/Apis/[Media]/Download/MediaDownloader.cs | 10,805 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Kucoin.Utility;
using Kucoin.WebSocket.Events;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
namespace Kucoin.WebSocket
{
/// <summary>
/// A <see cref="IDepthWebSocketClient"/> implementation.
/// </summary>
public class DepthWebSocketClient : KucoinWebSocketClient<DepthUpdateEventArgs>, IDepthWebSocketClient
{
#region Public Events
public event EventHandler<DepthUpdateEventArgs> DepthUpdate;
#endregion Public Events
#region Constructors
/// <summary>
/// Default constructor provides default web socket stream, but no logging.
/// </summary>
public DepthWebSocketClient()
: this(new KucoinWebSocketStream())
{ }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="stream"></param>
/// <param name="logger"></param>
public DepthWebSocketClient(IWebSocketStream stream, ILogger<DepthWebSocketClient> logger = null)
: base(stream, logger)
{ }
#endregion Construtors
#region Public Methods
public virtual void Subscribe(string symbol, int limit, Action<DepthUpdateEventArgs> callback)
{
Throw.IfNullOrWhiteSpace(symbol, nameof(symbol));
symbol = symbol.FormatSymbol();
Logger?.LogDebug($"{nameof(DepthWebSocketClient)}.{nameof(Subscribe)}: \"{symbol}\" \"{limit}\" (callback: {(callback == null ? "no" : "yes")}). [thread: {Thread.CurrentThread.ManagedThreadId}]");
SubscribeStream(GetStreamName(symbol, limit), callback);
}
public virtual void Unsubscribe(string symbol, int limit, Action<DepthUpdateEventArgs> callback)
{
Throw.IfNullOrWhiteSpace(symbol, nameof(symbol));
symbol = symbol.FormatSymbol();
Logger?.LogDebug($"{nameof(DepthWebSocketClient)}.{nameof(Unsubscribe)}: \"{symbol}\" \"{limit}\" (callback: {(callback == null ? "no" : "yes")}). [thread: {Thread.CurrentThread.ManagedThreadId}]");
UnsubscribeStream(GetStreamName(symbol, limit), callback);
}
#endregion Public Methods
#region Protected Methods
protected override void OnWebSocketEvent(WebSocketStreamEventArgs args, IEnumerable<Action<DepthUpdateEventArgs>> callbacks)
{
Logger?.LogDebug($"{nameof(DepthWebSocketClient)}: \"{args.Json}\"");
try
{
var jObject = JObject.Parse(args.Json);
var eventType = jObject["e"]?.Value<string>();
DepthUpdateEventArgs eventArgs;
switch (eventType)
{
case null: // partial depth stream.
{
var symbol = args.StreamName.Split('@')[0].ToUpperInvariant();
// Simulate event time.
var eventTime = DateTime.UtcNow.ToTimestampK().ToDateTimeK();
var lastUpdateId = jObject["lastUpdateId"].Value<long>();
var bids = jObject["bids"].Select(entry => (entry[0].Value<decimal>(), entry[1].Value<decimal>())).ToArray();
var asks = jObject["asks"].Select(entry => (entry[0].Value<decimal>(), entry[1].Value<decimal>())).ToArray();
eventArgs = new DepthUpdateEventArgs(eventTime, args.Token, symbol, lastUpdateId, lastUpdateId, bids, asks);
break;
}
case "depthUpdate":
{
var symbol = jObject["s"].Value<string>();
var eventTime = jObject["E"].Value<long>().ToDateTimeK();
var firstUpdateId = jObject["U"].Value<long>();
var lastUpdateId = jObject["u"].Value<long>();
var bids = jObject["b"].Select(entry => (entry[0].Value<decimal>(), entry[1].Value<decimal>())).ToArray();
var asks = jObject["a"].Select(entry => (entry[0].Value<decimal>(), entry[1].Value<decimal>())).ToArray();
eventArgs = new DepthUpdateEventArgs(eventTime, args.Token, symbol, firstUpdateId, lastUpdateId, bids, asks);
break;
}
default:
Logger?.LogWarning($"{nameof(DepthWebSocketClient)}.{nameof(OnWebSocketEvent)}: Unexpected event type ({eventType}).");
return;
}
try
{
if (callbacks != null)
{
foreach (var callback in callbacks)
callback(eventArgs);
}
DepthUpdate?.Invoke(this, eventArgs);
}
catch (OperationCanceledException) { }
catch (Exception e)
{
if (!args.Token.IsCancellationRequested)
{
Logger?.LogError(e, $"{nameof(DepthWebSocketClient)}: Unhandled depth update event handler exception.");
}
}
}
catch (OperationCanceledException) { }
catch (Exception e)
{
if (!args.Token.IsCancellationRequested)
{
Logger?.LogError(e, $"{nameof(DepthWebSocketClient)}.{nameof(OnWebSocketEvent)}");
}
}
}
#endregion Protected Methods
#region Private Methods
private static string GetStreamName(string symbol, int limit)
=> limit > 0 ? $"{symbol.ToLowerInvariant()}@depth{limit}" : $"{symbol.ToLowerInvariant()}@depth";
#endregion Private Methods
}
}
| 38.133758 | 211 | 0.541173 | [
"MIT"
] | domibu/MarketTool | Kucoin/WebSocket/DepthWebSocketClient.cs | 5,989 | 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.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class EventDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<EventDeclarationSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
EventDeclarationSyntax eventDeclaration,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptions options,
CancellationToken cancellationToken)
{
CSharpStructureHelpers.CollectCommentBlockSpans(eventDeclaration, ref spans, options);
// fault tolerance
if (eventDeclaration.AccessorList == null ||
eventDeclaration.AccessorList.IsMissing ||
eventDeclaration.AccessorList.OpenBraceToken.IsMissing ||
eventDeclaration.AccessorList.CloseBraceToken.IsMissing)
{
return;
}
SyntaxNodeOrToken current = eventDeclaration;
var nextSibling = current.GetNextSibling();
// Check IsNode to compress blank lines after this node if it is the last child of the parent.
//
// Full events are grouped together with event field definitions in Metadata as Source.
var compressEmptyLines = options.IsMetadataAsSource
&& (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.EventDeclaration) || nextSibling.IsKind(SyntaxKind.EventFieldDeclaration));
spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan(
eventDeclaration,
eventDeclaration.Identifier,
compressEmptyLines: compressEmptyLines,
autoCollapse: true,
type: BlockTypes.Member,
isCollapsible: true));
}
}
}
| 42.509804 | 148 | 0.674354 | [
"MIT"
] | AlexanderSemenyak/roslyn | src/Features/CSharp/Portable/Structure/Providers/EventDeclarationStructureProvider.cs | 2,170 | C# |
using FakeXrmEasy;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Xrm.Sdk;
using System;
using System.Reflection;
using Abc.LuckyStar2.Shared;
using Abc.LuckyStar2.ProxyTypes;
using Abc.LuckyStar2.Plugin;
namespace Abc.LuckyStar2.PluginTest
{
[TestClass]
public class PostAccountUpdateAsynchronousTest
{
public static XrmFakedContext Context { get; set; }
public static XrmFakedPluginExecutionContext PluginContext { get; set; }
[ClassInitialize()]
public static void ClassInit(TestContext context)
{
Context = new XrmFakedContext();
Context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(ProxyTypesAssembly));
PluginContext = Context.GetDefaultPluginContext();
PluginContext.PrimaryEntityName = "plugin";
PluginContext.MessageName = "tUpdate";
PluginContext.Stage = (int)StageEnum.PostOperation;
PluginContext.Mode = (int)ExecutionModeEnum.Asynchronous;
PluginContext.InputParameters["Target"] = null;
}
/*
[TestMethod]
public void _00_UnsecureString_And_SecureString()
{
var target = new Entity("plugin")
{
["pluginid"] = Guid.NewGuid()
};
PluginContext.InputParameters["Target"] = target;
var unsecureString = "UnsecureString";
var secureString = "SecureString";
Context.ExecutePluginWithConfigurations<PostAccountUpdateAsynchronous>(PluginContext, unsecureString, secureString);
Assert.IsTrue(target != null);
}
*/
[TestMethod]
public void _01_Stage_Does_Not_Equals_PostOperation()
{
var context = new XrmFakedContext();
var plugin = context.GetDefaultPluginContext();
plugin.Stage = -1;
Assert.ThrowsException<InvalidPluginExecutionException>(() =>
{
context.ExecutePluginWith<PostAccountUpdateAsynchronous>(plugin);
}, "Stage does not equals PostOperation");
}
[TestMethod]
public void _02_PrimaryEntityName_Does_Not_Equals_plugin()
{
var context = new XrmFakedContext();
var plugin = context.GetDefaultPluginContext();
plugin.Stage = (int)StageEnum.PostOperation;
plugin.PrimaryEntityName = "abcd";
Assert.ThrowsException<InvalidPluginExecutionException>(() =>
{
context.ExecutePluginWith<PostAccountUpdateAsynchronous>(plugin);
}, "PrimaryEntityName does not equals plugin");
}
[TestMethod]
public void _03_MessageName_Does_Not_Equals_tUpdate()
{
var context = new XrmFakedContext();
var plugin = context.GetDefaultPluginContext();
plugin.Stage = (int)StageEnum.PostOperation;
plugin.PrimaryEntityName = "plugin";
plugin.MessageName = "abcd";
Assert.ThrowsException<InvalidPluginExecutionException>(() =>
{
context.ExecutePluginWith<PostAccountUpdateAsynchronous>(plugin);
}, "MessageName does not equals tUpdate");
}
[TestMethod]
public void _04_Mode_Does_Not_Equals_Asynchronous()
{
var context = new XrmFakedContext();
var plugin = context.GetDefaultPluginContext();
plugin.Stage = (int)StageEnum.PostOperation;
plugin.PrimaryEntityName = "plugin";
plugin.MessageName = "tUpdate";
plugin.Mode = -1;
Assert.ThrowsException<InvalidPluginExecutionException>(() =>
{
context.ExecutePluginWith<PostAccountUpdateAsynchronous>(plugin);
}, "Execution does not equals Asynchronous");
}
/*
[TestMethod]
public void _05_CrmPluginRegistration_Check()
{
var @class = new PostAccountUpdateAsynchronous();
foreach (var attribute in Attribute.GetCustomAttributes(@class.GetType()))
{
if (attribute.GetType().Equals(typeof(CrmPluginRegistrationAttribute)))
{
var check = attribute as CrmPluginRegistrationAttribute;
Assert.IsNotNull(check.Image1Attributes);
Assert.IsNotNull(check.Image1Name);
Assert.IsNotNull(check.Image1Type);
}
else
Assert.Fail();
}
}
*/
[TestMethod]
public void _06()
{
Assert.IsTrue(true);
}
}
}
| 36.890625 | 128 | 0.602499 | [
"MIT"
] | Kayserheimer/Dynamics-Crm-DevKit | test/v.2.10.31/Abc.LuckyStar2/Abc.LuckyStar2.Plugin.Test/PostAccountUpdateAsynchronousTest.cs | 4,724 | C# |
using System;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GRGcms.Common;
namespace GRGcms.Web.admin.manager
{
public partial class group_select : Web.UI.ManagePage
{
protected int totalCount;
protected int page;
protected int pageSize;
protected string keywords = string.Empty;
protected string ucode = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
this.keywords = DTRequest.GetQueryString("keywords");
this.ucode = DTRequest.GetQueryString("ucode");
this.pageSize = GetPageSize(10); //每页数量
if (!Page.IsPostBack)
{
ChkAdminLevel("manager_group", DTEnums.ActionEnum.View.ToString()); //检查权限
Model.user model = GetAdminInfo(); //取得当前管理员信息
RptBind("type='APP'" + CombSqlTxt(keywords), "createdTime desc");
}
}
#region 数据绑定=================================
private void RptBind(string _strWhere, string _orderby)
{
this.page = DTRequest.GetQueryInt("page", 1);
txtKeywords.Text = this.keywords;
BLL.group bll = new BLL.group();
this.rptList.DataSource = bll.GetList(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
this.rptList.DataBind();
//绑定页码
txtPageNum.Text = this.pageSize.ToString();
string pageUrl = Utils.CombUrlTxt("group_select.aspx", "ucode={0}&keywords={1}&page={2}",this.ucode,this.keywords, "__id__");
PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
}
#endregion
#region 组合SQL查询语句==========================
protected string CombSqlTxt(string _keywords)
{
StringBuilder strTemp = new StringBuilder();
_keywords = _keywords.Replace("'", "");
if (!string.IsNullOrEmpty(_keywords))
{
strTemp.Append("and discussionName like '%" + _keywords + "%'");
}
return strTemp.ToString();
}
#endregion
#region 返回每页数量=============================
private int GetPageSize(int _default_size)
{
int _pagesize;
if (int.TryParse(Utils.GetCookie("group_page_size", "GRGcmsPage"), out _pagesize))
{
if (_pagesize > 0)
{
return _pagesize;
}
}
return _default_size;
}
#endregion
//查询操作
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Redirect(Utils.CombUrlTxt("group_select.aspx", "ucode={0}&keywords={1}",this.ucode,txtKeywords.Text.Trim()));
}
//设置分页数量
protected void txtPageNum_TextChanged(object sender, EventArgs e)
{
int _pagesize;
if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
{
if (_pagesize > 0)
{
Utils.WriteCookie("group_select", "GRGcmsPage", _pagesize.ToString(), 14400);
}
}
Response.Redirect(Utils.CombUrlTxt("group_select.aspx", "ucode={0}&keywords={1}",this.ucode,this.keywords));
}
}
} | 36.229167 | 137 | 0.554054 | [
"MIT"
] | zengfanmao/mpds | LiveVideoSDK/VIMS.Cms/GRGcms.Web/admin/manager/group_select.aspx.cs | 3,574 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.